/* Klipzy.lv — Landing page */
function Landing({ go, aud, setAud, lang, setLang, user }) {
  const K = window.KLIPZY;
  // Logged-in users skip auth: CTAs jump straight to their dashboard.
  const authed = user && user.status === 'in';
  const role = authed && user.profile && user.profile.role;
  const ctaGo = (r) => (authed && role) ? go(homeForRole(role), { tab: 'panel' }) : go('auth', { role: r });
  const { campaigns } = useCampaigns();
  const featured = campaigns.slice(0, 3);
  const ps = usePlatformStats();
  const activeCount = campaigns.filter((c) => (c.status || 'active') === 'active').length;
  // Derive from public campaign aggregates so the band shows even when signed
  // out (submissions are sign-in-gated; campaigns are public). Fall back to the
  // richer platform-stats read when it's available.
  const campViews = campaigns.reduce((s, c) => s + (Number(c.views) || 0), 0);
  const campSpent = campaigns.reduce((s, c) => s + (Number(c.spent) || 0), 0);
  const totalViews = (ps && ps.totalViews) || campViews;
  const paidOut = (ps && ps.paidOut) || campSpent;
  const viewsKM = (n) => {
    n = Number(n) || 0;
    if (n >= 1e6) return (n / 1e6).toFixed(n % 1e6 === 0 ? 0 : 1).replace('.', ',') + 'M';
    if (n >= 1000) return (n / 1000).toFixed(n % 1000 === 0 ? 0 : 1).replace('.', ',') + 'K';
    return String(n);
  };
  const _lvEur = (s) => lang === 'en' ? '€' + s : s + ' €';
  const bandStats = [
    [_lvEur((Math.round(paidOut || 0)).toLocaleString('lv-LV').replace(/\u00a0/g, ' ')), tr('Izmaksāts klipotājiem', lang)],
    [String(activeCount), tr('Aktīvās kampaņas', lang)],
    [viewsKM(totalViews), tr('Kopējie skatījumi', lang)],
  ];
  // Average CPM across active campaigns, rounded to the nearest €0.05.
  const rates = campaigns.map((c) => Number(c.rate) || 0).filter((r) => r > 0);
  const avgRate = rates.length ? Math.round((rates.reduce((s, r) => s + r, 0) / rates.length) / 0.05) * 0.05 : 2.40;
  const avgRateLabel = lang === 'en' ? '~€' + avgRate.toFixed(2).replace('.', ',') : '~' + avgRate.toFixed(2).replace('.', ',') + ' €';

  return (
    <div className="app-scroll fade-in" style={{ height: '100%' }}>
      <PublicNav go={go} route="landing" aud={aud} setAud={setAud} lang={lang} setLang={setLang} />

      {/* HERO */}
      <section style={{ position: 'relative', overflow: 'hidden' }}>
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(900px 480px at 78% -10%, rgba(37,99,235,.10), transparent 60%)',
        }} />

        <div className="container r-hero" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1.05fr .95fr', gap: 56, alignItems: 'center', padding: '64px 28px 84px' }}>
          <div className="hero-copy">
            <div className="pill pill-accent" style={{ height: 30, marginBottom: 22 }}>
              <Icon d={I.spark} size={14} /> {aud === 'clipper' ? tr('Pelni no skatījumiem', lang) : tr('Maksā tikai par rezultātu', lang)}
            </div>
            {aud === 'clipper' ? (
              <h1 className="r-hero-h1" style={{ fontSize: 56, lineHeight: 1.04, letterSpacing: '-0.035em', fontWeight: 600 }}>
                {tr('Pelni, veidojot klipus ', lang)}<span style={{ color: 'var(--accent)' }}>{tr('zīmoliem', lang)}</span>
              </h1>
            ) : (
              <h1 className="r-hero-h1" style={{ fontSize: 56, lineHeight: 1.04, letterSpacing: '-0.035em', fontWeight: 600 }}>
                {tr('Saturs, par kuru maksā ', lang)}<span style={{ color: 'var(--accent)' }}>{tr('pēc rezultātiem', lang)}</span>
              </h1>
            )}
            <p style={{ fontSize: 18.5, color: 'var(--text-2)', marginTop: 22, maxWidth: 480, lineHeight: 1.5 }}>
              {aud === 'clipper'
                ? tr('Publicē klipus un pelni par to skatījumiem.', lang)
                : tr('Sasniedz jaunu auditoriju ar klipotāju veidotu saturu un maksā par skatījumiem.', lang)}
            </p>
            <div className="hero-actions" style={{ display: 'flex', gap: 12, marginTop: 30 }}>
              {aud === 'clipper' ? (
                <button className="btn btn-primary btn-lg" onClick={() => ctaGo('clipper')}>
                  {tr('Sākt pelnīt', lang)} <Icon d={I.arrowR} size={17} />
                </button>
              ) : (
                <button className="btn btn-primary btn-lg" onClick={() => ctaGo('brand')}>
                  {tr('Sākt kampaņu', lang)} <Icon d={I.arrowR} size={17} />
                </button>
              )}
            </div>
            <div className="hero-stats" style={{ display: 'flex', gap: 26, marginTop: 38 }}>
              {(aud === 'clipper'
                ? [[avgRateLabel,'par 1000 skatījumiem'], ['48h','vidējais izmaksu laiks'], ['6+','aktīvi zīmoli']]
                : [['100K+','vidējie skatījumi'], ['10+','aktīvi klipotaji'], ['24h','pirmie rezultāti']]
              ).map(([a, b]) => (
                <div key={b}>
                  <div className="tnum" style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{a}</div>
                  <div className="muted" style={{ fontSize: 12.5 }}>{tr(b, lang)}</div>
                </div>
              ))}
            </div>
          </div>

          {/* product mock */}
          <HeroMock go={go} aud={aud} lang={lang} />
        </div>
      </section>

      {/* LOGO STRIP */}
      <div style={{ borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)', background: '#fff' }}>
        <div className="container" style={{ padding: '22px 28px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 26, flexWrap: 'wrap' }}>
          <span className="eyebrow" style={{ color: 'var(--muted)' }}>{tr('Mums uzticas', lang)}</span>
          <img src="assets/serpa-logo.png" alt="SERPA Media Group" style={{ height: 30, width: 'auto', display: 'block' }} />
        </div>
      </div>

      {/* PAR KLIPZY — quick nav */}
      <section className="container" style={{ padding: '56px 28px 20px' }}>
        <div className="r-grid4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14 }}>
          {[
            ['Kampaņas', 'Pārlūko aktuālās zīmolu kampaņas', I.search, () => go('marketplace')],
            ['Kā tas darbojas', 'Process klipotājiem un zīmoliem', I.spark, () => { const e = document.getElementById('how'); const s = document.querySelector('.app-scroll'); if (e && s) s.scrollTo({ top: e.offsetTop - 80, behavior: 'smooth' }); }],
            ['Mācības', 'Mācies veidot klipus, kas piesaista skatījumus', I.film, () => go('academy')],
            ['Cenas', 'Maksā tikai par skatījumiem', I.wallet, () => go('pricing')],
          ].map(([t, d, ic, fn]) => (

            <button key={t} onClick={fn} style={{
              textAlign: 'left', background: '#fff', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
              padding: '16px 18px', cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 8,
              transition: 'box-shadow .16s, transform .16s, border-color .16s',
            }}
              onMouseEnter={(e) => { e.currentTarget.style.boxShadow = 'var(--sh-md)'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.borderColor = 'var(--accent-tint-2)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; e.currentTarget.style.borderColor = 'var(--border)'; }}>
              <span style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--accent-tint)', color: 'var(--accent-700)', display: 'grid', placeItems: 'center' }}><Icon d={ic} size={19} /></span>
              <span style={{ fontSize: 15.5, fontWeight: 600 }}>{tr(t, lang)}</span>
              <span className="muted" style={{ fontSize: 13, lineHeight: 1.4 }}>{tr(d, lang)}</span>
            </button>
          ))}
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section id="how" className="container" style={{ padding: '78px 28px 20px' }}>
        <div style={{ textAlign: 'center', maxWidth: 620, margin: '0 auto 48px' }}>
          <span className="eyebrow">{tr('Kā tas darbojas', lang)}</span>
          <h2 style={{ fontSize: 38, marginTop: 12, letterSpacing: '-0.03em' }}>{aud === 'clipper' ? tr('Sāc pelnīt 3 soļos', lang) : tr('No kampaņas līdz rezultātiem', lang)}</h2>
          <p className="muted" style={{ fontSize: 16.5, marginTop: 12 }}>{aud === 'clipper' ? tr('Izvēlies kampaņu, izveido klipu un pelni par skatījumiem.', lang) : tr('Izveido kampaņu, saņem klipotāju veidotu saturu un seko rezultātiem.', lang)}</p>
        </div>
        <HowItWorks aud={aud} lang={lang} />
        <div style={{ textAlign: 'center', marginTop: 36 }}>
          <button className="btn btn-primary btn-lg" onClick={() => go('academy')}>{tr('Uzzināt vairāk', lang)} <Icon d={I.arrowR} size={17} /></button>
        </div>
      </section>

      {/* FEATURED CAMPAIGNS / TESTIMONIALS */}
      {aud === 'clipper' ? (
        <section className="container" style={{ padding: '64px 28px 20px' }}>
          <div className="spread" style={{ marginBottom: 26, alignItems: 'flex-end' }}>
            <div>
              <span className="eyebrow">{tr('Aktuālās kampaņas', lang)}</span>
              <h2 style={{ fontSize: 32, marginTop: 10 }}>{tr('Sāc pelnīt jau šodien', lang)}</h2>
            </div>
            <button className="btn btn-secondary" onClick={() => go('marketplace')}><span className="btn-text-full">{tr('Skatīt visas kampaņas', lang)}</span><span className="btn-text-short">{tr('Visas kampaņas', lang)}</span> <Icon d={I.arrowR} size={16} /></button>
          </div>
          <div className="r-grid3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 20 }}>
            {featured.map((c) => <CampaignCard key={c.id} c={c} go={go} lang={lang} />)}
          </div>
        </section>
      ) : (
        <Testimonials lang={lang} />
      )}

      {/* STATS BAND */}
      <section className="container" style={{ padding: '64px 28px' }}>
        <div className="r-grid3 r-statband" style={{ background: 'linear-gradient(120deg, #1E3A8A, #2563EB)', borderRadius: 'var(--r-xl)', padding: '46px 48px', color: '#fff', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 30, position: 'relative', overflow: 'hidden' }}>
          <div aria-hidden="true" style={{ position: 'absolute', right: -60, top: -60, width: 280, height: 280, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,255,255,.14), transparent 70%)' }} />
          {bandStats.map(([a, b]) => (
            <div key={b} style={{ position: 'relative', textAlign: 'center' }}>
              <div className="tnum" style={{ fontSize: 42, fontWeight: 600, letterSpacing: '-0.03em' }}>{a}</div>
              <div style={{ fontSize: 15, opacity: .82, marginTop: 6 }}>{tr(b, lang)}</div>
            </div>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section className="container" style={{ padding: '20px 28px 80px', textAlign: 'center' }}>
        <div className="card" style={{ padding: '56px 40px', borderRadius: 'var(--r-xl)' }}>
          <h2 style={{ fontSize: 34, letterSpacing: '-0.03em' }}>{aud === 'clipper' ? tr('Gatavs sākt pelnīt?', lang) : tr('Gatavs sākt kampaņu?', lang)}</h2>
          <p className="muted" style={{ fontSize: 17, marginTop: 12, maxWidth: 440, margin: '12px auto 0' }}>{tr('Latvijas pirmā klipu kampaņas platforma.', lang)}</p>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 26 }}>
            {aud === 'clipper' ? (
              <button className="btn btn-primary btn-lg" onClick={() => ctaGo('clipper')}>{tr('Sākt klipot', lang)}</button>
            ) : (
              <button className="btn btn-primary btn-lg" onClick={() => ctaGo('brand')}>{tr('Sākt kampaņu', lang)}</button>
            )}
          </div>
        </div>
      </section>

      <Footer go={go} lang={lang} setLang={setLang} />
    </div>
  );
}

function HeroMock({ go, aud, lang }) {
  const K = window.KLIPZY;
  const _lvEur = (s) => lang === 'en' ? '€' + s : s + ' €';
  const brand = aud === 'brand';
  const ps = usePlatformStats();
  const live = false; // hero panel always shows illustrative example data, never real campaigns

  const panelLabel = brand ? tr('Zīmola panelis', lang) : tr('Klipotāja panelis', lang);
  const stat1 = brand
    ? { label: tr('Aktīvās kampaņas', lang), value: '5', up: '+18%' }
    : live
      ? { label: tr('Kopējie skatījumi', lang), value: views(ps.totalViews) }
      : { label: tr('Kopējie skatījumi', lang), value: '651K', up: '+18%' };
  const stat2 = brand
    ? { label: tr('Pārbaudīti skatījumi', lang), value: '849K', up: '+12%' }
    : live
      ? { label: tr('Izmaksāts klipotājiem', lang), value: eur0(ps.paidOut) }
      : { label: tr('Nopelnīts', lang), value: _lvEur('111,13'), up: '+12%' };
  const listLabel = brand ? tr('Aktīvie klipotaji', lang) : tr('Aktīvās kampaņas', lang);

  const brandRows = [
    { name: 'Jānis', sub: 'Klipotājs', views: '184K', earned: _lvEur('184'), icon: 'man' },
    { name: 'Pēteris', sub: 'Klipotājs', views: '142K', earned: _lvEur('142'), icon: 'man' },
    { name: 'Anna', sub: 'Klipotāja', views: '74K', earned: _lvEur('74'), icon: 'woman' },
  ];

  return (
    <div className="hero-panel" style={{ position: 'relative' }}>
      <div className="card" style={{ borderRadius: 'var(--r-xl)', padding: 18, boxShadow: 'var(--sh-lg)' }}>
        <div className="spread" style={{ marginBottom: 14, padding: '2px 4px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 9, height: 9, borderRadius: 9, background: '#16A34A' }} />
            <span style={{ fontSize: 13, fontWeight: 560 }}>{panelLabel}</span>
          </div>
          <span className="muted" style={{ fontSize: 12 }}>{tr('šodien', lang)}</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
          <MiniStat label={stat1.label} value={stat1.value} up={stat1.up} />
          <MiniStat label={stat2.label} value={stat2.value} up={stat2.up} />
        </div>
        <div style={{ background: '#F8FAFC', borderRadius: 12, padding: '12px 14px', border: '1px solid var(--border)' }}>
          <div className="spread" style={{ marginBottom: 10 }}>
            <span className="eyebrow">{listLabel}</span>
            {live && <span className="tnum" style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--accent-700)' }}>{ps.activeCampaigns}</span>}
          </div>
          {brand
            ? brandRows.map((r) => (
              <div key={r.name} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '8px 0', borderTop: '1px solid var(--border)' }}>
                <PersonAvatar icon={r.icon} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 540 }}>{r.name}</div>
                  <div className="muted" style={{ fontSize: 11.5 }}>{tr(r.sub, lang)}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="tnum" style={{ fontSize: 13, fontWeight: 560 }}>{r.views}</div>
                  <div className="tnum" style={{ fontSize: 11.5, color: 'var(--green)', fontWeight: 540 }}>{r.earned}</div>
                </div>
              </div>
            ))
            : live
              ? (ps.feed.length ? ps.feed.slice(0, 3) : []).map((m) => (
              <div key={m.cid} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '8px 0', borderTop: '1px solid var(--border)' }}>
                <BrandLogo initials={m.initials} grad={m.grad} size={32} radius={8} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 540, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.brand}</div>
                  <div className="muted" style={{ fontSize: 11.5 }}>{eur(m.rate)} / 1000</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="tnum" style={{ fontSize: 13, fontWeight: 560 }}>{views(m.views)}</div>
                  <div className="tnum" style={{ fontSize: 11.5, color: 'var(--green)', fontWeight: 540 }}>{eur0(m.paid)}</div>
                </div>
              </div>
              ))
              : K.myCampaigns.slice(0, 3).map((m) => {
                const heroDisplay = { 'riga-energy': { rate: _lvEur('120'), earned: _lvEur('384,00') }, 'nordbyte': { rate: _lvEur('100'), earned: _lvEur('185,00') }, 'baltbet': { rate: _lvEur('85'), earned: _lvEur('78,20') } };
                const d = heroDisplay[m.cid] || { rate: eur(m.rate), earned: eur(m.earned) };
                return (
              <div key={m.cid} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '8px 0', borderTop: '1px solid var(--border)' }}>
                <BrandLogo initials={m.initials} grad={m.grad} size={32} radius={8} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 540 }}>{m.brand}</div>
                  <div className="muted" style={{ fontSize: 11.5 }}>{d.rate} / 1000</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="tnum" style={{ fontSize: 13, fontWeight: 560 }}>{views(m.views)}</div>
                  <div className="tnum" style={{ fontSize: 11.5, color: 'var(--green)', fontWeight: 540 }}>{d.earned}</div>
                </div>
              </div>
                );
              })}
          {live && !ps.feed.length && (
            <div className="muted" style={{ fontSize: 12, padding: '10px 0', borderTop: '1px solid var(--border)' }}>{tr('Šodien nav aktīvu kampaņu', lang)}</div>
          )}
        </div>
      </div>
      <div className="hero-float-card card" style={{ position: 'absolute', bottom: -22, left: -26, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 11, boxShadow: 'var(--sh-lg)' }}>
        <span style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--green-tint)', color: 'var(--green)', display: 'grid', placeItems: 'center' }}>
          <Icon d={brand ? I.man : I.wallet} size={18} />
        </span>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>{brand ? '+172K' : (live && ps.lastPayout ? '+' + eur0(ps.lastPayout.amount) : (lang === 'en' ? '+€384,00' : '+384,00 €'))}</div>
          <div className="muted" style={{ fontSize: 11.5 }}>{brand ? tr('Jauni skatījumi no Jānis', lang) : (live && ps.lastPayout && ps.lastPayout.campaign ? ps.lastPayout.campaign + ' ' + tr('izmaksa', lang) : tr('Rīga Energy izmaksa', lang))}</div>
        </div>
      </div>
    </div>
  );
}

function PersonAvatar({ icon, size = 32 }) {
  return (
    <span style={{
      width: size, height: size, flex: 'none', borderRadius: 8,
      background: 'var(--accent-tint)', color: 'var(--accent-700)',
      display: 'grid', placeItems: 'center',
    }}>
      <Icon d={I[icon]} size={Math.round(size * 0.6)} />
    </span>
  );
}
function MiniStat({ label, value, up }) {
  return (
    <div style={{ background: '#fff', border: '1px solid var(--border)', borderRadius: 12, padding: '11px 13px' }}>
      <div className="eyebrow" style={{ fontSize: 10.5 }}>{label}</div>
      <div className="tnum" style={{ fontSize: 20, fontWeight: 600, marginTop: 5 }}>{value}</div>
      <div style={{ fontSize: 11, color: 'var(--green)', fontWeight: 540, marginTop: 2 }}>{up}</div>
    </div>
  );
}

function HowItWorks({ aud, lang }) {
  const data = {
    clipper: [
      { t: 'Atrodi kampaņu', d: 'Aplūko zīmolu kapņas un izvēlies sev piemērotāko.', long: 'Pārlūko aktīvās zīmolu kampaņās un izvēlies sev piemērotāko. Katra kampaņa skaidri norāda budzētu un satura vadlīnijas.', icon: 'search' },
      { t: 'Izveido klipu', d: 'Izveido īsformāta klipu pēc zīmola vadlīnijām.', long: 'Izveido īsformāta klipu pēc zīmola vadlīnijām un publicē to savos kanālos — TikTok, Instagram vai YouTube.', icon: 'film' },
      { t: 'Saņem samaksu', d: 'Iesniedz saiti — skatījumi tiek izsekoti un izmaksāti automātiski.', long: 'Iesniedz savu klipu Klipzy. Mēs automātiski uzskaitām tā skatījumus un aprēķinām jūsu ieņēmumus, pamatojoties uz kampaņas likmi.', icon: 'wallet' },
    ],
    brand: [
      { t: 'Izveido kampaņu', d: 'Nosaki cenu par 1000 skatījumiem, budžetu un vadlīnijas.', long: 'Nosaki cenu par 1000 skatījumiem, kopējo budžetu un satura vadlīnijas. Tavu kampaņu uzreiz redz visi platformas klipotāji.', icon: 'megaphone' },
      { t: 'Klipotāji veido saturu', d: 'Klipotāji veido saturu tavam zīmolam.', long: 'Klipotāji veido un publicē saturu tavam zīmolam — TikTok, Instagram un YouTube platformās.', icon: 'users' },
      { t: 'Maksā tikai par rezultātu', d: 'Maksā tikai par pārbaudītiem skatījumiem.', long: 'Maksā par pārbaudītiem skatījumiem un seko kampaņas rezultātiem savā Klipzy panelī.', icon: 'trend' },
    ],
  };
  const steps = data[aud] || data.clipper;
  const [open, setOpen] = React.useState(0);
  const active = steps[open] || steps[0];

  return (
    <div className="r-grid2" style={{ display: 'grid', gridTemplateColumns: '0.95fr 1.05fr', gap: 24, alignItems: 'stretch' }}>
      {/* LEFT — accordion */}
      <div className="card" style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 6, background: 'linear-gradient(180deg,#F8FBFF,#fff)', borderColor: 'var(--accent-tint-2)' }}>
        {steps.map((s, i) => {
          const on = i === open;
          return (
            <button key={s.t} onClick={() => setOpen(i)} style={{
              textAlign: 'left', border: 'none', cursor: 'pointer', width: '100%',
              background: on ? '#fff' : 'transparent', borderRadius: 'var(--r-lg)',
              padding: '16px 16px', boxShadow: on ? 'var(--sh-sm)' : 'none',
              transition: 'background .14s, box-shadow .14s',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
                <span style={{
                  width: 32, height: 32, flex: 'none', borderRadius: 9, display: 'grid', placeItems: 'center',
                  background: on ? 'var(--accent)' : 'var(--accent-tint)', color: on ? '#fff' : 'var(--accent-700)',
                  fontWeight: 600, fontSize: 13.5, fontVariantNumeric: 'tabular-nums', transition: 'background .14s, color .14s',
                }}>{i + 1}</span>
                <span style={{ flex: 1, fontSize: 16, fontWeight: 560, color: on ? 'var(--text)' : 'var(--text-2)' }}>{tr(s.t, lang)}</span>
                <Icon d={I.chevR} size={18} style={{ color: 'var(--muted)', transform: on ? 'rotate(90deg)' : 'none', transition: 'transform .16s' }} />
              </div>
              <div style={{
                display: 'grid', gridTemplateRows: on ? '1fr' : '0fr',
                transition: 'grid-template-rows .2s ease', overflow: 'hidden',
              }}>
                <div style={{ minHeight: 0 }}>
                  <p className="muted" style={{ fontSize: 14, lineHeight: 1.5, margin: '10px 0 2px', paddingLeft: 45 }}>{tr(s.d, lang)}</p>
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* RIGHT — detail */}
      <div className="card" style={{ padding: 36, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <span style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--accent-tint)', color: 'var(--accent-700)', display: 'grid', placeItems: 'center', marginBottom: 22 }}>
          <Icon d={I[active.icon]} size={28} />
        </span>
        <h3 style={{ fontSize: 26, letterSpacing: '-0.02em' }}>{tr(active.t, lang)}</h3>
        <p style={{ fontSize: 16.5, color: 'var(--text-2)', lineHeight: 1.6, marginTop: 14, maxWidth: 460 }}>{tr(active.long, lang)}</p>
      </div>
    </div>
  );
}

/* shared campaign card (used on landing + marketplace) */
function CampaignCard({ c, go, lang }) {
  const pct = Math.round((c.spent / c.budget) * 100);
  return (
    <div className="card" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', transition: 'box-shadow .16s, transform .16s', cursor: 'pointer' }}
      onClick={() => go('campaign', { id: c.id })}
      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = 'var(--sh-md)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'var(--sh-sm)'; e.currentTarget.style.transform = 'none'; }}>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <BrandLogo initials={c.initials} grad={c.grad} src={c.brandLogo} size={46} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 15.5, fontWeight: 600 }}>{c.brand}</div>
            <div className="muted" style={{ fontSize: 13 }}>{tr(c.product, lang)}</div>
          </div>
          <span className="pill pill-niche" style={{ marginLeft: 'auto' }}>{tr(c.niche, lang)}</span>
        </div>

        <div style={{ background: 'var(--accent-tint)', borderRadius: 12, padding: '13px 15px', display: 'flex', alignItems: 'baseline', gap: 7 }}>
          <span className="tnum" style={{ fontSize: 24, fontWeight: 600, color: 'var(--accent-700)', letterSpacing: '-0.02em' }}>{eur(c.rate)}</span>
          <span style={{ fontSize: 13, color: 'var(--accent-700)', fontWeight: 500 }}>{tr('/ 1000 skatījumiem', lang)}</span>
        </div>

        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {c.platforms.map((p) => <Platform key={p} name={p} />)}
        </div>

        <div style={{ marginTop: 'auto' }}>
          <Budget spent={c.spent} budget={c.budget} lang={lang} />
        </div>
      </div>
      <div style={{ padding: 14, borderTop: '1px solid var(--border)' }}>
        <button className="btn btn-secondary btn-block" onClick={(e) => { e.stopPropagation(); go('campaign', { id: c.id }); }}>{tr('Skatīt kampaņu', lang)}</button>
      </div>
    </div>
  );
}

function Testimonials({ lang }) {
  const K = window.KLIPZY;
  const quotes = [
    { name: 'Kārlis Ozols', text: 'Mēs maksājām tikai par reāliem skatījumiem — desmitiem klipotāju sasniedza auditoriju, ko paši nekad nebūtu aizsnieguši.' },
    { name: 'Elīna Bērziņa', text: 'Kampaņa bija gatava dažās minūtēs, un pirmie rezultāti ienāca jau tajā pašā dienā. Bez riska, bez liekām maksām.' },
    { name: 'Mārtiņš Kalniņš', text: 'Labākā satura mārketinga investīcija — caurspīdīgi rezultāti un skatījumi, ko varam izsekot reāllaikā.' },
    { name: 'Anna Liepa', text: 'Klipzy palīdzēja mums sasniegt jaunu, jaunāku auditoriju autentiskā veidā. Iesakām katram zīmolam.' },
    { name: 'Pēteris Zariņš', text: 'No budžeta līdz pirmajiem 100k skatījumiem — viss process bija vienkāršs un pilnībā pārredzams.' },
    { name: 'Laura Krūmiņa', text: 'Mūsu zīmola atpazīstamība auga strauji, maksājot tikai par sasniegtajiem rezultātiem.' },
  ];
  const items = K.campaigns.map((c, i) => ({ ...c, ...quotes[i % quotes.length] }));
  const trackRef = React.useRef(null);
  const [canLeft, setCanLeft] = React.useState(false);
  const [canRight, setCanRight] = React.useState(true);

  const update = () => {
    const el = trackRef.current;
    if (!el) return;
    setCanLeft(el.scrollLeft > 4);
    setCanRight(el.scrollLeft < el.scrollWidth - el.clientWidth - 4);
  };
  React.useEffect(() => { update(); }, []);

  const scrollBy = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * (el.clientWidth * 0.9), behavior: 'smooth' });
  };

  const Arrow = ({ dir, show }) => (
    <button onClick={() => scrollBy(dir)} aria-label={dir > 0 ? 'Nākamās atsauksmes' : 'Iepriekšējās atsauksmes'} style={{
      position: 'absolute', top: '50%', [dir > 0 ? 'right' : 'left']: -22, transform: 'translateY(-50%)',
      width: 52, height: 52, borderRadius: 999, background: '#fff', border: '1px solid var(--border)',
      cursor: 'pointer', display: 'grid', placeItems: 'center', zIndex: 3, boxShadow: 'var(--sh-md)',
      opacity: show ? 1 : 0, pointerEvents: show ? 'auto' : 'none', transition: 'opacity .18s, box-shadow .16s, border-color .16s',
    }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent-tint-2)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--accent-700)" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" aria-hidden="true">
        {dir > 0 ? <path d="M8 4l11 8-11 8z" /> : <path d="M16 4L5 12l11 8z" />}
      </svg>
    </button>
  );

  return (
    <section className="container" style={{ padding: '64px 28px 20px' }}>
      <div style={{ textAlign: 'center', maxWidth: 620, margin: '0 auto 40px' }}>
        <span className="eyebrow">{tr('Atsauksmes', lang)}</span>
        <h2 style={{ fontSize: 32, marginTop: 10, letterSpacing: '-0.02em' }}>{tr('Ko mūsu klienti saka par Klipzy', lang)}</h2>
      </div>
      <div style={{ position: 'relative', maxWidth: 1000, margin: '0 auto' }}>
        <Arrow dir={-1} show={canLeft} />
        <Arrow dir={1} show={canRight} />
        <div ref={trackRef} onScroll={update} className="testi-track" style={{
          display: 'flex', gap: 20, overflowX: 'auto', scrollSnapType: 'x mandatory',
          paddingBottom: 4, scrollbarWidth: 'none',
        }}>
          {items.map((t) => (
            <div key={t.id} className="testi-card" style={{
              flex: 'none', width: 'calc((100% - 40px) / 3)', scrollSnapAlign: 'start',
              background: '#F1F5F9', border: '1px solid var(--border)', borderRadius: 'var(--r-xl)',
              padding: '26px 26px 22px', display: 'flex', flexDirection: 'column',
            }}>
              <span style={{ fontSize: 52, lineHeight: 0.8, fontWeight: 700, color: 'var(--accent)', fontFamily: 'Georgia, serif', height: 30 }}>&ldquo;</span>
              <p style={{ fontSize: 15, color: 'var(--text-2)', lineHeight: 1.55, marginTop: 14, flex: 1 }}>{tr(t.text, lang)}</p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 22 }}>
                <BrandLogo initials={t.initials} grad={t.grad} size={42} radius={11} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 600 }}>{t.name}</div>
                  <div className="muted" style={{ fontSize: 13 }}>{t.brand}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Footer({ go, lang, setLang }) {
  const cols = [
    ['Produkts', ['Kampaņas', 'Cenas', 'Mācības', 'Klipotājiem', 'Zīmoliem']],
    ['Uzņēmums', ['Par mums', 'Blogs', 'Kontakti']],
    ['Resursi', ['Palīdzība', 'Noteikumi', 'Privātuma politika', 'Drošība']],
  ];
  const SLUG = {
    'Kampaņas': '/kampanas', 'Mācības': '/macibas', 'Cenas': '/cenas',
    'Klipotājiem': '/klipotajiem', 'Zīmoliem': '/zimoliem-info', 'Par mums': '/par-mums',
    'Blogs': '/blogs', 'Kontakti': '/kontakti', 'Palīdzība': '/palidziba',
    'Noteikumi': '/noteikumi', 'Privātuma politika': '/privatums', 'Drošība': '/drosiba',
  };
  const nav = (it) => {
    const map = {
      'Kampaņas': ['marketplace'], 'Mācības': ['academy'], 'Cenas': ['pricing'],
      'Klipotājiem': ['for-clippers'], 'Zīmoliem': ['for-brands'], 'Par mums': ['about'],
      'Blogs': ['blog'], 'Kontakti': ['contact'], 'Palīdzība': ['help'],
      'Noteikumi': ['legal', { page: 'terms' }], 'Privātuma politika': ['legal', { page: 'privacy' }],
      'Drošība': ['legal', { page: 'security' }],
    };
    const t = map[it];
    if (t) go(t[0], t[1] || {});
  };
  return (
    <footer style={{ borderTop: '1px solid var(--border)', background: '#fff' }}>
      <div className="container r-footer" style={{ padding: '52px 28px 30px', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 36 }}>
        <div className="footer-brand">
          <Logo size={20} onClick={() => go('landing')} />
          <p className="muted" style={{ fontSize: 14, marginTop: 16, maxWidth: 260, lineHeight: 1.5 }}>{tr('Klipu kampaņu platforma, kas savieno zīmolus ar klipotājiem un atlīdzību balsta uz sasniegtajiem skatījumiem.', lang)}</p>
          <div className="pill" style={{ marginTop: 16 }}>🇱🇻 {tr('Pieejams Latvijā', lang)}</div>
        </div>
        {cols.map(([h, items]) => (
          <div key={h}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>{tr(h, lang)}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-start' }}>
              {items.map((it) => <a key={it} className="footer-link" href={SLUG[it] || '/'} onClick={(e) => { if (!e.metaKey && !e.ctrlKey && e.button === 0) { e.preventDefault(); nav(it); } }}>{tr(it, lang)}</a>)}
            </div>
          </div>
        ))}
        <div className="footer-lang" style={{ gridColumn: '1 / -1' }}>
          <LangSwitch lang={lang} setLang={setLang} langs={['lv', 'en']} />
        </div>
      </div>
      <div className="container" style={{ padding: '20px 28px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
        <span className="muted" style={{ fontSize: 13 }}>© 2026 Klipzy.lv<span className="footer-tagline"> — {tr('Šobrīd pieejams tikai Latvijas tirgū.', lang)}</span></span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <a href="https://www.instagram.com/klipzy.lv" target="_blank" rel="noopener noreferrer" aria-label="Instagram" style={{ color: 'var(--muted)', display: 'flex', alignItems: 'center' }}>
            <Icon d="M7 2h10a5 5 0 0 1 5 5v10a5 5 0 0 1-5 5H7a5 5 0 0 1-5-5V7a5 5 0 0 1 5-5z M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M17.5 6.5h.01" size={19} /></a>
          <a href="https://www.youtube.com/@Klipzy-lv" target="_blank" rel="noopener noreferrer" aria-label="YouTube" style={{ color: 'var(--muted)', display: 'flex', alignItems: 'center' }}>
            <Icon d="M22 8.2a2.6 2.6 0 0 0-1.8-1.8C18.6 6 12 6 12 6s-6.6 0-8.2.4A2.6 2.6 0 0 0 2 8.2 27 27 0 0 0 1.6 12 27 27 0 0 0 2 15.8a2.6 2.6 0 0 0 1.8 1.8C5.4 18 12 18 12 18s6.6 0 8.2-.4a2.6 2.6 0 0 0 1.8-1.8A27 27 0 0 0 22.4 12 27 27 0 0 0 22 8.2z M10 9.2l5 2.8-5 2.8z" size={20} /></a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Landing, CampaignCard, Footer });
