/* global React */
const { useState: useStateCk, useEffect: useEffectCk, useRef: useRefCk } = React;

/* ----------------------------------------------------------------- */
/*  ASPACE — Cookie Consent System                                    */
/*  - Floating editorial consent card                                 */
/*  - Premium preferences modal                                       */
/* ----------------------------------------------------------------- */

const STORAGE_KEY = 'aspace.consent.v1';
const CATEGORY_KEYS = [
  { key: 'necessary',  required: true  },
  { key: 'analytics',  required: false },
  { key: 'functional', required: false },
  { key: 'marketing',  required: false },
];

function readConsent() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null'); } catch { return null; }
}
function writeConsent(state) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...state, ts: Date.now() })); } catch {}
  window.dispatchEvent(new CustomEvent('aspace:consent', { detail: state }));
}

/* ----------------------------- BANNER ---------------------------- */
function CookieBanner() {
  const t = (window.useT && window.useT()) || ((k) => k);
  const [visible, setVisible] = useStateCk(false);
  const [prefsOpen, setPrefsOpen] = useStateCk(false);
  const [mounted, setMounted] = useStateCk(false);

  useEffectCk(() => {
    const existing = readConsent();
    if (!existing) {
      const t = setTimeout(() => { setVisible(true); setTimeout(() => setMounted(true), 30); }, 800);
      return () => clearTimeout(t);
    }
  }, []);

  useEffectCk(() => {
    const onOpen = () => { setPrefsOpen(true); };
    window.addEventListener('aspace:open-cookie-prefs', onOpen);
    return () => window.removeEventListener('aspace:open-cookie-prefs', onOpen);
  }, []);

  const acceptAll = () => {
    writeConsent({ necessary: true, analytics: true, functional: true, marketing: true });
    setMounted(false); setTimeout(() => setVisible(false), 480);
  };
  const onlyNecessary = () => {
    writeConsent({ necessary: true, analytics: false, functional: false, marketing: false });
    setMounted(false); setTimeout(() => setVisible(false), 480);
  };

  return (
    <React.Fragment>
      {visible && (
        <div role="dialog" aria-label={t('cookie.bannerAria')} style={{
          position: 'fixed',
          left: 'clamp(16px, 2vw, 32px)',
          bottom: 'clamp(16px, 2vw, 32px)',
          zIndex: 9300,
          maxWidth: 'min(440px, calc(100vw - 32px))',
          opacity: mounted ? 1 : 0,
          transform: mounted ? 'translateY(0) scale(1)' : 'translateY(20px) scale(0.97)',
          transition: 'opacity 600ms cubic-bezier(0.22,1,0.36,1), transform 720ms cubic-bezier(0.22,1.2,0.36,1)',
        }}>
          <div style={{
            position: 'relative',
            padding: 'clamp(22px, 2.4vw, 30px)',
            borderRadius: 'clamp(20px, 2vw, 26px)',
            background: 'rgba(244,242,236,0.94)',
            backdropFilter: 'blur(28px) saturate(140%)',
            WebkitBackdropFilter: 'blur(28px) saturate(140%)',
            border: '1px solid rgba(255,255,255,0.6)',
            boxShadow: '0 30px 80px -28px rgba(0,0,0,0.32), 0 8px 24px -10px rgba(0,0,0,0.14), inset 0 1px 0 rgba(255,255,255,0.6)',
            color: '#0A0A0B',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase',
              color: 'rgba(10,10,11,0.55)', marginBottom: 16,
            }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--aspace-blue)' }}/>
              <span>{t('cookie.eyebrowLeft')}</span>
              <span style={{ flex: 1, height: 1, background: 'rgba(10,10,11,0.16)' }}/>
              <span>{t('cookie.eyebrowRight')}</span>
            </div>

            <div style={{
              fontFamily: "'Inter Tight',sans-serif", fontWeight: 500,
              fontSize: 'clamp(20px, 1.8vw, 24px)',
              letterSpacing: '-0.018em', lineHeight: 1.18,
              marginBottom: 12,
            }}>
              {t('cookie.headline')}
            </div>

            <p style={{
              fontSize: 13.5, lineHeight: 1.55,
              color: 'rgba(10,10,11,0.65)',
              margin: '0 0 22px',
            }}>
              {t('cookie.copy')}
            </p>

            <div style={{ display: 'grid', gap: 10 }}>
              <button onClick={acceptAll} className="ck-btn ck-primary">
                <span>{t('cookie.acceptAll')}</span>
                <span className="ck-arrow">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
                </span>
              </button>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <button onClick={() => setPrefsOpen(true)} className="ck-btn ck-ghost">{t('cookie.customize')}</button>
                <button onClick={onlyNecessary} className="ck-btn ck-ghost">{t('cookie.necessary')}</button>
              </div>
            </div>

            <div style={{
              marginTop: 16, paddingTop: 14,
              borderTop: '1px solid rgba(10,10,11,0.10)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              fontSize: 11, letterSpacing: '0.06em',
              color: 'rgba(10,10,11,0.45)',
            }}>
              <a href="cookies.html" style={{ color: 'inherit', textDecoration: 'none' }}>{t('cookie.linkPolicy')}</a>
              <a href="privacy.html" style={{ color: 'inherit', textDecoration: 'none' }}>{t('cookie.linkPrivacy')}</a>
            </div>
          </div>
        </div>
      )}

      <CookiePrefsModal open={prefsOpen} onClose={() => setPrefsOpen(false)} onSaved={() => { setMounted(false); setTimeout(() => setVisible(false), 480); }} />

      <style>{`
        .ck-btn {
          all: unset; cursor: pointer;
          display: inline-flex; align-items: center; justify-content: center; gap: 10px;
          padding: 14px 20px;
          border-radius: 999px;
          font-family: 'Inter Tight', sans-serif;
          font-weight: 500; font-size: 14px;
          text-align: center;
          transition: transform 300ms cubic-bezier(0.22,1.2,0.36,1), background 280ms ease, color 280ms ease, border-color 280ms ease;
        }
        .ck-btn:hover { transform: translateY(-1px); }
        .ck-primary { background: #0A0A0B; color: #fff; padding-right: 8px; }
        .ck-primary .ck-arrow {
          width: 32px; height: 32px; border-radius: 50%;
          background: var(--aspace-blue); color: #000;
          display: inline-flex; align-items: center; justify-content: center;
          margin-left: 4px; transition: transform 300ms cubic-bezier(0.22,1.2,0.36,1);
        }
        .ck-primary:hover .ck-arrow { transform: rotate(-45deg); }
        .ck-ghost {
          background: rgba(10,10,11,0.04);
          border: 1px solid rgba(10,10,11,0.10);
          color: #0A0A0B;
        }
        .ck-ghost:hover {
          background: #0A0A0B; color: #fff; border-color: #0A0A0B;
        }
      `}</style>
    </React.Fragment>
  );
}

/* --------------------- PREFERENCES MODAL ----------------------- */
function CookiePrefsModal({ open, onClose, onSaved }) {
  const t = (window.useT && window.useT()) || ((k) => k);
  const [state, setState] = useStateCk(() => {
    const existing = readConsent();
    return existing || { necessary: true, analytics: false, functional: false, marketing: false };
  });
  const [mounted, setMounted] = useStateCk(false);

  useEffectCk(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      setTimeout(() => setMounted(true), 30);
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      window.addEventListener('keydown', onKey);
      return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
    } else {
      setMounted(false);
    }
  }, [open, onClose]);

  if (!open && !mounted) return null;

  const save = () => {
    writeConsent(state);
    onClose();
    onSaved && onSaved();
  };
  const acceptAll = () => {
    const all = { necessary: true, analytics: true, functional: true, marketing: true };
    setState(all); writeConsent(all); onClose(); onSaved && onSaved();
  };

  return (
    <React.Fragment>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 9750,
        background: 'rgba(10,10,11,0.45)',
        backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
        opacity: mounted ? 1 : 0,
        transition: 'opacity 600ms cubic-bezier(0.22,1,0.36,1)',
      }}/>
      <div role="dialog" aria-modal="true" style={{
        position: 'fixed', zIndex: 9760,
        left: '50%', top: '50%',
        transform: `translate(-50%, ${mounted ? '-50%' : 'calc(-50% + 24px)'}) scale(${mounted ? 1 : 0.97})`,
        opacity: mounted ? 1 : 0,
        width: 'min(640px, calc(100vw - 24px))',
        maxHeight: 'calc(100vh - 48px)',
        display: 'flex', flexDirection: 'column',
        background: '#F4F2EC',
        borderRadius: 'clamp(20px, 2vw, 26px)',
        overflow: 'hidden',
        boxShadow: '0 50px 120px -30px rgba(0,0,0,0.5), 0 20px 50px -20px rgba(0,0,0,0.2)',
        transition: 'opacity 600ms ease, transform 720ms cubic-bezier(0.22,1.2,0.36,1)',
      }}>
        <header style={{
          padding: 'clamp(22px, 2.4vw, 32px) clamp(24px, 3vw, 36px)',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 20,
          borderBottom: '1px solid rgba(10,10,11,0.10)',
        }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'rgba(10,10,11,0.55)', marginBottom: 10 }}>{t('cookie.prefs.eyebrow')}</div>
            <div style={{ fontFamily: "'Inter Tight',sans-serif", fontWeight: 500, fontSize: 'clamp(24px, 2.2vw, 30px)', letterSpacing: '-0.02em', lineHeight: 1.1 }}>
              {t('cookie.prefs.heading')}
            </div>
          </div>
          <button onClick={onClose} aria-label={t('cookie.prefs.closeAria')} style={{
            all: 'unset', cursor: 'pointer', flexShrink: 0,
            width: 36, height: 36, borderRadius: '50%',
            border: '1px solid rgba(10,10,11,0.18)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M6 6l12 12M18 6L6 18"/></svg>
          </button>
        </header>

        <div style={{ flex: 1, overflowY: 'auto', padding: 'clamp(8px, 1vw, 16px) clamp(24px, 3vw, 36px)' }}>
          {CATEGORY_KEYS.map(cat => {
            const c = t('cookie.cats.' + cat.key) || {};
            return (
            <div key={cat.key} style={{
              padding: 'clamp(20px, 2vw, 26px) 0',
              borderBottom: '1px solid rgba(10,10,11,0.10)',
              display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'start',
            }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <div style={{ fontFamily: "'Inter Tight',sans-serif", fontWeight: 500, fontSize: 18, letterSpacing: '-0.01em' }}>{c.label}</div>
                  {cat.required && (
                    <span style={{ fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(10,10,11,0.55)', padding: '3px 8px', border: '1px solid rgba(10,10,11,0.18)', borderRadius: 99 }}>{t('cookie.prefs.alwaysOn')}</span>
                  )}
                </div>
                <div style={{ fontSize: 13.5, lineHeight: 1.55, color: 'rgba(10,10,11,0.6)', maxWidth: 440 }}>{c.d}</div>
              </div>
              <Switch
                disabled={cat.required}
                value={cat.required ? true : state[cat.key]}
                onChange={(v) => setState(s => ({ ...s, [cat.key]: v }))}
              />
            </div>
            );
          })}
        </div>

        <footer style={{
          padding: 'clamp(18px, 2vw, 24px) clamp(24px, 3vw, 36px)',
          borderTop: '1px solid rgba(10,10,11,0.10)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap',
        }}>
          <button onClick={save} className="ck-btn ck-ghost">{t('cookie.prefs.save')}</button>
          <button onClick={acceptAll} className="ck-btn ck-primary">
            <span>{t('cookie.prefs.acceptAll')}</span>
            <span className="ck-arrow">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </span>
          </button>
        </footer>
      </div>
    </React.Fragment>
  );
}

function Switch({ value, onChange, disabled }) {
  return (
    <button
      role="switch"
      aria-checked={value}
      disabled={disabled}
      onClick={() => !disabled && onChange(!value)}
      style={{
        all: 'unset',
        cursor: disabled ? 'default' : 'pointer',
        position: 'relative',
        width: 52, height: 30,
        borderRadius: 999,
        background: value ? 'var(--aspace-blue)' : 'rgba(10,10,11,0.16)',
        opacity: disabled ? 0.55 : 1,
        transition: 'background 360ms cubic-bezier(0.22,1,0.36,1)',
      }}
    >
      <span style={{
        position: 'absolute', top: 3, left: value ? 25 : 3,
        width: 24, height: 24, borderRadius: '50%',
        background: '#fff',
        boxShadow: '0 2px 6px rgba(0,0,0,0.18)',
        transition: 'left 360ms cubic-bezier(0.22,1.2,0.36,1)',
      }}/>
    </button>
  );
}

window.CookieBanner = CookieBanner;
window.openCookiePrefs = () => window.dispatchEvent(new CustomEvent('aspace:open-cookie-prefs'));
