/* global React */
// Puffy site — shared chrome components. Depends on PuffyKit being loaded
// first (../ui_kits/ios_app/PuffyKit.jsx). Exports via window.PuffySite.

const { MINT, MINT_STROKE, TEAL, TEXT, T2, T3, GLASS, Icon, Puffy } = window.PuffyKit;

// ─── i18n hook ────────────────────────────────
// Re-renders components on language change.
function useI18n() {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const onChange = () => force();
    window.addEventListener('puffy:langchange', onChange);
    return () => window.removeEventListener('puffy:langchange', onChange);
  }, []);
  return {
    lang: window.PuffyI18n ? window.PuffyI18n.current : 'en',
    t: (key) => (window.PuffyI18n ? window.PuffyI18n.t(key) : key),
  };
}

// ─── Language switcher ────────────────────────
function LangSwitcher() {
  const { lang } = useI18n();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, []);

  const meta = window.PuffyI18n ? window.PuffyI18n.LANG_META : {};
  const supported = window.PuffyI18n ? window.PuffyI18n.SUPPORTED : ['en'];
  const current = meta[lang] || meta.en;

  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-block' }}>
      <button
        onClick={() => setOpen(v => !v)}
        aria-label="Change language"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          height: 40, padding: '0 12px',
          background: 'transparent', border: '1px solid rgba(0,0,0,0.1)',
          borderRadius: 999, cursor: 'pointer',
          fontSize: 14, fontWeight: 510, color: TEXT,
          fontFamily: 'inherit',
        }}>
        <span style={{ fontSize: 16 }}>{current.flag}</span>
        <span>{current.native}</span>
        <svg width="10" height="10" viewBox="0 0 10 10" style={{ opacity: 0.5 }}>
          <path d="M1 3l4 4 4-4" stroke={TEXT} strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: '110%', right: 0, minWidth: 180,
          background: '#fff', borderRadius: 14,
          boxShadow: '0 12px 32px rgba(0,0,0,0.12)', border: '1px solid rgba(0,0,0,0.06)',
          padding: 6, zIndex: 100,
        }}>
          {supported.map(code => {
            const m = meta[code];
            const active = code === lang;
            return (
              <button key={code}
                onClick={() => { window.PuffyI18n.set(code); setOpen(false); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                  padding: '8px 12px', borderRadius: 8,
                  background: active ? 'rgba(127,239,227,0.25)' : 'transparent',
                  border: 'none', cursor: 'pointer', textAlign: 'left',
                  fontSize: 14, fontWeight: active ? 590 : 400, color: TEXT,
                  fontFamily: 'inherit',
                }}>
                <span style={{ fontSize: 16 }}>{m.flag}</span>
                <span>{m.native}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── Nav ─────────────────────────────────────
function Nav({ active }) {
  const { t } = useI18n();
  const links = [
    { id: 'features', href: 'features.html', label: t('nav.features') },
    { id: 'pricing',  href: 'pricing.html',  label: t('nav.pricing') },
    { id: 'blog',     href: 'blog.html',     label: t('nav.blog') },
    { id: 'faq',      href: 'faq.html',      label: t('nav.faq') },
    { id: 'about',    href: 'about.html',    label: t('nav.about') },
  ];
  return (
    <header className="p-nav">
      <div className="p-wrap-wide p-nav-inner">
        <a href="home.html" className="p-nav-logo" aria-label="Puffy home">
          <PuffyLogoMark size={28}/>
          <span>puffy</span>
        </a>
        <nav className="p-nav-links">
          {links.map(l => (
            <a key={l.id} href={l.href}
               className={'p-nav-link' + (active === l.id ? ' is-active' : '')}>
              {l.label}
            </a>
          ))}
          <div style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <LangSwitcher/>
            <a href="get-access.html"
               className="p-nav-link p-nav-link--cta"
               style={{
                 background: MINT, border: `2px solid ${MINT_STROKE}`,
                 color: '#000', fontWeight: 590,
                 height: 40, padding: '0 18px',
                 display: 'inline-flex', alignItems: 'center',
               }}>
              {t('nav.cta')}
            </a>
          </div>
        </nav>
      </div>
    </header>
  );
}

// Simple Puffy mark (the iOS-kit abstract dog) used on Asky surfaces
// stays as <Puffy/>. For MARKETING surfaces (hero, CTAs, footer, nav)
// we use the real penguin logo. This is Penguin, the brand mark.
function Penguin({ size = 64, withRing = false, ringColor = '#FFFFFF' }) {
  const inner = (
    <span
      aria-hidden="true"
      style={{
        display: 'inline-block', width: size, height: size,
        borderRadius: Math.round(size * 0.24),
        backgroundImage: `url("../assets/puffy-logo-app-icon.png")`,
        backgroundSize: 'cover', backgroundPosition: 'center',
        boxShadow: '0 8px 24px rgba(0,0,0,0.08)',
      }}
    />
  );
  if (!withRing) return inner;
  const pad = Math.round(size * 0.22);
  const total = size + pad * 2;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: total, height: total,
      borderRadius: '50%',
      background: ringColor,
      boxShadow: '0 18px 48px rgba(15,23,42,0.08), inset 0 0 0 1px rgba(15,23,42,0.04)',
    }}>{inner}</div>
  );
}

function PuffyLogoMark({ size = 32 }) { return <Penguin size={size}/>; }

// ─── Footer ──────────────────────────────────
function Footer() {
  const { t } = useI18n();
  return (
    <footer className="p-footer">
      <div className="p-wrap-wide">
        <div className="p-footer-grid p-footer-grid--wide">
          <div className="p-footer-col">
            <a href="home.html" className="p-nav-logo" style={{ marginBottom: 16 }}>
              <PuffyLogoMark size={28}/>
              <span>puffy</span>
            </a>
            <p style={{ fontSize: 15, color: T2, lineHeight: 1.5, maxWidth: 320, margin: '12px 0 20px' }}>
              {t('footer.tagline')}
            </p>
            <div style={{ display: 'flex', gap: 8 }}>
              <SocialLink label="Instagram"/>
              <SocialLink label="TikTok"/>
              <SocialLink label="X"/>
            </div>
          </div>
          <div className="p-footer-col">
            <h4>{t('footer.product')}</h4>
            <ul>
              <li><a href="feature-passport.html">{t('features.passport.title')}</a></li>
              <li><a href="feature-asky.html">{t('features.asky.title')}</a></li>
              <li><a href="feature-life.html">{t('features.calendar.title')}</a></li>
              <li><a href="feature-avatar.html">{t('features.avatar.title')}</a></li>
              <li><a href="features.html">{t('features.cta')}</a></li>
            </ul>
          </div>
          <div className="p-footer-col">
            <h4>{t('nav.blog')}</h4>
            <ul>
              <li><a href="blog.html">{t('nav.blog')}</a></li>
              <li><a href="faq.html">{t('nav.faq')}</a></li>
            </ul>
          </div>
          <div className="p-footer-col">
            <h4>{t('footer.company')}</h4>
            <ul>
              <li><a href="about.html">{t('nav.about')}</a></li>
              <li><a href="get-access.html">{t('nav.cta')}</a></li>
              <li><a href="mailto:hello@puffy.app">Contact</a></li>
            </ul>
          </div>
          <div className="p-footer-col">
            <h4>{t('footer.legal')}</h4>
            <ul>
              <li><a href="privacy.html">Privacy</a></li>
              <li><a href="terms.html">Terms</a></li>
            </ul>
          </div>
        </div>
        <div className="p-footer-bottom">
          <span>© 2026 Puffy.</span>
          <span>iOS · iPhone 17 Pro</span>
        </div>
      </div>
    </footer>
  );
}

function SocialLink({ label }) {
  return (
    <a href="#" aria-label={label}
       style={{
         width: 36, height: 36, borderRadius: '50%',
         background: 'rgba(0,0,0,0.04)',
         display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
         fontSize: 13, fontWeight: 590, color: TEXT,
       }}>
      {label[0]}
    </a>
  );
}

// ─── WaitlistCta ─────────────────────────────
// Shared "Get early access" section used on every page — hero-ish block with
// Penguin mark, title, lede and the Waitlist form. Tweakable via props so
// pages can shift the headline/lede without rebuilding the chrome.
function WaitlistCta({
  title = 'Get early access to Puffy.',
  lede = 'Leave your email and we\u2019ll invite you in as soon as testing opens.',
  mark = true,
  tone = 'mint',         // 'mint' | 'cream' | 'white'
  compact = false,
  note = null,
  id = 'waitlist',
}) {
  const tones = {
    mint:  { bg: 'linear-gradient(180deg, rgba(127,239,227,0.4) 0%, rgba(127,239,227,0.75) 100%)' },
    cream: { bg: 'linear-gradient(180deg, #F5EFE6 0%, #EFE6D5 100%)' },
    white: { bg: '#F2F2F7' },
  };
  const t = tones[tone] || tones.mint;
  return (
    <section id={id} style={{
      background: t.bg,
      padding: compact ? '64px 0' : '96px 0',
      position: 'relative', overflow: 'hidden',
    }}>
      <div className="p-wrap" style={{ position: 'relative', textAlign: 'center' }}>
        <Reveal>
          {mark && (
            <div style={{ display: 'inline-block', marginBottom: 20 }}>
              <Penguin size={compact ? 64 : 76} withRing/>
            </div>
          )}
          <h2 className="p-h2" style={{ marginBottom: 14 }}>{title}</h2>
          {lede && (
            <p className="p-lede" style={{ margin: '0 auto 28px' }}>{lede}</p>
          )}
          <div style={{ display: 'flex', justifyContent: 'center' }}><Waitlist/></div>
          {note && (
            <p className="p-muted" style={{ fontSize: 13, marginTop: 20 }}>{note}</p>
          )}
        </Reveal>
      </div>
    </section>
  );
}

// Reveal needed here before it's defined below — forward-ref dance avoided by
// defining Reveal first in file order; include a guard in case of import order.

// ─── Waitlist ────────────────────────────────
function Waitlist({ id = 'waitlist', cta, placeholder }) {
  const { t } = useI18n();
  const [email, setEmail] = React.useState('');
  const [ok, setOk] = React.useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (!email || !/.+@.+\..+/.test(email)) return;
    setOk(true);
  };
  return (
    <form id={id} className={'p-waitlist' + (ok ? ' p-waitlist--ok' : '')} onSubmit={submit}>
      <input
        type="email" required
        placeholder={ok ? t('waitlist.success') : (placeholder || t('waitlist.placeholder'))}
        value={ok ? '' : email}
        onChange={(e) => setEmail(e.target.value)}
        disabled={ok}
      />
      <button type="submit">{ok ? '✓' : (cta || t('waitlist.button'))}</button>
    </form>
  );
}

// ─── Dog placeholder illustration ────────────
// A soft, low-fidelity sleeping dog silhouette. Flat shapes, no stock photo.
// Three palette variants so different sections don't look identical.
function DogIllustration({ variant = 'corgi', size = 320 }) {
  const sets = {
    corgi:    { fur: '#E8B887', belly: '#F4D4B0', dark: '#5A3E26' },
    golden:   { fur: '#E3B775', belly: '#F3DCB2', dark: '#5C3F20' },
    black:    { fur: '#3C3C3C', belly: '#6B6B6B', dark: '#1A1A1A' },
  };
  const c = sets[variant] || sets.corgi;
  return (
    <svg viewBox="0 0 320 240" width={size} height={size * 0.75} role="img" aria-label="Illustrated dog">
      {/* soft ground shadow */}
      <ellipse cx="160" cy="215" rx="120" ry="10" fill="rgba(0,0,0,0.06)"/>
      {/* body — curled up */}
      <path d="M60 160 Q40 120 90 100 Q130 80 200 90 Q270 100 275 150 Q280 200 220 205 L110 205 Q55 205 60 160Z"
            fill={c.fur}/>
      {/* belly */}
      <path d="M120 180 Q160 195 220 180 Q230 200 200 205 L140 205 Q110 200 120 180Z" fill={c.belly}/>
      {/* tail tucked */}
      <path d="M258 160 Q280 145 282 170 Q280 185 260 180Z" fill={c.fur}/>
      {/* head */}
      <circle cx="100" cy="115" r="42" fill={c.fur}/>
      {/* snout */}
      <ellipse cx="82" cy="125" rx="22" ry="14" fill={c.belly}/>
      {/* nose */}
      <ellipse cx="68" cy="123" rx="5" ry="4" fill={c.dark}/>
      {/* closed eye (sleeping) */}
      <path d="M95 110 Q100 108 105 110" stroke={c.dark} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
      {/* ear flop */}
      <path d="M128 90 Q145 85 140 120 Q125 125 122 108Z" fill={c.dark} opacity="0.6"/>
      <path d="M128 90 Q145 85 140 120 Q125 125 122 108Z" fill={c.fur}/>
      {/* paw */}
      <ellipse cx="155" cy="200" rx="14" ry="8" fill={c.belly}/>
    </svg>
  );
}

// ─── Big decorative paw print (disabled — opt-in only, per design call) ────
// Previously rendered a paw SVG. Now a no-op so every existing <PawMark/>
// across the site simply renders nothing. Re-enable selectively when needed.
function PawMark() { return null; }

// ─── Reveal-on-scroll ────────────────────────
// Wraps children in a p-reveal div that fades/slides in on intersect.
function Reveal({ children, delay = 0, as = 'div', style = {}, className = '' }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (!('IntersectionObserver' in window)) { el.classList.add('is-in'); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setTimeout(() => el.classList.add('is-in'), delay);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  const Tag = as;
  return <Tag ref={ref} className={'p-reveal ' + className} style={style}>{children}</Tag>;
}

// ─── Screenshot placeholder ──────────────────
// Used where we intend to drop in real app screenshots. Renders a soft
// dashed "phone-shaped" slot with a label — swap for an <img/> when the
// real asset is ready.
function ScreenshotSlot({ label = 'Screenshot', w = 300, h = 640, tilt = 0, note = '' }) {
  const { MINT_STROKE: MS, T2: C2, T3: C3, TEXT: CT, Icon: Ic } = window.PuffyKit;
  return (
    <div style={{
      width: w, height: h,
      transform: tilt ? `rotate(${tilt}deg)` : undefined,
      background: 'rgba(127,239,227,0.08)',
      border: `2px dashed ${MS}`,
      borderRadius: Math.min(44, Math.round(w * 0.14)),
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: 20, textAlign: 'center', gap: 8,
      color: C2,
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 12,
        background: 'var(--puffy-mint)', border: `1.5px solid ${MS}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 4,
      }}>
        <Ic name="paw" size={22} color={CT}/>
      </div>
      <div style={{ fontSize: 15, fontWeight: 590, color: CT, letterSpacing: '-0.2px' }}>{label}</div>
      <div style={{ fontSize: 12, fontFamily: 'var(--puffy-font-mono)', color: C3 }}>{w} × {h}</div>
      {note && <div style={{ fontSize: 12, color: C3, maxWidth: 200, lineHeight: 1.4 }}>{note}</div>}
    </div>
  );
}

// ─── Section shell ───────────────────────────
function Section({ bg = '#fff', paw = false, id, children, style = {} }) {
  return (
    <section id={id} style={{ background: bg, ...style }}>
      {paw && <div className="p-paw-bg"/>}
      <div className="p-wrap" style={{ position: 'relative' }}>{children}</div>
    </section>
  );
}

Object.assign(window, {
  PuffySite: {
    Nav, Footer, Waitlist, WaitlistCta, DogIllustration, PuffyLogoMark, Penguin,
    PawMark, Reveal, Section, ScreenshotSlot, LangSwitcher, useI18n,
  },
});
