// chrome.jsx — Cursor follower + Theme toggle button.
// Both rely on the global applyTheme() + tokens already set on :root.

// ── CursorFollower ──────────────────────────────────────────────────────────
// Renders two layered dots: a small precise dot tracking the pointer exactly
// + a larger outline ring that lags behind. Grows when over interactive
// elements (a, button, [data-cursor="hover"]). Hidden on touch devices.
function CursorFollower() {
  React.useEffect(() => {
    if (matchMedia('(pointer: coarse)').matches) return;
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    const dot  = document.createElement('div');
    const ring = document.createElement('div');
    dot.className  = 'cursor-dot';
    ring.className = 'cursor-ring';
    dot.setAttribute('aria-hidden', 'true');
    ring.setAttribute('aria-hidden', 'true');
    document.body.appendChild(dot);
    document.body.appendChild(ring);

    let mx = window.innerWidth / 2, my = window.innerHeight / 2;
    let rx = mx, ry = my;
    let raf;

    const onMove = (e) => {
      mx = e.clientX; my = e.clientY;
      dot.style.transform  = `translate3d(${mx}px, ${my}px, 0) translate(-50%, -50%)`;
    };
    const tick = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      ring.style.transform = `translate3d(${rx.toFixed(2)}px, ${ry.toFixed(2)}px, 0) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();

    const onOver = (e) => {
      const t = e.target.closest('a, button, [data-cursor="hover"]');
      ring.classList.toggle('is-hover', !!t);
    };
    const onLeave = () => {
      dot.style.opacity = '0';
      ring.style.opacity = '0';
    };
    const onEnter = () => {
      dot.style.opacity = '1';
      ring.style.opacity = '1';
    };

    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseover', onOver);
    document.documentElement.addEventListener('mouseleave', onLeave);
    document.documentElement.addEventListener('mouseenter', onEnter);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseover', onOver);
      document.documentElement.removeEventListener('mouseleave', onLeave);
      document.documentElement.removeEventListener('mouseenter', onEnter);
      dot.remove(); ring.remove();
    };
  }, []);
  return null;
}

// ── ThemeToggle ─────────────────────────────────────────────────────────────
// Sun/moon icon that flips data-theme on <html> and persists the choice in
// localStorage. Reads initial state from <html data-theme="…">.
function ThemeToggle({ palette, onChange }) {
  const [mode, setMode] = React.useState(() => getCurrentMode());
  const toggle = () => {
    const next = mode === 'dark' ? 'light' : 'dark';
    setMode(next);
    applyTheme(palette, next);
    try { localStorage.setItem('mws-mode', next); } catch {}
    if (onChange) onChange(next);
  };
  // Sync if palette changes externally
  React.useEffect(() => { applyTheme(palette, mode); }, [palette, mode]);
  return (
    <button type="button" className="theme-toggle" onClick={toggle}
            aria-label={mode === 'dark' ? 'Passa a tema chiaro' : 'Passa a tema scuro'}>
      <span className="tt-icon tt-sun" aria-hidden>
        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
             strokeWidth="1.6" strokeLinecap="round">
          <circle cx="12" cy="12" r="4"/>
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
        </svg>
      </span>
      <span className="tt-icon tt-moon" aria-hidden>
        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
        </svg>
      </span>
      <span className="tt-thumb"/>
    </button>
  );
}

// ── CookieBanner ────────────────────────────────────────────────────────────
// GDPR-compliant banner. Appears on first visit, persists consent in
// localStorage under 'mws-cookie-consent'.
function CookieBanner() {
  const KEY = 'mws-cookie-consent';
  const [show, setShow] = React.useState(false);
  const [hiding, setHiding] = React.useState(false);

  React.useEffect(() => {
    try {
      if (!localStorage.getItem(KEY)) {
        const t = setTimeout(() => setShow(true), 700);
        return () => clearTimeout(t);
      }
    } catch {}
  }, []);

  const dismiss = (type) => {
    try {
      localStorage.setItem(KEY, JSON.stringify({ consent: type, ts: new Date().toISOString() }));
    } catch {}
    setHiding(true);
    setTimeout(() => setShow(false), 500);
  };

  if (!show) return null;

  const cls = ['cookie-banner', !hiding && 'is-visible', hiding && 'is-hiding']
    .filter(Boolean).join(' ');

  return (
    <div className={cls} role="dialog" aria-live="polite" aria-label="Consenso cookie">
      <div className="cookie-banner-icon" aria-hidden="true">🍪</div>
      <div className="cookie-banner-body">
        <p className="cookie-banner-title">Cookie &amp; Privacy</p>
        <p className="cookie-banner-text">
          Usiamo cookie tecnici essenziali e, con il tuo consenso, analytics
          anonimi per migliorare il sito.{' '}
          <a href="cookie.html">Cookie policy</a>
        </p>
      </div>
      <div className="cookie-banner-actions">
        <button className="cookie-btn-essential" onClick={() => dismiss('essential')}>
          Solo necessari
        </button>
        <button className="cookie-btn-accept" onClick={() => dismiss('all')}>
          Accetta tutti
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { CursorFollower, ThemeToggle, CookieBanner });
