"use client"

import { useEffect, useRef, useState } from "react"
import { Palette } from "lucide-react"

const STORAGE_KEY = "valabel-colors"

const VARS = [
  { key: "bg", label: "Fond", cssVar: "--bg" },
  { key: "text", label: "Texte", cssVar: "--text" },
  { key: "accent", label: "Accent", cssVar: "--accent" },
] as const

type ColorKey = (typeof VARS)[number]["key"]
type ColorState = Partial<Record<ColorKey, string>>

function readStored(): ColorState {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? (JSON.parse(raw) as ColorState) : {}
  } catch {
    return {}
  }
}

function applyColors(colors: ColorState) {
  const root = document.documentElement
  for (const { key, cssVar } of VARS) {
    const v = colors[key]
    if (v) root.style.setProperty(cssVar, v)
    else root.style.removeProperty(cssVar)
  }
}

function readDefaults(): ColorState {
  if (typeof document === "undefined") return {}
  const computed = getComputedStyle(document.documentElement)
  const d: ColorState = {}
  for (const { key, cssVar } of VARS) {
    d[key] = computed.getPropertyValue(cssVar).trim() || "#000000"
  }
  return d
}

// Les 3 couleurs de marque (fond, texte, accent) — personnalisables et
// mémorisées en localStorage. Un override inline sur <html> prime sur le
// thème clair/sombre, quel que soit celui-ci.
export function ColorPickerToggle({ className }: { className?: string }) {
  const [open, setOpen] = useState(false)
  const [colors, setColors] = useState<ColorState>(() =>
    typeof window === "undefined" ? {} : readStored()
  )
  const [defaults] = useState<ColorState>(readDefaults)
  const popRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (popRef.current && !popRef.current.contains(e.target as Node)) setOpen(false)
    }
    if (open) document.addEventListener("mousedown", onClickOutside)
    return () => document.removeEventListener("mousedown", onClickOutside)
  }, [open])

  function update(key: ColorKey, value: string) {
    const next = { ...colors, [key]: value }
    setColors(next)
    applyColors(next)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
  }

  function reset() {
    setColors({})
    applyColors({})
    localStorage.removeItem(STORAGE_KEY)
  }

  return (
    <div className={`relative ${className ?? ""}`} ref={popRef}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-label="Personnaliser les couleurs du site"
        className="inline-flex items-center justify-center h-10 w-10 border border-[var(--border)] text-[var(--text-secondary)] hover:text-[var(--text)] hover:border-[var(--border-subtle)] transition-colors"
      >
        <Palette className="h-4 w-4" />
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-56 border border-[var(--border)] bg-[var(--surface)] p-4 shadow-2xl z-40">
          <p className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mb-3">
            Couleurs du site
          </p>
          <div className="space-y-3">
            {VARS.map((v) => (
              <label
                key={v.key}
                className="flex items-center justify-between gap-3 text-sm text-[var(--text-secondary)]"
              >
                {v.label}
                <input
                  type="color"
                  value={colors[v.key] ?? defaults[v.key] ?? "#000000"}
                  onChange={(e) => update(v.key, e.target.value)}
                  className="h-7 w-10 cursor-pointer border border-[var(--border)] bg-transparent p-0"
                />
              </label>
            ))}
          </div>
          <button
            type="button"
            onClick={reset}
            className="mt-4 font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] hover:text-[var(--text)] transition-colors"
          >
            Réinitialiser
          </button>
        </div>
      )}
    </div>
  )
}
