/* Landing page component — Rubin */
/* global React, window */
const { useState, useEffect } = React;

// Scroll-reveal: attach `.in` to any `.reveal` element as it enters the viewport.
function useScrollReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    if (!els.length) return;
    if (!('IntersectionObserver' in window)) {
      els.forEach(el => el.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: '0px 0px -12% 0px', threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function Landing() {
  const tweaks = window.useTweaks
    ? window.useTweaks(window.TWEAK_DEFAULTS)
    : [window.TWEAK_DEFAULTS, () => {}];
  const [t, setT] = tweaks;
  const lang = (t && t.lang) || 'en';
  const c = window.LANDING_COPY[lang];

  const setLang = l => setT('lang', l);
  useScrollReveal();

  return (
    <div className="landing">
      <Nav c={c} lang={lang} setLang={setLang} />
      <Hero c={c} />
      <Ticker c={c} />
      <Problem c={c} />
      <Capabilities c={c} />
      <HowItWorks c={c} />
      <DemoBand c={c} />
      <Audiences c={c} />
      <Metrics c={c} />
      <CTA c={c} />
      <Footer c={c} />
      {window.TweaksPanel_App ? <window.TweaksPanel_App /> : null}
    </div>
  );
}

// ─── Nav ────────────────────────────────────────────────────────────
function Nav({ c, lang, setLang }) {
  return (
    <header className="nav">
      <div className="nav-inner">
        <a className="nav-brand" href="#top">
          <span className="mark" />
          Rubin
        </a>
        <nav className="nav-links">
          <a href="#product">{c.nav.product}</a>
          <a href="#how">{c.nav.howItWorks}</a>
          <a href="#ops">{c.nav.forOps}</a>
          <a href="#inv">{c.nav.forInv}</a>
        </nav>
        <div className="nav-right">
          <div className="lang-switch">
            <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
            <button className={lang === 'pl' ? 'on' : ''} onClick={() => setLang('pl')}>PL</button>
          </div>
          <a className="btn btn-sm" href="/dashboard/">{c.nav.login}</a>
          <a className="btn btn-sm primary" href="/demo.html">{c.nav.demo}</a>
        </div>
      </div>
    </header>
  );
}

// ─── Hero ───────────────────────────────────────────────────────────
function Hero({ c }) {
  const [a, b, em, rest] = c.hero.title;
  // Compute live stats from window.TRAINS if available
  const trains = (window.TRAINS || []).filter(x => x.status === 'enroute');
  const totalRev = trains.reduce((s, x) => s + x.revenue, 0);
  const totalCap = trains.reduce((s, x) => s + x.capacity, 0);
  const totalSold = trains.reduce((s, x) => s + x.soldSeats, 0);
  const loadPct = totalCap ? Math.round((totalSold / totalCap) * 100) : 0;
  const revFmt = totalRev >= 1_000_000
    ? (totalRev / 1_000_000).toFixed(2) + ' mln zł'
    : Math.round(totalRev / 1000) + ' tys. zł';

  return (
    <section className="hero" id="top">
      <div className="hero-text">
        <div className="hero-eyebrow reveal">
          <span className="dot" /> {c.hero.eyebrow}
        </div>
        <h1 className="hero-title reveal" style={{ '--rev-delay': '80ms' }}>
          {a}<br/>
          {b}<em>{em}</em>{rest}
        </h1>
        <p className="hero-sub reveal" style={{ '--rev-delay': '220ms' }}>{c.hero.sub}</p>
        <div className="hero-ctas reveal" style={{ '--rev-delay': '340ms' }}>
          <a className="btn primary" href="/demo.html">{c.hero.primary} →</a>
          <a className="btn" href="/dashboard/">{c.hero.secondary}</a>
          <span className="mini-note">· {c.hero.note}</span>
        </div>
      </div>
      <div className="hero-viz reveal" style={{ '--rev-delay': '180ms' }}>
        <div className="hero-viz-head">
          <span>RUBIN · LIVE FEED</span>
          <span className="sp" />
          <span className="live"><span className="dot" /> PL · CZ · DE</span>
        </div>
        <div className="hero-viz-svg">
          <window.HeroMap />
        </div>
        <div className="hero-viz-overlay">
          <div className="cell">
            <div className="l">Revenue · today</div>
            <div className="v hi">{revFmt}<span className="delta">+4.8%</span></div>
          </div>
          <div className="cell">
            <div className="l">Load factor</div>
            <div className="v">{loadPct}%<span className="delta">+3.1pp</span></div>
          </div>
          <div className="cell">
            <div className="l">Trains · live</div>
            <div className="v">{trains.length}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Ticker ─────────────────────────────────────────────────────────
function Ticker({ c }) {
  const items = [...c.ticker, ...c.ticker]; // duplicate for seamless loop
  return (
    <div className="ticker">
      <div className="ticker-track">
        {items.map((it, i) => (
          <div className="ticker-item" key={i}>
            <strong>{it.k}</strong>
            <span>·</span>
            <span>{it.v}</span>
            <strong>{it.n}</strong>
            <span className={it.up ? 'up' : 'down'}>{it.d}</span>
            <span className="sep">●</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Problem ────────────────────────────────────────────────────────
function Problem({ c }) {
  const [a, em, rest] = c.problem.title;
  return (
    <section id="problem">
      <div className="sec-head reveal" data-folio="01">
        <div className="sec-label"><span className="num">{c.problem.label.split(' / ')[0]}</span> / {c.problem.label.split(' / ')[1]}</div>
        <h2 className="sec-title">{a}<em>{em}</em>{rest}</h2>
        <p className="sec-sub">{c.problem.sub}</p>
      </div>
      <div className="problem-grid">
        {c.problem.cards.map((card, i) => (
          <div className="problem-card reveal" style={{ '--rev-delay': `${i * 120}ms` }} key={i}>
            <div className="big">{card.big[0]}<small>{card.big[1]}</small></div>
            <div className="t">{card.t}</div>
            <div className="d">{card.d}</div>
            <div className="src">{card.src}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Capabilities ───────────────────────────────────────────────────
function Capabilities({ c }) {
  const [a, em, rest] = c.caps.title;
  const vizMap = {
    curve: <window.BookingCurve />,
    pricing: <window.PricingLadder />,
    compete: <window.CompeteBars />,
    matrix: <window.ODMatrix />,
  };
  return (
    <section id="product">
      <div className="sec-head reveal" data-folio="02">
        <div className="sec-label"><span className="num">{c.caps.label.split(' / ')[0]}</span> / {c.caps.label.split(' / ')[1]}</div>
        <h2 className="sec-title">{a}<em>{em}</em>{rest}</h2>
        <p className="sec-sub">{c.caps.sub}</p>
      </div>
      <div className="caps">
        {c.caps.items.map((it, i) => (
          <div className="cap-row reveal" key={i}>
            <div className="cap-text">
              <div className="cap-num">{it.num} <span className="tag">{it.tag}</span></div>
              <div className="cap-title">{it.title}</div>
              <div className="cap-desc">{it.desc}</div>
              <ul className="cap-bullets">
                {it.bullets.map((b, j) => <li key={j}>{b}</li>)}
              </ul>
            </div>
            <div className="cap-viz">{vizMap[it.viz]}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── How ────────────────────────────────────────────────────────────
function HowItWorks({ c }) {
  const [a, em, rest] = c.how.title;
  return (
    <section id="how">
      <div className="sec-head reveal" data-folio="03">
        <div className="sec-label"><span className="num">{c.how.label.split(' / ')[0]}</span> / {c.how.label.split(' / ')[1]}</div>
        <h2 className="sec-title">{a}<em>{em}</em>{rest}</h2>
      </div>
      <div className="how">
        {c.how.cols.map((col, i) => (
          <div className="how-col reveal" style={{ '--rev-delay': `${i * 140}ms` }} key={i}>
            <div className="how-step">{col.step}</div>
            <h4>{col.t}</h4>
            <p>{col.p}</p>
            <div className="sources">
              {col.sources.map((s, j) => <span key={j}>{s}</span>)}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Demo band ──────────────────────────────────────────────────────
function DemoBand({ c }) {
  const [a, em, rest] = c.demo.title;
  return (
    <div className="demo-band" id="demo">
      <div className="demo-inner">
        <div className="reveal">
          <div className="sec-label">{c.demo.label}</div>
          <h2 className="sec-title">{a}<em>{em}</em>{rest}</h2>
          <p className="sec-sub" style={{ marginBottom: 20 }}>{c.demo.sub}</p>
          <p style={{ fontFamily: "'Instrument Serif', serif", fontSize: 15, color: 'var(--ink-3)', lineHeight: 1.55, marginBottom: 28, maxWidth: 480 }}>
            {c.demo.sub2}
          </p>
          <a className="btn primary" href="/dashboard/">{c.demo.cta} →</a>
        </div>
        <div className="demo-frame reveal" style={{ '--rev-delay': '160ms' }}>
          <div className="demo-frame-head">
            <span className="dots"><i /><i /><i /></span>
            <span>rubin.rail · control room</span>
          </div>
          <div className="demo-frame-svg">
            <window.DemoFrame />
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Audiences ──────────────────────────────────────────────────────
function Audiences({ c }) {
  const [a, em, rest] = c.audiences.title;
  return (
    <section id="audiences">
      <div className="sec-head reveal" data-folio="05">
        <div className="sec-label">{c.audiences.label}</div>
        <h2 className="sec-title">{a}<em>{em}</em>{rest}</h2>
      </div>
      <div className="audiences">
        <div className="aud-card reveal" id="ops">
          <span className="icon">{c.audiences.ops.icon}</span>
          <h4>{c.audiences.ops.h}</h4>
          <p className="pitch">{c.audiences.ops.pitch}</p>
          <ul>{c.audiences.ops.bullets.map((b, i) => <li key={i}>{b}</li>)}</ul>
          <div className="aud-cta"><a className="btn primary" href="/demo.html">{c.audiences.ops.cta} →</a></div>
        </div>
        <div className="aud-card reveal" id="inv" style={{ '--rev-delay': '160ms' }}>
          <span className="icon">{c.audiences.inv.icon}</span>
          <h4>{c.audiences.inv.h}</h4>
          <p className="pitch">{c.audiences.inv.pitch}</p>
          <ul>{c.audiences.inv.bullets.map((b, i) => <li key={i}>{b}</li>)}</ul>
          <div className="aud-cta"><a className="btn" href="/demo.html">{c.audiences.inv.cta} →</a></div>
        </div>
      </div>
    </section>
  );
}

// ─── Metrics ────────────────────────────────────────────────────────
function Metrics({ c }) {
  const [a, em, rest] = c.metrics.title;
  return (
    <section id="metrics">
      <div className="sec-head reveal" data-folio="06">
        <div className="sec-label">{c.metrics.label}</div>
        <h2 className="sec-title">{a}<em>{em}</em>{rest}</h2>
        <p className="sec-sub">{c.metrics.sub}</p>
      </div>
      <div className="metrics">
        {c.metrics.items.map((m, i) => (
          <div className="metric reveal" style={{ '--rev-delay': `${i * 100}ms` }} key={i}>
            <div className="v">{m.v[0]}<small>{m.v[1]}</small></div>
            <div className="l">{m.l}</div>
            <div className="d">{m.d}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── CTA ────────────────────────────────────────────────────────────
function CTA({ c }) {
  return (
    <section className="cta-band" id="cta">
      <div className="reveal">
        <h2>{c.cta.h[0]}</h2>
        <p>{c.cta.p}</p>
      </div>
      <div className="cta-actions reveal" style={{ '--rev-delay': '160ms' }}>
        <a className="btn primary" href="/demo.html">{c.cta.primary} →</a>
        <a className="btn" href="/demo.html">{c.cta.secondary}</a>
      </div>
    </section>
  );
}

// ─── Footer ─────────────────────────────────────────────────────────
function Footer({ c }) {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <span>{c.footer.copy}</span>
        <span className="sp" />
        {c.footer.links.map((l, i) => <a key={i} href={c.footer.hrefs?.[i] || '#'}>{l}</a>)}
      </div>
    </footer>
  );
}

window.Landing = Landing;
