// Nawi — Landing Page sections
// Single source of truth for EN + AR. Each section takes `lang` ('en' or 'ar').
// AR pages render with dir="rtl" on <html>, Almarai as primary font.

const { useState: useStateLP, useEffect: useEffectLP, useRef: useRefLP } = React;

// Bilingual string helper — pick by current lang
function T(strings, lang) {return strings[lang] || strings.en;}

// Quick inline helper for short bilingual strings used inline
function tx(en, ar, lang) {return lang === 'ar' ? ar : en;}

// ────────────────────────────────────────────────────────────────────
// Atoms
// ────────────────────────────────────────────────────────────────────

function Eyebrow({ children, color, style = {} }) {
  return (
    <div style={{
      fontSize: 11, fontWeight: 700, letterSpacing: '2.4px',
      textTransform: 'uppercase', color: color || 'var(--accent)',
      ...style
    }}>{children}</div>);

}

function CTAButton({ children, variant = 'primary', icon, onClick, style = {} }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', gap: 10,
    padding: '13px 22px', borderRadius: 12,
    fontFamily: 'inherit', fontSize: 14, fontWeight: 600, letterSpacing: '0.1px',
    cursor: 'pointer', border: 'none',
    transition: 'transform 150ms var(--ease-smooth), background 150ms var(--ease-smooth), border-color 150ms var(--ease-smooth)',
    whiteSpace: 'nowrap',
    ...style
  };
  const styles = variant === 'primary' ? {
    background: 'var(--accent)', color: 'white',
    boxShadow: '0 8px 24px color-mix(in oklab, var(--accent) 32%, transparent)'
  } : variant === 'ghost' ? {
    background: 'transparent', color: 'var(--fg1)',
    border: '1px solid var(--border)'
  } : {
    background: 'var(--surface)', color: 'var(--fg1)',
    border: '1px solid var(--border)'
  };
  return (
    <button onClick={onClick} style={{ ...base, ...styles }}
    onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.97)'}
    onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
    onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
      {icon}{children}</button>);

}

function StoreButton({ store, lang }) {
  const labels = {
    en: { app: ['Download on the', 'App Store'], play: ['Get it on', 'Google Play'] },
    ar: { app: ['حمّله من', 'آب ستور'], play: ['احصل عليه من', 'جوجل بلاي'] }
  };
  const [l1, l2] = labels[lang || 'en'][store];
  return (
    <button className="lp-store-btn">
      <div className="lp-store-btn-glyph">
        {store === 'app' ?
        <svg width="22" height="26" viewBox="0 0 22 26" fill="currentColor">
            <path d="M14.94 13.84c-.02-2.96 2.42-4.4 2.53-4.46-1.38-2.02-3.53-2.3-4.3-2.33-1.83-.18-3.57 1.07-4.5 1.07-.93 0-2.36-1.04-3.88-1.01-2 .03-3.84 1.16-4.87 2.95-2.08 3.6-.53 8.92 1.5 11.84 1 1.43 2.18 3.04 3.7 2.98 1.48-.06 2.04-.96 3.83-.96 1.79 0 2.3.96 3.87.93 1.6-.03 2.61-1.46 3.59-2.9 1.13-1.66 1.6-3.27 1.63-3.36-.04-.02-3.11-1.19-3.13-4.75zM12.1 5.18C12.9 4.18 13.45 2.8 13.3 1.4c-1.2.05-2.65.8-3.49 1.78-.75.87-1.4 2.27-1.22 3.63 1.34.1 2.71-.68 3.5-1.63z" />
          </svg> :

        <svg width="22" height="26" viewBox="0 0 22 26" fill="none">
            <path d="M2.5 1.4c-.4.4-.6.96-.6 1.7v19.8c0 .74.2 1.3.6 1.7l.07.07L13.5 13.6v-.27L2.57 1.34l-.07.07z" fill="#34A853" />
            <path d="M17 17.3l-3.5-3.7v-.27l3.5-3.7.08.05 4.16 2.36c1.18.67 1.18 1.78 0 2.45l-4.16 2.36-.08.05z" fill="#FBBC04" />
            <path d="M17.08 17.25L13.5 13.6 2.5 24.6c.4.4 1.04.46 1.78.04l12.8-7.26" fill="#EA4335" />
            <path d="M17.08 9.95L4.28 2.7C3.54 2.27 2.9 2.33 2.5 2.73L13.5 13.6l3.58-3.65z" fill="#4285F4" />
          </svg>
        }
      </div>
      <div className="lp-store-btn-text">
        <div className="lp-store-btn-line1">{l1}</div>
        <div className="lp-store-btn-line2">{l2}</div>
      </div>
    </button>);

}

// Beta invite email form — used in hero + final CTA
function BetaInvite({ lang, variant = 'inline' }) {
  const [email, setEmail] = useStateLP('');
  const [sent, setSent] = useStateLP(false);
  const [busy, setBusy] = useStateLP(false);
  const [errorMsg, setErrorMsg] = useStateLP('');
  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    if (!email.trim() || !/.+@.+\..+/.test(email)) return;
    setBusy(true);
    setErrorMsg('');
    try {
      const r = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), lang, source: variant }),
      });
      if (r.ok || r.status === 409) {
        setSent(true);
      } else {
        const body = await r.json().catch(() => ({}));
        setErrorMsg(body.error || (lang === 'ar' ? 'حدث خطأ. جرّب مرّة ثانية.' : 'Something went wrong. Try again.'));
      }
    } catch (_err) {
      // Offline / design-tool preview — still acknowledge.
      setSent(true);
    } finally {
      setBusy(false);
    }
  };
  const s = lang === 'ar' ? {
    placeholder: 'بريدك الإلكتروني',
    button: 'اطلب دعوة',
    sending: 'جارٍ الإرسال…',
    success: 'تمّ. سنتواصل معك عندما يتاح مكان.',
  } : {
    placeholder: 'you@email.com',
    button: 'Request invite',
    sending: 'Sending…',
    success: 'Done — we\u2019ll be in touch when a seat opens.',
  };
  if (sent) {
    return (
      <div className="lp-beta-invite-success">
        <span className="lp-beta-invite-success-dot" />
        {s.success}
      </div>
    );
  }
  return (
    <form className={`lp-beta-invite lp-beta-invite--${variant}`} onSubmit={submit}>
      <input
        type="email"
        required
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder={s.placeholder}
        className="lp-beta-invite-input"
        disabled={busy}
      />
      <button type="submit" className="lp-beta-invite-btn" disabled={busy}>
        {busy ? s.sending : s.button}
      </button>
      {errorMsg && (
        <div className="lp-beta-invite-error" role="alert">{errorMsg}</div>
      )}
    </form>
  );
}

function PhoneWrap({ children, scale = 0.82, tilt = 0, halo = true, haloColor, glow = 0.45, style = {} }) {
  const w = 402 * scale,h = 874 * scale;
  return (
    <div className="lp-phone-wrap" style={{ width: w, height: h, position: 'relative', ...style }}>
      {halo &&
      <div className="lp-phone-halo" style={{
        background: `radial-gradient(60% 50% at 50% 45%, ${haloColor || 'color-mix(in oklab, var(--accent) 38%, transparent)'} 0%, transparent 70%)`,
        opacity: glow
      }} />
      }
      <div style={{
        position: 'absolute', inset: 0,
        transform: `scale(${scale}) ${tilt ? `rotate(${tilt}deg)` : ''}`,
        transformOrigin: 'top left',
        width: 402, height: 874
      }}>{children}</div>
    </div>);

}

function NawiPhone({ screen = 'today', dark = true }) {
  const bg = dark ? '#050505' : '#FAFAFA';
  const [tasks, setTasks] = useStateLP(window.TODAY_TASKS);
  const [inbox] = useStateLP(window.INBOX_TASKS);
  const toggleTask = (id) => setTasks((p) => p.map((t) => t.id === id ? { ...t, done: !t.done } : t));
  const screenEl =
  screen === 'today' ? <window.TodayScreen tasks={tasks} onToggle={toggleTask} isDark={dark} /> :
  screen === 'inbox' ? <window.InboxScreen tasks={inbox} onToggle={() => {}} isDark={dark} /> :
  screen === 'matrix' ? <window.MatrixScreen isDark={dark} /> :
  screen === 'cal' ? <window.CalendarScreen isDark={dark} /> :
  <window.SettingsScreen isDark={dark} onTheme={() => {}} onTryPaywall={() => {}} />;
  return (
    <window.IOSDevice dark={dark}>
      <div style={{
        position: 'relative', width: '100%', height: '100%',
        display: 'flex', flexDirection: 'column', background: bg, overflow: 'hidden'
      }}>
        <window.IOSStatusBar dark={dark} time="14:21" />
        {screenEl}
        {screen !== 'me' && <window.FAB onClick={() => {}} isDark={dark} />}
        <window.BottomNav current={screen} onTap={() => {}} isDark={dark} />
      </div>
    </window.IOSDevice>);

}

// Floating CSS-3D cubes
function CSSCube3D({ size = 120, dim = false, dur = 22, reverse = false, style = {} }) {
  const sty = { '--c': `${size}px`, '--dur': `${dur}s`, ...style };
  if (reverse) sty.animationName = 'lp-3d-spin-reverse';
  return (
    <div className="lp-3d-cube lp-3d-cube--float" style={sty}>
      <div className={`lp-3d-cube-face f ${dim ? 'dim' : ''}`} />
      <div className={`lp-3d-cube-face b ${dim ? 'dim' : ''}`} />
      <div className={`lp-3d-cube-face l ${dim ? 'dim' : ''}`} />
      <div className={`lp-3d-cube-face r ${dim ? 'dim' : ''}`} />
      <div className={`lp-3d-cube-face t ${dim ? 'dim' : ''}`} />
      <div className={`lp-3d-cube-face bt ${dim ? 'dim' : ''}`} />
    </div>);

}

// ────────────────────────────────────────────────────────────────────
// NAV
// ────────────────────────────────────────────────────────────────────
function LangToggle({ lang }) {
  const otherHref = lang === 'ar' ? 'index.html' : 'index_ar.html';
  return (
    <a href={otherHref} className="lp-lang-toggle" aria-label={lang === 'ar' ? 'Switch to English' : 'التبديل إلى العربية'}>
      <span className={lang === 'en' ? 'is-active' : ''}>EN</span>
      <span className="lp-lang-toggle-sep">·</span>
      <span dir="ltr" style={{ fontFamily: 'var(--font-ar)' }} className={lang === 'ar' ? 'is-active' : ''}>AR</span>
    </a>);

}

function LPNav({ lang }) {
  const links = T({
    en: [
    { href: '#calendar', label: 'Calendar' },
    { href: '#quickadd', label: 'Quick add' },
    { href: '#matrix', label: 'Matrix' },
    { href: '#privacy', label: 'Privacy' }],

    ar: [
    { href: '#calendar', label: 'التقويم' },
    { href: '#quickadd', label: 'الإضافة السريعة' },
    { href: '#matrix', label: 'المصفوفة' },
    { href: '#privacy', label: 'الخصوصيّة' }]

  }, lang);
  return (
    <nav className="lp-nav">
      <a href="#" className="lp-nav-brand" aria-label="Nawi">
        <img src="assets/nawi_logo_dark_inverted.svg" alt="" width="34" height="34" />
        <span>{tx('Nawi', 'ناوي', lang)}</span>
      </a>
      <div className="lp-nav-links">
        {links.map((l) => <a key={l.href} href={l.href}>{l.label}</a>)}
      </div>
      <div className="lp-nav-actions">
        <LangToggle lang={lang} />
        <CTAButton variant="primary" style={{ padding: '9px 16px', fontSize: 13 }}
          onClick={() => {
            const el = document.querySelector('.lp-final-cta');
            if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
          }}>
          {tx('Request invite', 'اطلب دعوة', lang)}
        </CTAButton>
      </div>
    </nav>);

}

// ────────────────────────────────────────────────────────────────────
// HERO
// ────────────────────────────────────────────────────────────────────
function LPHero({ lang, variant }) {
  const s = T({
    en: {
      pill: 'Closed beta · invite only',
      title: <>Your day,<br />done with care.</>,
      body: <>A task and calendar app made in Riyadh for the way the Gulf actually plans. Hijri and Gregorian on the same screen. Quick-add reads <span className="lp-inline-accent">"بعد المغرب"</span>. Nothing on the page that isn't earning its place.</>,
      meta: ['Closed beta', 'Invite only', 'iOS · Android']
    },
    ar: {
      pill: 'بيتا مغلقة · بدعوة فقط',
      title: <>يومُك،<br />مُنجَزٌ بعِناية</>,
      body: <>تطبيقُ مهامٍ وتقويمٍ، يفهم طريقتك في التّخطيط. الهجريُّ والميلاديُّ على الشّاشةِ نفسِها. الإضافةُ السّريعة تقرأ <span className="lp-inline-accent">«بعد المغرب»</span>. لا شيءَ في الصّفحةِ دونما سبب</>,
      meta: ['بيتا مغلقة', 'بدعوة فقط', 'iOS · أندرويد']
    }
  }, lang);

  return (
    <section className="lp-section lp-hero" data-screen-label="01 Hero">
      <div className="lp-hero-bg-glow" aria-hidden />
      <div className="lp-hero-grid">
        <div className="lp-hero-copy">
          <div className="lp-hero-pill">
            <span className="lp-hero-pill-dot" />
            {s.pill}
          </div>
          <h1 className="lp-hero-title">{s.title}</h1>
          <p className="lp-hero-body">{s.body}</p>
          <div className="lp-hero-ctas">
            <BetaInvite lang={lang} variant="hero" />
          </div>
          <div className="lp-hero-meta">
            <span><span className="lp-hero-meta-dot" /> {s.meta[0]}</span>
            <span></span>
            <span>{s.meta[1]}</span>
            <span>·</span>
            <span>{s.meta[2]}</span>
          </div>
        </div>

        <div className="lp-hero-phones">
          <canvas id="hero-3d-canvas" className="lp-hero-3d-canvas" aria-hidden="true" />
          {variant === 'twin' ?
          <>
              <PhoneWrap scale={0.66} tilt={-3} style={{ position: 'absolute', left: 0, top: 80, zIndex: 1 }} glow={0.35}>
                <NawiPhone screen="cal" dark={false} />
              </PhoneWrap>
              <PhoneWrap scale={0.72} tilt={2} style={{ position: 'absolute', right: 0, top: 0, zIndex: 2 }} glow={0.6}>
                <NawiPhone screen="today" dark={true} />
              </PhoneWrap>
            </> :
          variant === 'fan' ?
          <>
              <PhoneWrap scale={0.6} tilt={-6} style={{ position: 'absolute', left: 0, top: 60 }} glow={0.3}>
                <NawiPhone screen="matrix" dark={true} />
              </PhoneWrap>
              <PhoneWrap scale={0.68} tilt={0} style={{ position: 'absolute', left: '24%', top: 0, zIndex: 2 }} glow={0.55}>
                <NawiPhone screen="today" dark={true} />
              </PhoneWrap>
              <PhoneWrap scale={0.6} tilt={6} style={{ position: 'absolute', right: 0, top: 60 }} glow={0.3}>
                <NawiPhone screen="cal" dark={true} />
              </PhoneWrap>
            </> :

          <PhoneWrap scale={0.85} tilt={0} style={{ position: 'relative', margin: '0 auto' }} glow={0.55}>
              <NawiPhone screen="today" dark={true} />
            </PhoneWrap>
          }
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// BRAND STATEMENT
// ────────────────────────────────────────────────────────────────────
function LPBrandStatement({ lang }) {
  const s = T({
    en: {
      eyebrow: 'Zero clutter · one voice',
      title: <>One color does<br />the work of ten.</>,
      body: 'Nawi uses one accent color — Ultraviolet. Everything else is type, whitespace, and intention. No chrome that doesn\u2019t carry meaning.',
      swatchName: 'Ultraviolet'
    },
    ar: {
      eyebrow: 'دون فوضى · صوتٌ واحد',
      title: <>لونٌ واحد<br />يقومُ بعملِ العشرة</>,
      body: 'ناوي يستخدم لونًا مميّزًا واحدًا — أُلتراڤايلوت. وما تبقّى خطٌّ وفراغٌ ونيّة. لا زخرفةَ لا تحمل معنىً.',
      swatchName: 'أُلتراڤايلوت'
    }
  }, lang);

  return (
    <section className="lp-section lp-brand-statement" data-screen-label="02 Brand">
      <Eyebrow>{s.eyebrow}</Eyebrow>
      <h2 className="lp-statement-title">{s.title}</h2>
      <p className="lp-statement-body">{s.body}</p>
      <div className="lp-statement-cube">
        <div className="lp-3d-stage" style={{ width: 180, height: 180, position: 'relative' }}>
          <CSSCube3D size={130} dur={28} style={{ left: 25, top: 25 }} />
        </div>
      </div>
      <div className="lp-statement-swatch">
        <div className="lp-statement-swatch-chip" style={{ background: 'var(--accent)' }} />
        <div className="lp-statement-swatch-meta">
          <div className="lp-statement-swatch-name">{s.swatchName}</div>
          <div className="lp-statement-swatch-hex" id="lp-accent-hex">#4D21FC</div>
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// CALENDARS
// ────────────────────────────────────────────────────────────────────
function LPCalendars({ lang }) {
  const s = T({
    en: {
      eyebrow: 'Hijri + Gregorian',
      title1: 'Two calendars,',
      title2: 'one calm.',
      body: 'The 1st of every month shows both. Saudi National holidays, Islamic dates, and your team\u2019s standup live on the same grid — never stacked, never an afterthought.',
      stack: {
        l1: 'Gregorian', v1: 'Mon, May 18 · 2026',
        l2: 'Hijri', v2en: 'Mon, 3 Ramadan', v2yr: '1447',
        l3: 'Maghrib', v3: '18:42'
      },
      pills: [
      { c: 'lp-event-saudi', label: 'Saudi National' },
      { c: 'lp-event-islamic', label: 'Islamic' },
      { c: 'lp-event-international', label: 'International' }]

    },
    ar: {
      eyebrow: 'هجريّ + ميلاديّ',
      title1: 'تقويمان،',
      title2: 'صَفاءٌ واحد',
      body: 'أوّلُ كلِّ شهرٍ يظهر بالتقويمين. المناسبات الوطنيّة، والتّواريخُ الإسلاميّة، واجتماعاتُ فريقِك على الشبكةِ نفسِها. لا تراكم، ولا تأجيل.',
      stack: {
        l1: 'الميلاديّ', v1: 'الإثنين، ١٨ مايو · ٢٠٢٦',
        l2: 'الهجريّ', v2en: 'الإثنين، ٣ رمضان', v2yr: '١٤٤٧',
        l3: 'المغرب', v3: '١٨:٤٢'
      },
      pills: [
      { c: 'lp-event-saudi', label: 'وطنيّ سعوديّ' },
      { c: 'lp-event-islamic', label: 'إسلاميّ' },
      { c: 'lp-event-international', label: 'دوليّ' }]

    }
  }, lang);

  return (
    <section id="calendar" className="lp-section lp-feature lp-feature--ltr" data-screen-label="03 Calendar">
      <div className="lp-feature-copy">
        <Eyebrow>{s.eyebrow}</Eyebrow>
        <h2 className="lp-h2">{s.title1}</h2>
        <h2 className="lp-h2 lp-h2-line2">{s.title2}</h2>
        <p className="lp-feature-body">{s.body}</p>

        <div className="lp-date-stack">
          <div className="lp-date-stack-row">
            <div className="lp-date-stack-label">{s.stack.l1}</div>
            <div className="lp-date-stack-value">{s.stack.v1}</div>
          </div>
          <div className="lp-date-stack-divider" />
          <div className="lp-date-stack-row">
            <div className="lp-date-stack-label">{s.stack.l2}</div>
            <div className="lp-date-stack-value">
              <span>{s.stack.v2en}</span>
              <span style={{ color: 'var(--fg3)', marginInlineStart: 12, fontSize: 14 }}>{s.stack.v2yr}</span>
            </div>
          </div>
          <div className="lp-date-stack-divider" />
          <div className="lp-date-stack-row">
            <div className="lp-date-stack-label">{s.stack.l3}</div>
            <div className="lp-date-stack-value lp-date-stack-prayer">
              <span className="lp-prayer-dot" />
              {s.stack.v3}
            </div>
          </div>
        </div>

        <div className="lp-feature-tags">
          {s.pills.map((p, i) =>
          <span key={i} className={`lp-event-pill ${p.c}`}>{p.label}</span>
          )}
        </div>
      </div>

      <div className="lp-feature-visual">
        <PhoneWrap scale={0.78} tilt={2} glow={0.5}>
          <NawiPhone screen="cal" dark={true} />
        </PhoneWrap>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// QUICK ADD (NLP)
// ────────────────────────────────────────────────────────────────────
function LPQuickAdd({ lang }) {
  const s = T({
    en: {
      eyebrow: 'Natural language',
      title1: 'Type how you',
      title2: 'actually speak.',
      body: <>On-device parser. Reads Saudi Arabic prayer markers (<span className="lp-inline-accent">"بعد المغرب"</span>, <span className="lp-inline-accent">"بعد أسبوعين"</span>), English dates, priorities, and project tags — and turns them into structured fields. No commands, no syntax.</>,
      label: 'You type',
      examples: [
      { text: 'Coffee with Layla tomorrow at 9', highlights: [
        { start: 18, end: 26, type: 'date', label: 'Tomorrow' },
        { start: 27, end: 32, type: 'time', label: '09:00' }]
      },
      { text: 'اجتماع المنتج بعد المغرب', rtl: true, highlights: [
        { start: 13, end: 23, type: 'reminder', label: 'بعد المغرب' }]
      },
      { text: 'Renew Iqama before MOI deadline p2', highlights: [
        { start: 6, end: 11, type: 'project', label: 'Iqama' },
        { start: 32, end: 34, type: 'priority', label: 'P2' }]
      }],

      pills: ['date', 'time', 'priority', 'reminder', 'project']
    },
    ar: {
      eyebrow: 'اللّغة الطّبيعيّة',
      title1: 'اكتبْ مثلما',
      title2: 'تتكلّم.',
      body: <>محلّلٌ داخليٌّ يعمل على الجهاز. يقرأ علاماتِ الصّلوات (<span className="lp-inline-accent">«بعد المغرب»</span>، <span className="lp-inline-accent">«بعد أسبوعين»</span>)، والتّواريخَ الإنجليزيّة، والأولويّات، والمشاريع — ويحوّلها إلى حقولٍ مُنظّمة. دون أوامر، دون صيغة.</>,
      label: 'تكتبُ أنت',
      examples: [
      { text: 'قهوة مع ليلى بكرا الساعة ٩', rtl: true, highlights: [
        { start: 14, end: 18, type: 'date', label: 'بكرا' },
        { start: 24, end: 25, type: 'time', label: '٩:٠٠' }]
      },
      { text: 'اجتماع المنتج بعد المغرب', rtl: true, highlights: [
        { start: 13, end: 23, type: 'reminder', label: 'بعد المغرب' }]
      },
      { text: 'تجديد الإقامة قبل موعد الجوازات p2', rtl: true, highlights: [
        { start: 6, end: 13, type: 'project', label: 'الإقامة' },
        { start: 32, end: 34, type: 'priority', label: 'P2' }]
      }],

      pills: ['تاريخ', 'وقت', 'أولويّة', 'تذكير', 'مشروع']
    }
  }, lang);

  const [idx, setIdx] = useStateLP(0);
  useEffectLP(() => {
    const t = setInterval(() => setIdx((i) => (i + 1) % s.examples.length), 3200);
    return () => clearInterval(t);
  }, [lang]);
  const cur = s.examples[idx];
  const colors = { date: '#00D084', time: '#F59E0B', priority: '#EF4444', reminder: '#38BDF8', project: '#0EA5E9' };
  const types = ['date', 'time', 'priority', 'reminder', 'project'];

  const renderParts = () => {
    const parts = [];
    let cursor = 0;
    cur.highlights.forEach((h, i) => {
      if (cursor < h.start) parts.push(<span key={'p' + i}>{cur.text.slice(cursor, h.start)}</span>);
      parts.push(
        <span key={'h' + i} className="lp-nlp-hl" style={{ background: colors[h.type] }}>
          {cur.text.slice(h.start, h.end)}
        </span>
      );
      cursor = h.end;
    });
    if (cursor < cur.text.length) parts.push(<span key="end">{cur.text.slice(cursor)}</span>);
    return parts;
  };

  return (
    <section id="quickadd" className="lp-section lp-feature lp-feature--rtl" data-screen-label="04 Quick Add">
      <div className="lp-feature-visual">
        <PhoneWrap scale={0.78} tilt={-2} glow={0.5}>
          <NawiPhone screen="inbox" dark={true} />
        </PhoneWrap>
      </div>

      <div className="lp-feature-copy">
        <Eyebrow>{s.eyebrow}</Eyebrow>
        <h2 className="lp-h2">{s.title1}</h2>
        <h2 className="lp-h2 lp-h2-line2">{s.title2}</h2>
        <p className="lp-feature-body">{s.body}</p>

        <div className="lp-nlp-card">
          <div className="lp-nlp-prompt">
            <div className="lp-nlp-label">{s.label}</div>
            <div className="lp-nlp-text" dir={cur.rtl ? 'rtl' : 'ltr'}>
              {renderParts()}
              <span className="lp-nlp-caret" />
            </div>
          </div>
          <div className="lp-nlp-chips">
            {cur.highlights.map((h, i) =>
            <span key={i} className="lp-nlp-chip" style={{ background: colors[h.type] }}>
                <span className="lp-nlp-chip-val">{h.label}</span>
              </span>
            )}
          </div>
        </div>

        <div className="lp-feature-tags">
          {types.map((t, i) =>
          <span key={t} className="lp-event-pill" style={{
            background: `color-mix(in oklab, ${colors[t]} 12%, transparent)`,
            color: colors[t],
            border: `1px solid color-mix(in oklab, ${colors[t]} 28%, transparent)`
          }}>{s.pills[i]}</span>
          )}
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// MATRIX
// ────────────────────────────────────────────────────────────────────
function LPMatrix({ lang }) {
  const s = T({
    en: {
      eyebrow: 'Eisenhower priorities',
      title1: 'Important.',
      title2: 'Or just loud?',
      body: 'A 2 × 2 you can actually live in. Every task lands in one of four boxes, and the box decides what happens to it. Drag, re-rank, or let the priority flag do the routing.',
      quadrants: [
      { id: 'do', en: 'Do', color: '#EF4444', body: 'Urgent + important. Today, by name.' },
      { id: 'schedule', en: 'Schedule', color: 'var(--accent)', body: 'Important, not urgent. Put it on the calendar.' },
      { id: 'delegate', en: 'Delegate', color: '#F59E0B', body: 'Urgent, not important. Hand it off.' },
      { id: 'eliminate', en: 'Eliminate', color: 'var(--fg2)', body: 'Neither. Be honest. Let it go.' }]

    },
    ar: {
      eyebrow: 'مصفوفة آيزنهاور',
      title1: 'مُهمّ؟',
      title2: 'أم مجرّد ضوضاء؟',
      body: 'مصفوفةٌ بحجمِ ٢×٢ يمكنك أن تعيش فيها. كلُّ مهمّةٍ تحطّ في إحدى الخاناتِ الأربع، والخانةُ تقرّر مصيرها. اسحب، أو رتّب، أو دع علَم الأولويّة يتولّى الأمر.',
      quadrants: [
      { id: 'do', en: 'افعل', color: '#EF4444', body: 'عاجل ومهمّ. اليوم، بالاسم.' },
      { id: 'schedule', en: 'جدول', color: 'var(--accent)', body: 'مهمّ، غير عاجل. ضعهُ على التّقويم.' },
      { id: 'delegate', en: 'فوّض', color: '#F59E0B', body: 'عاجل، غير مهمّ. سلّمهُ لغيرِك.' },
      { id: 'eliminate', en: 'احذف', color: 'var(--fg2)', body: 'لا هذا ولا ذاك. كن صريحًا. تخلَّ عنه.' }]

    }
  }, lang);

  return (
    <section id="matrix" className="lp-section lp-feature lp-feature--ltr" data-screen-label="05 Matrix">
      <div className="lp-feature-copy">
        <Eyebrow>{s.eyebrow}</Eyebrow>
        <h2 className="lp-h2">{s.title1}</h2>
        <h2 className="lp-h2 lp-h2-line2 lp-h2-italic">{s.title2}</h2>
        <p className="lp-feature-body">{s.body}</p>

        <div className="lp-matrix-grid">
          {s.quadrants.map((q) =>
          <div key={q.id} className="lp-matrix-cell" style={{ borderColor: `color-mix(in oklab, ${q.color} 30%, var(--border))` }}>
              <div className="lp-matrix-cell-head">
                <span className="lp-matrix-cell-en" style={{ color: q.color }}>{q.en}</span>
              </div>
              <div className="lp-matrix-cell-body">{q.body}</div>
            </div>
          )}
        </div>
      </div>

      <div className="lp-feature-visual">
        <PhoneWrap scale={0.78} tilt={2} glow={0.5}>
          <NawiPhone screen="matrix" dark={true} />
        </PhoneWrap>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// PRIVACY
// ────────────────────────────────────────────────────────────────────
function LPPrivacy({ lang }) {
  const s = T({
    en: {
      eyebrow: 'On-device · local-first',
      title: 'Your day, your data.',
      body: <>The Saudi-Parser model that reads <span className="lp-inline-accent">"بعد المغرب"</span> runs on your phone. Sync is opt-in, end-to-end. We don\u2019t sell anything, because we sell the app.</>,
      stats: [
      { num: '0', label: 'trackers' },
      { num: '0', label: 'ads' },
      { num: '100%', label: 'local-first', accent: true }]

    },
    ar: {
      eyebrow: 'على الجهاز · محلّيٌ أوّلًا',
      title: 'يومُك، بياناتُك',
      body: <>نموذجُ «المحلّل السّعودي» الذي يقرأ <span className="lp-inline-accent">«بعد المغرب»</span> يعمل على هاتفِك. المزامنةُ اختياريّة ولا نبيع بياناتِك.</>,
      stats: [
      { num: '٠', label: 'تتبع' },
      { num: '٠', label: 'إعلانات' },
      { num: '٪١٠٠', label: 'محلّيّ أوّلًا', accent: true }]

    }
  }, lang);

  return (
    <section id="privacy" className="lp-section lp-privacy" data-screen-label="06 Privacy">
      <div className="lp-3d-stage lp-privacy-cubes-left" style={{ width: 240, height: 320, left: -40, top: 120 }} aria-hidden>
        <CSSCube3D size={72} dim dur={32} style={{ left: 30, top: 30 }} />
        <CSSCube3D size={48} dur={20} style={{ left: 130, top: 160 }} />
      </div>
      <div className="lp-3d-stage lp-privacy-cubes-right" style={{ width: 240, height: 320, right: -40, top: 100 }} aria-hidden>
        <CSSCube3D size={56} dur={26} reverse style={{ right: 30, top: 40 }} />
        <CSSCube3D size={84} dim dur={36} style={{ right: 100, top: 180 }} />
      </div>
      <div className="lp-privacy-inner">
        <Eyebrow>{s.eyebrow}</Eyebrow>
        <h2 className="lp-privacy-title">{s.title}</h2>
        <p className="lp-privacy-body">{s.body}</p>
        <div className="lp-privacy-stats">
          {s.stats.map((st, i) =>
          <React.Fragment key={i}>
              {i > 0 && <div className="lp-privacy-stat lp-privacy-stat-divider" />}
              <div className="lp-privacy-stat">
                <div className={`lp-privacy-stat-num ${st.accent ? 'lp-privacy-stat-num--accent' : ''}`}>{st.num}</div>
                <div className="lp-privacy-stat-label">{st.label}</div>
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// QUOTE MOMENT
// ────────────────────────────────────────────────────────────────────
function LPQuote({ lang }) {
  const s = T({
    en: {
      label: 'The principle',
      quote: <>Write a task <span className="lp-bilingual-hl">tomorrow at 9</span>.<br />The app figures out the rest.</>
    },
    ar: {
      label: 'المبدأ',
      quote: <>اكتبِ المُهمّة <span className="lp-bilingual-hl">بعد المغرب</span>.<br />التّطبيقُ يتكفّلُ بالباقي.</>
    }
  }, lang);

  return (
    <section className="lp-section lp-bilingual" data-screen-label="07 Principle">
      <div className="lp-quote-card">
        <Eyebrow color="var(--fg3)">{s.label}</Eyebrow>
        <div className="lp-quote-text">{s.quote}</div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// FINAL CTA
// ────────────────────────────────────────────────────────────────────
function LPFinalCTA({ lang }) {
  const s = T({
    en: {
      eyebrow: 'Request an invite',
      title: 'Get on the list.',
      body: 'Nawi is in closed beta. iOS 16+ and Android 10+. Drop your email and we\u2019ll send an invite when a seat opens.',
      note: 'Closed beta · TestFlight + Play Internal Testing'
    },
    ar: {
      eyebrow: 'اطلب دعوة',
      title: 'انضمّ للقائمة',
      body: 'ناوي حاليًا في بيتا مغلقة. للـ iOS 16 فما فوق، وأندرويد 10 فما فوق. اترك بريدك، وسنرسل دعوة عندما يتاح مكان.',
      note: 'بيتا مغلقة · عبر TestFlight و Play Internal Testing'
    }
  }, lang);

  return (
    <section className="lp-section lp-final-cta" data-screen-label="08 Get Nawi">
      <div className="lp-3d-stage lp-final-cubes" style={{ width: 280, height: 280, left: 0, top: -40 }} aria-hidden>
        <CSSCube3D size={64} dur={24} style={{ left: 80, top: 60 }} />
        <CSSCube3D size={40} dim dur={18} style={{ left: 180, top: 140 }} />
      </div>
      <div className="lp-3d-stage lp-final-cubes-r" style={{ width: 280, height: 280, right: 0, top: -20 }} aria-hidden>
        <CSSCube3D size={56} dim dur={28} reverse style={{ right: 80, top: 30 }} />
        <CSSCube3D size={36} dur={16} style={{ right: 180, top: 130 }} />
      </div>
      <div className="lp-final-cta-inner">
        <Eyebrow>{s.eyebrow}</Eyebrow>
        <h2 className="lp-final-cta-title">{s.title}</h2>
        <p className="lp-final-cta-body">{s.body}</p>
        <div className="lp-final-cta-buttons">
          <BetaInvite lang={lang} variant="final" />
        </div>
        <div className="lp-final-cta-note">
          <span className="lp-final-cta-note-dot" />
          {s.note}
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// FOOTER
// ────────────────────────────────────────────────────────────────────
function LPFooter({ lang }) {
  const s = T({
    en: {
      tag: 'Zero clutter. One voice.',
      product: 'Product', legal: 'Legal',
      productLinks: [
        { label: 'Calendar', href: '#calendar' },
        { label: 'Quick add', href: '#quickadd' },
        { label: 'Matrix', href: '#matrix' },
      ],
      legalLinks: [
        { label: 'Privacy', href: 'legal.html?doc=privacy&lang=en' },
        { label: 'Terms',   href: 'legal.html?doc=terms&lang=en' },
      ],
      bottom: '© 2026 Nawi · Made with care in Riyadh',
      stores: []
    },
    ar: {
      tag: 'دون فوضى. صوتٌ واحد',
      product: 'المنتج', legal: 'قانونيّ',
      productLinks: [
        { label: 'التقويم',          href: '#calendar' },
        { label: 'الإضافة السريعة',  href: '#quickadd' },
        { label: 'المصفوفة',         href: '#matrix' },
      ],
      legalLinks: [
        { label: 'الخصوصيّة', href: 'legal.html?doc=privacy&lang=ar' },
        { label: 'الشّروط',   href: 'legal.html?doc=terms&lang=ar' },
      ],
      bottom: '© ٢٠٢٦ ناوي ',
      stores: []
    }
  }, lang);

  return (
    <footer className="lp-footer">
      <div className="lp-footer-inner">
        <div className="lp-footer-brand">
          <img src="assets/nawi_logo_dark_inverted.svg" alt="" width="28" height="28" />
          <div>
            <div className="lp-footer-brand-name">{tx('Nawi', 'ناوي', lang)}</div>
            <div className="lp-footer-brand-tag">{s.tag}</div>
          </div>
        </div>
        <div className="lp-footer-links">
          <div className="lp-footer-col">
            <div className="lp-footer-col-h">{s.product}</div>
            {s.productLinks.map((l, i) => <a key={i} href={l.href}>{l.label}</a>)}
          </div>
          <div className="lp-footer-col">
            <div className="lp-footer-col-h">{s.legal}</div>
            {s.legalLinks.map((l, i) => <a key={i} href={l.href}>{l.label}</a>)}
          </div>
        </div>
      </div>
      <div className="lp-footer-bottom">
        <div>{s.bottom}</div>
        <div className="lp-footer-bottom-right">
          {s.stores.map((st, i) => <a key={i} href="#">{st}</a>)}
        </div>
      </div>
    </footer>);

}

Object.assign(window, {
  LPNav, LPHero, LPBrandStatement, LPCalendars, LPQuickAdd,
  LPMatrix, LPPrivacy, LPQuote, LPFinalCTA, LPFooter
});