/* Legal pages, the consent banner and the cookie switches. The consent core
   (consent.js) owns storage and gtag; everything here is presentation. */

const legalMono = { fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: '0.08em', textTransform: 'uppercase' };
const legalPill = { ...legalMono, fontSize: 10.5, border: 'none', borderRadius: 999, padding: '11px 20px', cursor: 'pointer', transition: 'background .25s ease, color .25s ease, border-color .25s ease' };

function LegalToggle({ on, locked, onChange, label }) {
  return (
    <button role="switch" aria-checked={on} aria-label={label} disabled={locked} onClick={() => !locked && onChange(!on)}
      style={{ width: 42, height: 24, borderRadius: 999, border: 'none', padding: 2, cursor: locked ? 'default' : 'pointer', flexShrink: 0, background: on ? 'var(--orange-500)' : 'var(--gray-300)', opacity: locked ? 0.55 : 1, transition: 'background .25s ease' }}>
      <span style={{ display: 'block', width: 20, height: 20, borderRadius: '50%', background: 'var(--white)', transform: on ? 'translateX(18px)' : 'none', transition: 'transform .25s cubic-bezier(.22,1,.36,1)' }} />
    </button>
  );
}

function CookieControls({ l, onDone }) {
  const c = l.cookiesUI;
  const stored = window.smConsent.get();
  const [an, setAn] = React.useState(stored ? !!stored.analytics : false);
  const [mk, setMk] = React.useState(stored ? !!stored.marketing : false);
  const [saved, setSaved] = React.useState(false);
  const [erased, setErased] = React.useState(false);
  /* Choice made - flash the confirmation, then send them back to the page
     they came for. Staying on a settings page after saving is a dead end. */
  const apply = (a, m) => {
    window.smConsent.save({ analytics: a, marketing: m });
    setAn(a); setMk(m); setSaved(true);
    setTimeout(() => { setSaved(false); if (onDone) onDone(); }, 900);
  };
  const rows = [
    { name: c.necessary, body: c.necessaryBody, on: true, locked: true },
    { name: c.analytics, body: c.analyticsBody, on: an, locked: false, set: setAn },
    { name: c.marketing, body: c.marketingBody, on: mk, locked: false, set: setMk },
  ];
  return (
    <div style={{ margin: '34px 0 8px' }}>
      {rows.map((r) => (
        <div key={r.name} style={{ display: 'flex', alignItems: 'flex-start', gap: 20, padding: '18px 0', borderTop: '1.5px solid var(--gray-200)' }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: '-0.01em', color: 'var(--black)' }}>{r.name}</div>
            <p style={{ margin: '6px 0 0', fontFamily: 'var(--font-body)', fontSize: 14.5, lineHeight: 1.6, color: 'var(--gray-600)', maxWidth: '58ch' }}>{r.body}</p>
          </div>
          <LegalToggle on={r.on} locked={r.locked} onChange={(v) => r.set(v)} label={r.name} />
        </div>
      ))}
      <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 10, paddingTop: 22, borderTop: '1.5px solid var(--gray-200)' }}>
        <button onClick={() => apply(an, mk)} style={{ ...legalPill, background: 'var(--black)', color: 'var(--white)' }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--orange-500)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--black)'; }}>{c.save}</button>
        <button onClick={() => apply(true, true)} style={{ ...legalPill, background: 'transparent', color: 'var(--black)', boxShadow: 'inset 0 0 0 1.5px var(--gray-300)' }}>{c.acceptAll}</button>
        <button onClick={() => apply(false, false)} style={{ ...legalPill, background: 'transparent', color: 'var(--gray-600)', boxShadow: 'inset 0 0 0 1.5px var(--gray-300)' }}>{c.onlyNecessary}</button>
        <span aria-live="polite" style={{ ...legalMono, color: saved ? 'var(--orange-600)' : 'transparent', transition: 'color .3s ease' }}>{c.saved}</span>
      </div>
      {stored && stored.id && (
        <p style={{ ...legalMono, margin: '18px 0 0', color: 'var(--gray-500)' }}>
          {c.idLabel} {stored.id} · {c.choiceLabel} {new Date(stored.ts).toLocaleDateString()}
        </p>
      )}
      {/* GDPR access and erasure, self-service. The site keeps no server-side
          record, so the browser copy IS the complete dataset - download hands
          it over as JSON, erase wipes it and the banner returns. */}
      <div style={{ marginTop: 40, paddingTop: 22, borderTop: '1.5px solid var(--gray-200)' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: '-0.01em', color: 'var(--black)' }}>{c.dataTitle}</div>
        <p style={{ margin: '8px 0 16px', fontFamily: 'var(--font-body)', fontSize: 14.5, lineHeight: 1.6, color: 'var(--gray-600)', maxWidth: '58ch' }}>{c.dataBody}</p>
        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
          <button onClick={() => {
            const rec = window.smConsent.get();
            const blob = new Blob([JSON.stringify({ site: 'sevcikmarketing.com', exported: new Date().toISOString(), consentRecord: rec || null, note: 'This is the complete set of data this site stores about this browser.' }, null, 2)], { type: 'application/json' });
            const a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = 'sevcikmarketing-my-data.json';
            a.click();
            setTimeout(() => URL.revokeObjectURL(a.href), 4000);
          }} style={{ ...legalPill, background: 'transparent', color: 'var(--black)', boxShadow: 'inset 0 0 0 1.5px var(--gray-300)' }}>{c.download}</button>
          <button onClick={() => { window.smConsent.reset(); setAn(false); setMk(false); setErased(true); setTimeout(() => setErased(false), 2400); }}
            style={{ ...legalPill, background: 'transparent', color: 'var(--gray-600)', boxShadow: 'inset 0 0 0 1.5px var(--gray-300)' }}
            onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--orange-600)'; e.currentTarget.style.boxShadow = 'inset 0 0 0 1.5px var(--orange-500)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--gray-600)'; e.currentTarget.style.boxShadow = 'inset 0 0 0 1.5px var(--gray-300)'; }}>{c.erase}</button>
          <span aria-live="polite" style={{ ...legalMono, color: erased ? 'var(--orange-600)' : 'transparent', transition: 'color .3s ease' }}>{c.erased}</span>
        </div>
      </div>
    </div>
  );
}

function LegalLayer({ doc, t, onBack, children }) {
  return (
    <div className="sm-screen-layer" style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'var(--paper)', overflowY: 'auto' }}>
      <div style={{ maxWidth: 820, margin: '0 auto', padding: 'clamp(24px, 4vw, 56px) clamp(20px, 4vw, 40px) 120px' }}>
        <button onClick={onBack} style={{ ...legalMono, background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--gray-600)' }}
          onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--orange-600)'; }} onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--gray-600)'; }}>← {t.backHome}</button>
        <div style={{ ...legalMono, marginTop: 'clamp(28px, 5vh, 52px)', color: 'var(--orange-600)' }}>{doc.kicker}</div>
        <h1 style={{ margin: '14px 0 0', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(30px, 4vw, 46px)', lineHeight: 1.05, letterSpacing: '-0.03em', color: 'var(--black)' }}>{doc.title}</h1>
        <p style={{ ...legalMono, margin: '16px 0 0', color: 'var(--gray-500)' }}>{doc.updated}</p>
        {doc.intro && <p style={{ margin: '22px 0 0', maxWidth: '62ch', fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 18, lineHeight: 1.5, color: 'var(--gray-700)', textWrap: 'pretty' }}>{doc.intro}</p>}
        {children}
        <div style={{ marginTop: 38 }}>
          {doc.sections.map(([h, ...ps]) => (
            <section key={h} style={{ padding: '24px 0', borderTop: '1.5px solid var(--gray-200)' }}>
              <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: '-0.015em', color: 'var(--black)' }}>{h}</h2>
              {(() => {
                const out = [];
                let bucket = null;
                const flush = () => {
                  if (!bucket) return;
                  out.push(<ul key={'l' + out.length} style={{ margin: '12px 0 0', paddingLeft: 0, listStyle: 'none', maxWidth: '64ch' }}>{bucket.map((x, k) => (
                    <li key={k} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '4px 0', fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.68, color: 'var(--gray-700)', textWrap: 'pretty' }}>
                      <span aria-hidden="true" style={{ width: 9, height: 1.5, flexShrink: 0, marginTop: 13, background: 'var(--gray-400)' }} />
                      <span>{x}</span>
                    </li>
                  ))}</ul>);
                  bucket = null;
                };
                ps.forEach((p, i) => {
                  const s = String(p);
                  if (s.startsWith('- ')) { (bucket = bucket || []).push(s.slice(2)); return; }
                  flush();
                  out.push(<p key={i} style={{ margin: '12px 0 0', maxWidth: '64ch', fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.68, color: 'var(--gray-700)', textWrap: 'pretty' }}>{p}</p>);
                });
                flush();
                return out;
              })()}
            </section>
          ))}
        </div>
        {doc.table && (
          <div style={{ marginTop: 8, overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body)', fontSize: 13.5, lineHeight: 1.5 }}>
              <thead>
                <tr>{doc.tableHead.map((h) => <th key={h} style={{ textAlign: 'left', padding: '10px 14px 10px 0', borderBottom: '1.5px solid var(--gray-300)', fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--gray-500)', whiteSpace: 'nowrap' }}>{h}</th>)}</tr>
              </thead>
              <tbody>
                {doc.table.map((row) => (
                  <tr key={row[0]}>
                    {row.map((cell, i) => <td key={i} style={{ padding: '10px 14px 10px 0', borderBottom: '1.5px solid var(--gray-200)', verticalAlign: 'top', color: i === 4 ? 'var(--gray-600)' : 'var(--black)', fontFamily: i === 0 ? 'var(--font-code)' : 'var(--font-body)', fontSize: i === 0 ? 12.5 : 13.5, whiteSpace: i < 4 ? 'nowrap' : 'normal' }}>{cell}</td>)}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function ConsentBanner({ l, active, onSettings }) {
  const [choice, setChoice] = React.useState(() => window.smConsent.get());
  React.useEffect(() => {
    const f = (e) => setChoice(e.detail);
    window.addEventListener('sm-consent', f);
    return () => window.removeEventListener('sm-consent', f);
  }, []);
  if (choice || !active) return null;
  const b = l.banner;
  const desktop = window.matchMedia('(min-width: 1025px)').matches;
  const card = (
    <div role="dialog" aria-modal={desktop ? 'true' : undefined} aria-label={b.kicker} style={{ maxWidth: desktop ? 460 : 400, background: 'var(--white)', borderRadius: 'var(--radius-card)', boxShadow: '0 18px 50px rgba(0,0,0,0.25)', padding: desktop ? '26px 28px' : '20px 22px' }}>
      <div style={{ ...legalMono, color: 'var(--orange-600)' }}>{b.kicker}</div>
      <p style={{ margin: '10px 0 16px', fontFamily: 'var(--font-body)', fontSize: desktop ? 15 : 14, lineHeight: 1.6, color: 'var(--gray-700)' }}>{b.text}</p>
      <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
        <button onClick={() => window.smConsent.save({ analytics: true, marketing: true })} style={{ ...legalPill, background: 'var(--black)', color: 'var(--white)' }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--orange-500)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--black)'; }}>{b.acceptAll}</button>
        <button onClick={() => window.smConsent.save({ analytics: false, marketing: false })} style={{ ...legalPill, background: 'transparent', color: 'var(--black)', boxShadow: 'inset 0 0 0 1.5px var(--gray-300)' }}>{b.onlyNecessary}</button>
        <button onClick={onSettings} style={{ ...legalMono, fontSize: 10.5, background: 'none', border: 'none', padding: '11px 6px', cursor: 'pointer', color: 'var(--gray-600)', textDecoration: 'underline', textUnderlineOffset: 3 }}>{b.settings}</button>
      </div>
    </div>
  );
  /* Desktop: centred over a soft scrim - it is a decision, so it gets the
     middle of the page. Mobile: a corner card, the page stays readable. */
  if (desktop) {
    return (
      <div style={{ position: 'fixed', inset: 0, zIndex: 140, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(10,14,20,0.34)', backdropFilter: 'blur(2px)' }}>{card}</div>
    );
  }
  return <div style={{ position: 'fixed', left: 16, right: 16, bottom: 16, zIndex: 140, display: 'flex', justifyContent: 'flex-start' }}>{card}</div>;
}

Object.assign(window, { LegalLayer, CookieControls, ConsentBanner });
