// ============================================================
// COOKIE BANNER — Lumikode
// ============================================================
// Banner GDPR-style. Persiste la scelta in localStorage.
// Auto-monta in #cookie-banner-root (creato al volo).
//
// Esposto su window per uso futuro:
//   window.lumikodeCookieConsent.get()  -> 'all' | 'essential' | null
//   window.lumikodeCookieConsent.reset() -> riapre il banner
// ============================================================

(function setupCookieBanner() {
  const STORAGE_KEY = 'lumikode_cookie_consent_v1';

  const cookieAPI = {
    get() { try { return localStorage.getItem(STORAGE_KEY); } catch (e) { return null; } },
    set(v) { try { localStorage.setItem(STORAGE_KEY, v); } catch (e) {} },
    reset() { try { localStorage.removeItem(STORAGE_KEY); location.reload(); } catch (e) {} },
  };
  window.lumikodeCookieConsent = cookieAPI;

  function CookieBanner() {
    const { useState, useEffect } = React;
    const motion = (window.FramerMotion && window.FramerMotion.motion) || { div: 'div' };
    const AnimatePresence = (window.FramerMotion && window.FramerMotion.AnimatePresence) || (({ children }) => children);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
      // Mostra solo se non c'è ancora una scelta
      if (!cookieAPI.get()) {
        const t = setTimeout(() => setVisible(true), 800);
        return () => clearTimeout(t);
      }
    }, []);

    function choose(value) {
      cookieAPI.set(value);
      setVisible(false);
    }

    const palette = (window.colors) || {
      brandGold: '#c9a84c',
      brandGoldMuted: '#8b7635',
      bgPrimary: '#0a0a14',
      textPrimary: '#f5f1e6',
      textMuted: 'rgba(245,241,230,0.65)',
      textDim: 'rgba(245,241,230,0.4)',
    };

    return (
      <AnimatePresence>
        {visible && (
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 30 }}
            transition={{ duration: 0.4, ease: 'easeOut' }}
            style={{
              position: 'fixed',
              bottom: 20,
              left: 20,
              right: 20,
              maxWidth: 560,
              marginLeft: 'auto',
              marginRight: 'auto',
              zIndex: 9999,
              padding: '20px 22px',
              background: 'linear-gradient(155deg, rgba(15,15,20,0.98), rgba(8,8,15,0.98))',
              border: `1px solid ${palette.brandGold}55`,
              borderRadius: 12,
              boxShadow: `0 12px 40px rgba(0,0,0,0.6), 0 0 30px ${palette.brandGold}15`,
              backdropFilter: 'blur(12px)',
              WebkitBackdropFilter: 'blur(12px)',
              fontFamily: "'DM Sans', sans-serif",
            }}
          >
            <div style={{
              fontFamily: "'Courier Prime', monospace",
              fontSize: '0.62rem',
              color: palette.brandGold,
              letterSpacing: 2,
              fontWeight: 700,
              marginBottom: 8,
              textTransform: 'uppercase',
            }}>
              ◢ Cookie & Privacy
            </div>
            <p style={{
              fontSize: '0.85rem',
              color: palette.textMuted,
              lineHeight: 1.6,
              fontWeight: 300,
              margin: 0,
              marginBottom: 16,
            }}>
              Usiamo solo cookie tecnici necessari al funzionamento del sito.
              Nessun tracker pubblicitario, nessuna profilazione.
              {' '}
              <a href="#" onClick={(e) => e.preventDefault()} style={{
                color: palette.brandGold,
                textDecoration: 'none',
                borderBottom: `1px dotted ${palette.brandGold}`,
              }}>Privacy policy</a>.
            </p>
            <div style={{
              display: 'flex',
              gap: 10,
              flexWrap: 'wrap',
            }}>
              <button
                onClick={() => choose('essential')}
                style={{
                  padding: '9px 16px',
                  background: 'transparent',
                  border: `1px solid ${palette.brandGold}40`,
                  color: palette.textPrimary,
                  fontFamily: "'DM Sans', sans-serif",
                  fontSize: '0.78rem',
                  fontWeight: 500,
                  letterSpacing: 0.5,
                  borderRadius: 6,
                  cursor: 'pointer',
                  transition: 'all 0.2s',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = palette.brandGold;
                  e.currentTarget.style.background = `${palette.brandGold}10`;
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = `${palette.brandGold}40`;
                  e.currentTarget.style.background = 'transparent';
                }}
              >
                Solo essenziali
              </button>
              <button
                onClick={() => choose('all')}
                style={{
                  padding: '9px 18px',
                  background: `linear-gradient(135deg, ${palette.brandGold}, ${palette.brandGoldMuted})`,
                  border: 'none',
                  color: '#0a0a14',
                  fontFamily: "'DM Sans', sans-serif",
                  fontSize: '0.78rem',
                  fontWeight: 700,
                  letterSpacing: 0.5,
                  borderRadius: 6,
                  cursor: 'pointer',
                  transition: 'all 0.2s',
                  boxShadow: `0 0 20px ${palette.brandGold}30`,
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-1px)';
                  e.currentTarget.style.boxShadow = `0 0 28px ${palette.brandGold}50`;
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = `0 0 20px ${palette.brandGold}30`;
                }}
              >
                Accetta tutto
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    );
  }

  function mount() {
    const ready = window.React && window.ReactDOM && window.ReactDOM.createRoot;
    if (!ready) return setTimeout(mount, 60);

    if (document.getElementById('cookie-banner-root')) return;
    const host = document.createElement('div');
    host.id = 'cookie-banner-root';
    document.body.appendChild(host);
    ReactDOM.createRoot(host).render(<CookieBanner />);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mount);
  } else {
    mount();
  }
})();
