// site-kit.jsx — PocketPolyglot marketing site shared primitives
// Theme-aware (reuses ppTheme/Waveform/Icon from kit.jsx). Exports to window.
// Wordmark · SiteNav · Footer · WaitlistForm · Reveal (scroll) · section helpers.

const SITE_SERIF = '"Spectral", Georgia, serif';
const SITE_UI = '-apple-system, "SF Pro Text", system-ui, sans-serif';

// one-time keyframes for site motion
if (typeof document !== 'undefined' && !document.getElementById('pp-site-kf')) {
  const s = document.createElement('style');
  s.id = 'pp-site-kf';
  s.textContent = `
    html { scroll-behavior: smooth; }
    .pp-reveal { opacity: 1; }
    .pp-reveal.is-in { animation: ppReveal .8s cubic-bezier(.2,.6,.3,1) both; }
    @keyframes ppReveal { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: none; } }
    @keyframes ppSiteWaveIdle { 0%,100% { transform: scaleY(0.7); } 50% { transform: scaleY(1); } }
    .pp-site a { text-decoration: none; }
    .pp-site button, .pp-site a.pp-btn { transition: transform .2s cubic-bezier(.34,1.4,.5,1), filter .2s ease, background .2s ease, border-color .2s ease, color .2s ease; }
    .pp-site button:active:not(:disabled), .pp-site a.pp-btn:active { transform: scale(0.97); filter: brightness(0.95); }
    .pp-site ::selection { background: rgba(44,94,140,0.18); }
    @media (prefers-reduced-motion: reduce) {
      html { scroll-behavior: auto; }
      .pp-site-wave-bar { animation: none !important; }
    }
    @media (max-width: 560px) {
      .pp-nav-inner { padding: 0 20px !important; }
      .pp-nav-links { display: none !important; }
      .pp-foot-inner { padding: 0 20px !important; gap: 36px !important; }
      .pp-foot-cols { gap: 40px !important; flex-wrap: wrap !important; }
      .pp-foot-bottom { padding: 0 20px !important; }
    }`;
  document.head.appendChild(s);
}

// ── Wordmark: six waveform bars + Pocket·Polyglot ───────────────────────
function Wordmark({ dark = false, size = 22, animated = false, color }) {
  const bars = [0.3, 0.7, 1, 0.6, 0.85, 0.3];
  const blue = color || (dark ? '#6EA8DA' : '#2C5E8C');
  const ink = dark ? '#EAF1F8' : '#1A2733';
  const h = Math.round(size * 0.95);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: Math.round(size * 0.5) }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: Math.max(2, size * 0.11), height: h }}>
        {bars.map((v, i) => (
          <i key={i} className={animated ? 'pp-site-wave-bar' : ''} style={{
            width: Math.max(2.5, size * 0.11), height: Math.round(v * h), borderRadius: 99,
            background: blue, display: 'block', transformOrigin: 'center bottom',
            animation: animated ? `ppSiteWaveIdle ${1.4 + i * 0.15}s ease-in-out ${i * 0.12}s infinite` : 'none',
          }}></i>
        ))}
      </div>
      <span style={{ fontFamily: SITE_SERIF, fontWeight: 500, fontSize: size, letterSpacing: -0.4, color: ink, lineHeight: 1 }}>
        Pocket<span style={{ color: blue }}>Polyglot</span>
      </span>
    </div>
  );
}

// ── Pill button / link ──────────────────────────────────────────────────
function PPButton({ children, href, dark = false, variant = 'primary', size = 'md', onClick, style = {} }) {
  const blue = dark ? '#6EA8DA' : '#2C5E8C';
  const big = size === 'lg';
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 9,
    height: big ? 60 : 50, padding: big ? '0 32px' : '0 24px', borderRadius: big ? 20 : 16,
    fontFamily: SITE_UI, fontSize: big ? 18 : 15.5, fontWeight: 600, letterSpacing: -0.2,
    cursor: 'pointer', border: 'none', whiteSpace: 'nowrap', ...style,
  };
  const skins = {
    primary: { background: blue, color: dark ? '#0B1117' : '#fff', boxShadow: `0 10px 26px ${dark ? 'rgba(110,168,218,0.30)' : 'rgba(44,94,140,0.26)'}` },
    ghost: { background: 'transparent', color: dark ? '#EAF1F8' : '#1A2733', border: `1.5px solid ${dark ? 'rgba(255,255,255,0.18)' : 'rgba(26,39,51,0.16)'}` },
  };
  const props = { className: 'pp-btn', style: { ...base, ...skins[variant] }, onClick };
  return href ? <a href={href} {...props}>{children}</a> : <button {...props}>{children}</button>;
}

// ── Sticky top nav ──────────────────────────────────────────────────────
function SiteNav({ dark = false, active, onToggleTheme }) {
  const ink = dark ? '#EAF1F8' : '#1A2733';
  const sub = dark ? 'rgba(234,241,248,0.62)' : 'rgba(26,39,51,0.6)';
  const [mob, setMob] = React.useState(typeof window !== 'undefined' ? window.innerWidth < 560 : false);
  React.useEffect(() => {
    const f = () => setMob(window.innerWidth < 560);
    window.addEventListener('resize', f);
    return () => window.removeEventListener('resize', f);
  }, []);
  const links = [
    { label: 'The method', href: 'Method.html', id: 'method' },
    { label: 'About', href: 'About.html', id: 'about' },
  ];
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: dark ? 'rgba(14,19,24,0.72)' : 'rgba(244,242,237,0.78)',
      backdropFilter: 'blur(18px) saturate(160%)', WebkitBackdropFilter: 'blur(18px) saturate(160%)',
      borderBottom: `0.5px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(26,39,51,0.08)'}`,
    }}>
      <div className="pp-nav-inner" style={{ maxWidth: 1180, margin: '0 auto', padding: '0 32px', height: 70, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <a href="index.html" style={{ display: 'flex' }}><Wordmark dark={dark} size={mob ? 16 : 20} /></a>
        <nav style={{ display: 'flex', alignItems: 'center', gap: mob ? 10 : 22 }}>
          <div className="pp-nav-links" style={{ display: 'flex', gap: 26 }}>
            {links.map(l => (
              <a key={l.id} href={l.href} style={{
                fontFamily: SITE_UI, fontSize: 14, fontWeight: 500,
                color: active === l.id ? (dark ? '#6EA8DA' : '#2C5E8C') : sub,
              }}>{l.label}</a>
            ))}
          </div>
          {onToggleTheme && (
            <button onClick={onToggleTheme} aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'} title={dark ? 'Light mode' : 'Dark mode'} style={{
              width: mob ? 36 : 40, height: mob ? 36 : 40, borderRadius: '50%', flexShrink: 0, padding: 0, cursor: 'pointer',
              border: `1px solid ${dark ? 'rgba(255,255,255,0.16)' : 'rgba(26,39,51,0.14)'}`, background: 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: ink,
            }}>
              {dark ? (
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#EAF1F8" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" /></svg>
              ) : (
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#1A2733" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4.2" /><path d="M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.2 5.2l1.5 1.5M17.3 17.3l1.5 1.5M18.8 5.2l-1.5 1.5M6.7 17.3l-1.5 1.5" /></svg>
              )}
            </button>
          )}
          <PPButton dark={dark} href="#waitlist" size="md" style={mob ? { height: 40, fontSize: 13, padding: '0 14px' } : { height: 42, fontSize: 14, padding: '0 20px' }}>{mob ? 'Join' : 'Join the waitlist'}</PPButton>
        </nav>
      </div>
    </header>
  );
}

// ── Scroll reveal ───────────────────────────────────────────────────────
function Reveal({ children, delay = 0, y = 20, style = {}, as = 'div' }) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    let done = false;
    const reveal = () => { if (!done) { done = true; setShown(true); cleanup(); } };
    const check = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight || 800;
      if (r.top < vh * 0.92 && r.bottom > 0) reveal();
    };
    const cleanup = () => {
      window.removeEventListener('scroll', check);
      window.removeEventListener('resize', check);
    };
    window.addEventListener('scroll', check, { passive: true });
    window.addEventListener('resize', check);
    const t1 = setTimeout(check, 30);
    const t2 = setTimeout(check, 300);
    return () => { cleanup(); clearTimeout(t1); clearTimeout(t2); };
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={`pp-reveal${shown ? ' is-in' : ''}`} style={{
      animationDelay: shown ? `${delay}s` : undefined,
      ...style,
    }}>{children}</Tag>
  );
}

// ── Eyebrow label ───────────────────────────────────────────────────────
function Eyebrow({ children, dark = false, color }) {
  return (
    <div style={{
      fontFamily: SITE_UI, fontSize: 12.5, fontWeight: 600, letterSpacing: 2.4, textTransform: 'uppercase',
      color: color || (dark ? 'rgba(234,241,248,0.42)' : 'rgba(26,39,51,0.4)'),
    }}>{children}</div>
  );
}

// ── Waitlist form ───────────────────────────────────────────────────────
function WaitlistForm({ dark = false, compact = false }) {
  const blue = dark ? '#6EA8DA' : '#2C5E8C';
  const ink = dark ? '#EAF1F8' : '#1A2733';
  const sub = dark ? 'rgba(234,241,248,0.6)' : 'rgba(26,39,51,0.58)';
  const surface = dark ? '#171E27' : '#FFFFFF';
  const hair = dark ? 'rgba(255,255,255,0.12)' : 'rgba(26,39,51,0.14)';
  const [email, setEmail] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const valid = /\S+@\S+\.\S+/.test(email);
  const submit = async (e) => {
    e.preventDefault();
    if (!valid || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const r = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      if (r.ok) setDone(true);
      else setError('Something went wrong. Please try again.');
    } catch {
      setError('Network error. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  if (done) {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14, padding: '18px 22px', borderRadius: 18,
        background: dark ? 'rgba(110,168,218,0.12)' : 'rgba(44,94,140,0.07)', border: `1px solid ${hexA(blue, 0.4)}`,
        maxWidth: 520,
      }}>
        <div style={{ width: 34, height: 34, borderRadius: '50%', background: blue, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="check" size={18} color={dark ? '#0B1117' : '#fff'} sw={2.6} />
        </div>
        <div>
          <div style={{ fontFamily: SITE_UI, fontSize: 15.5, fontWeight: 600, color: ink }}>You&rsquo;re on the list.</div>
          <div style={{ fontFamily: SITE_UI, fontSize: 13.5, color: sub, marginTop: 1 }}>We will write when it is ready to listen.</div>
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{ width: '100%', maxWidth: 520 }}>
      <div style={{
        display: 'flex', gap: 8, alignItems: 'center', padding: 8, borderRadius: 18,
        background: surface, border: `1px solid ${hair}`, boxShadow: dark ? 'none' : '0 6px 22px rgba(26,39,51,0.06)',
        flexWrap: compact ? 'nowrap' : 'wrap',
      }}>
        <input
          type="email" value={email} onChange={e => setEmail(e.target.value)}
          placeholder="you@email.com" aria-label="Email address"
          style={{
            flex: 1, minWidth: 180, height: 48, border: 'none', outline: 'none', background: 'transparent',
            fontFamily: SITE_UI, fontSize: 16, color: ink, padding: '0 14px',
          }}
        />
        <button type="submit" disabled={!valid || submitting} style={{
          height: 48, padding: '0 24px', borderRadius: 12, border: 'none', cursor: (valid && !submitting) ? 'pointer' : 'default',
          background: (valid && !submitting) ? blue : (dark ? 'rgba(255,255,255,0.08)' : 'rgba(26,39,51,0.08)'),
          color: (valid && !submitting) ? (dark ? '#0B1117' : '#fff') : (dark ? 'rgba(234,241,248,0.4)' : 'rgba(26,39,51,0.34)'),
          fontFamily: SITE_UI, fontSize: 15.5, fontWeight: 600, whiteSpace: 'nowrap', transition: 'background .2s, color .2s',
        }}>{submitting ? 'Joining…' : 'Join the waitlist'}</button>
      </div>
      <div style={{ fontFamily: SITE_UI, fontSize: 13, color: error ? '#B23B3B' : (dark ? 'rgba(234,241,248,0.4)' : 'rgba(26,39,51,0.4)'), marginTop: 12, paddingLeft: 4 }}>
        {error || 'Launching with Latvian · the first 1,000 words · no streaks, no spam.'}
      </div>
    </form>
  );
}

// ── Footer ──────────────────────────────────────────────────────────────
function SiteFooter({ dark = false }) {
  const sub = dark ? 'rgba(234,241,248,0.5)' : 'rgba(26,39,51,0.5)';
  const faint = dark ? 'rgba(234,241,248,0.34)' : 'rgba(26,39,51,0.34)';
  const hair = dark ? 'rgba(255,255,255,0.08)' : 'rgba(26,39,51,0.08)';
  const cols = [
    { h: 'Product', links: [['The method', 'Method.html'], ['About', 'About.html'], ['Join the waitlist', '#waitlist']] },
  ];
  return (
    <footer style={{ borderTop: `0.5px solid ${hair}`, padding: '64px 0 56px' }}>
      <div className="pp-foot-inner" style={{ maxWidth: 1180, margin: '0 auto', padding: '0 32px', display: 'flex', justifyContent: 'space-between', gap: 48, flexWrap: 'wrap' }}>
        <div style={{ maxWidth: 320 }}>
          <Wordmark dark={dark} size={20} />
          <p style={{ fontFamily: SITE_SERIF, fontSize: 17, fontStyle: 'italic', color: sub, margin: '20px 0 0', lineHeight: 1.5 }}>
            Only the words you&rsquo;ll actually use.
          </p>
        </div>
        <div className="pp-foot-cols" style={{ display: 'flex', gap: 64 }}>
          {cols.map(c => (
            <div key={c.h}>
              <div style={{ fontFamily: SITE_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: faint, marginBottom: 16 }}>{c.h}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {c.links.map(([t, h]) => (
                  <a key={t} href={h} style={{ fontFamily: SITE_UI, fontSize: 14.5, color: sub }}>{t}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="pp-foot-bottom" style={{ maxWidth: 1180, margin: '48px auto 0', padding: '0 32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
        <span style={{ fontFamily: SITE_UI, fontSize: 13, color: faint }}>© 2026 PocketPolyglot · The first 1,000 words</span>
      </div>
    </footer>
  );
}

Object.assign(window, {
  SITE_SERIF, SITE_UI, Wordmark, PPButton, SiteNav, Reveal, Eyebrow, WaitlistForm, SiteFooter,
});
