/* global React */
/* =====================================================
   AccentPicker — temporary client-facing palette previewer.
   Floats bottom-right; rewrites :root --accent-* tokens
   in real time so the whole site retints. Selection
   persists across reloads via localStorage.

   TO REMOVE WHEN CLIENT PICKS A FINAL PALETTE:
     1. Delete this file (accent-picker.jsx).
     2. Drop the <script> tag for it from index.html.
     3. Drop <AccentPicker /> from app.jsx.
     4. Update the three --accent-* values at :root in styles.css
        to the chosen palette's hex codes.
   The token system itself stays — that's production color.
   ===================================================== */
const { useState: useAPState, useEffect: useAPEffect, useRef: useAPRef } = React;

const PALETTES = [
  {
    id: "federal-blue",
    label: "Federal Blue",
    main: "#3a7fc2",
    hover: "#2a629c",
    onDark: "#a8cef0",
  },
  {
    id: "heritage-gold",
    label: "Heritage Gold",
    main: "#b89048",
    hover: "#8c6c2e",
    onDark: "#e8d49a",
  },
  {
    id: "patriot-teal",
    label: "Patriot Teal",
    main: "#0e8c8a",
    hover: "#0a6d6b",
    onDark: "#7dd3d0",
  },
  {
    id: "silver",
    label: "Silver",
    main: "#8a93a3",       // slightly darker than #9ca3af so it reads on white
    hover: "#5d6573",
    onDark: "#e2e8f0",
  },
  {
    id: "bright-yellow",
    label: "Bright Yellow",
    // Client direction: one flat brightest-highlighter yellow across all
    // three roles, no nuance. Contrast on white is intentionally bad —
    // they want the highlighter look.
    main: "#fff200",
    hover: "#fff200",
    onDark: "#fff200",
  },
];

const STORAGE_KEY = "dcsmv-accent";

function hexToRgb(hex) {
  const m = hex.replace("#", "").match(/.{2}/g);
  return m ? m.map(p => parseInt(p, 16)).join(", ") : "0, 0, 0";
}

function applyPalette(p) {
  const r = document.documentElement;
  r.style.setProperty("--accent-main", p.main);
  r.style.setProperty("--accent-hover", p.hover);
  r.style.setProperty("--accent-on-dark", p.onDark);
  // RGB triplets for rgba() sites (halos, drop-shadows, alpha gradients).
  r.style.setProperty("--accent-main-rgb", hexToRgb(p.main));
  r.style.setProperty("--accent-on-dark-rgb", hexToRgb(p.onDark));
}

function AccentPicker() {
  const initial = (() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      const match = PALETTES.find(p => p.id === saved);
      return match || PALETTES[0];
    } catch (_) {
      return PALETTES[0];
    }
  })();

  const [active, setActive] = useAPState(initial);
  const [open, setOpen] = useAPState(false);
  const panelRef = useAPRef(null);

  // Apply on mount + whenever active changes
  useAPEffect(() => {
    applyPalette(active);
    try { localStorage.setItem(STORAGE_KEY, active.id); } catch (_) {}
  }, [active]);

  // Close on Escape or outside click
  useAPEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    const onClick = (e) => {
      if (panelRef.current && !panelRef.current.contains(e.target)) setOpen(false);
    };
    window.addEventListener("keydown", onKey);
    // Defer click listener a tick so the same click that opened the panel
    // doesn't immediately close it.
    const t = setTimeout(() => window.addEventListener("mousedown", onClick), 0);
    return () => {
      window.removeEventListener("keydown", onKey);
      clearTimeout(t);
      window.removeEventListener("mousedown", onClick);
    };
  }, [open]);

  return (
    <div className="accent-picker" ref={panelRef}>
      {open && (
        <div className="ap-panel" role="menu" aria-label="Accent palette">
          <div className="ap-panel-head">Accent palette</div>
          {PALETTES.map(p => {
            const isActive = p.id === active.id;
            return (
              <button
                key={p.id}
                type="button"
                role="menuitemradio"
                aria-checked={isActive}
                aria-pressed={isActive}
                className={`ap-row ${isActive ? "active" : ""}`}
                onClick={() => setActive(p)}
              >
                <span className="ap-swatches" aria-hidden="true">
                  <span className="ap-sw" style={{ background: p.main }}></span>
                  <span className="ap-sw" style={{ background: p.hover }}></span>
                  <span className="ap-sw" style={{ background: p.onDark }}></span>
                </span>
                <span className="ap-label">{p.label}</span>
                {isActive && (
                  <svg
                    className="ap-check"
                    viewBox="0 0 24 24"
                    width="14"
                    height="14"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.6"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    aria-hidden="true"
                  >
                    <polyline points="4 12 10 18 20 6" />
                  </svg>
                )}
              </button>
            );
          })}
          <div className="ap-foot">Preview only — temporary widget</div>
        </div>
      )}
      <button
        type="button"
        className="ap-toggle"
        aria-label={open ? "Close accent color picker" : "Change accent color"}
        aria-expanded={open}
        aria-haspopup="menu"
        onClick={() => setOpen(o => !o)}
      >
        <span className="ap-toggle-swatch" style={{ background: active.main }} aria-hidden="true"></span>
      </button>

      {/* Styles inlined so the whole widget is one file — deleting this
          jsx + its index.html script tag + the <AccentPicker /> mount
          removes every trace. */}
      <style dangerouslySetInnerHTML={{ __html: `
        .accent-picker {
          position: fixed;
          right: 24px;
          bottom: 24px;
          z-index: 9999;
          font-family: var(--font-body);
        }
        .ap-toggle {
          width: 48px; height: 48px;
          border-radius: 999px;
          border: 1.5px solid var(--ink-300);
          background: var(--white);
          padding: 0;
          display: grid; place-items: center;
          box-shadow: 0 10px 28px rgba(10, 23, 51, 0.18), 0 2px 6px rgba(10, 23, 51, 0.08);
          cursor: pointer;
          transition: transform .15s ease, box-shadow .15s ease;
        }
        .ap-toggle:hover { transform: translateY(-1px); box-shadow: 0 14px 36px rgba(10, 23, 51, 0.22), 0 2px 6px rgba(10, 23, 51, 0.08); }
        .ap-toggle:focus-visible { outline: 3px solid var(--gold); outline-offset: 2px; }
        .ap-toggle-swatch {
          width: 28px; height: 28px;
          border-radius: 999px;
          border: 1.5px solid rgba(10, 23, 51, 0.12);
          display: block;
        }
        .ap-panel {
          position: absolute;
          right: 0;
          bottom: 60px;
          width: 280px;
          background: var(--white);
          border: 1.5px solid var(--ink-300);
          border-radius: var(--r-md);
          box-shadow: 0 24px 48px rgba(10, 23, 51, 0.18), 0 4px 10px rgba(10, 23, 51, 0.06);
          padding: 8px;
          display: flex;
          flex-direction: column;
          gap: 2px;
        }
        .ap-panel-head {
          font-size: 11px;
          font-weight: 700;
          letter-spacing: 0.16em;
          text-transform: uppercase;
          color: var(--ink-500);
          padding: 10px 12px 6px;
        }
        .ap-row {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 10px 12px;
          border: 0;
          background: transparent;
          border-radius: var(--r-sm);
          cursor: pointer;
          text-align: left;
          color: var(--ink-900);
          font-size: 14px;
          font-weight: 600;
          font-family: inherit;
          transition: background .12s ease;
        }
        .ap-row:hover { background: var(--off-white); }
        .ap-row.active { background: rgba(10, 23, 51, 0.05); }
        .ap-row:focus-visible { outline: 2px solid var(--gold); outline-offset: -2px; }
        .ap-swatches {
          display: inline-flex;
          gap: 3px;
          flex-shrink: 0;
        }
        .ap-sw {
          width: 14px; height: 22px;
          border-radius: 2px;
          border: 1px solid rgba(10, 23, 51, 0.1);
        }
        .ap-label { flex: 1; }
        .ap-check { color: var(--navy-900); flex-shrink: 0; }
        .ap-foot {
          font-size: 10px;
          letter-spacing: 0.1em;
          text-transform: uppercase;
          color: var(--ink-500);
          padding: 8px 12px 4px;
          border-top: 1px solid var(--ink-300);
          margin-top: 4px;
          text-align: center;
        }
        @media (max-width: 540px) {
          .accent-picker { right: 16px; bottom: 16px; }
          .ap-panel { width: 260px; }
        }
      `}} />
    </div>
  );
}

Object.assign(window, { AccentPicker });
