// Pre-app screens — Landing → Login → Persona picker. Shown before the windowed twin app.

// ---- Landing ----------------------------------------------------------

function LandingPage({ onTryDemo }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1400);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="lp-root">
      {/* Top bar */}
      <header className="lp-top">
        <div className="lp-brand">
          <span className="mark" />
          <span className="name">MarketForge</span>
          <span className="ver">v2026.04 · sim</span>
        </div>
        <nav className="lp-nav">
          <a>Product</a>
          <a>Pipeline</a>
          <a>Customers</a>
          <a>Docs</a>
          <a>Pricing</a>
        </nav>
        <div className="lp-top-cta">
          <button className="mf-btn sm ghost" onClick={onTryDemo}>Sign in</button>
          <button className="mf-btn sm primary" onClick={onTryDemo}>Try live demo →</button>
        </div>
      </header>

      {/* Hero */}
      <section className="lp-hero">
        <div className="lp-hero-copy">
          <div className="mono-lbl" style={{ color: 'var(--accent)' }}>
            § 01 · Digital twin of your market
          </div>
          <h1 className="lp-h1">
            Find the counterparty<br />
            before you ever introduce&nbsp;yourself.
          </h1>
          <p className="lp-lede">
            MarketForge runs a live, confidential simulation of your market — shops, buyers, inspectors —
            scored bidirectionally on every signal that matters. Identities stay closed until both sides
            opt in. Deals assemble themselves.
          </p>
          <div className="lp-cta-row">
            <button className="mf-btn primary" onClick={onTryDemo}>
              Try live demo <span className="arr">→</span>
            </button>
            <button className="mf-btn ghost" onClick={onTryDemo}>
              Book a walkthrough
            </button>
          </div>
          <div className="lp-meta">
            <span><span className="lp-dot ok" /> 12,478 entities in twin</span>
            <span className="sep">·</span>
            <span>1,204 active matches</span>
            <span className="sep">·</span>
            <span>SOC 2 · ITAR posture</span>
          </div>
        </div>

        {/* Matching pulse */}
        <div className="lp-hero-card">
          <div className="lp-card-head">
            <span className="mono-lbl">Matching pulse · live frame {String(tick).padStart(4,'0')}</span>
            <span className="mono-lbl" style={{ color: 'var(--accent)' }}>● SIM-4F82A</span>
          </div>
          <div className="lp-pulse">
            <div className="col">
              <div className="mono-lbl" style={{ marginBottom: 8 }}>SUPPLY</div>
              {['MS-0417','MS-2203','MS-0991','MS-1140','MS-0488'].map((n,i) => {
                const hot = (tick + i) % 5 === 0;
                return (
                  <div key={n} className={`node ${hot ? 'hot' : ''}`}>
                    <span>{n}</span>{hot && <span>●</span>}
                  </div>
                );
              })}
            </div>
            <div className="wires">
              <svg width="100%" height="100%" preserveAspectRatio="none">
                {[0,1,2].map(i => {
                  const y1 = 30 + ((tick*3 + i*7) % 5) * 34;
                  const y2 = 30 + ((tick*5 + i*3 + 2) % 5) * 34;
                  return (
                    <g key={`${tick}-${i}`}>
                      <line x1="0" y1={y1} x2="100%" y2={y2}
                        stroke="var(--accent)" strokeWidth="1.2" strokeDasharray="4 3" opacity="0.85" />
                      <circle cx="50%" cy={(y1+y2)/2} r="3" fill="var(--accent)">
                        <animate attributeName="r" values="2;5;2" dur="1.2s" repeatCount="indefinite" />
                      </circle>
                    </g>
                  );
                })}
              </svg>
            </div>
            <div className="col right">
              <div className="mono-lbl" style={{ marginBottom: 8, textAlign: 'right' }}>DEMAND</div>
              {['BU-2208','BU-0117','BU-4409','BU-1002','BU-3390'].map((n,i) => {
                const hot = (tick + i + 2) % 5 === 0;
                return (
                  <div key={n} className={`node ${hot ? 'hot' : ''}`}>
                    {hot && <span>●</span>}<span style={{ marginLeft: 'auto' }}>{n}</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="lp-card-foot">
            <span className="mono-lbl">Bidirectional · confidentiality-preserving · scored /100</span>
          </div>
        </div>
      </section>

      {/* 3-up roles */}
      <section className="lp-roles">
        <div className="lp-section-hd">
          <span className="mono-lbl" style={{ color: 'var(--accent)' }}>§ 02 · Participants</span>
          <h2 className="lp-h2">Three sides. One twin.</h2>
          <p className="lp-sub">
            Every participant is represented as a confidential twin — capabilities, certifications,
            capacity, uncertainty budgets. Matches clear only when every hard requirement is satisfied
            on both sides.
          </p>
        </div>
        <div className="lp-role-grid">
          {[
            { t: 'Machine shops', s: 'Supply side',
              b: 'You hold capacity, tooling and certifications. Surface in programs that fit your cell — without disclosing your book until a match clears.',
              stat: '1,248 shops', stat2: '41% avg. capacity',
            },
            { t: 'Buyers', s: 'Demand side',
              b: 'You have parts to make. Skip three weeks of RFQs — qualified suppliers who clear AS9100, ITAR, tolerance and delivery appear scored.',
              stat: '867 buyers', stat2: '4.2h avg. time-to-match',
            },
            { t: 'Inspectors', s: 'Verification side',
              b: 'You operate an accredited lab. Be surfaced on matches where your scope clears the 10:1 rule and your turnaround fits the buyer window.',
              stat: '312 labs', stat2: '100% accredited',
            },
          ].map(r => (
            <div key={r.t} className="lp-role-card">
              <div className="mono-lbl">{r.s}</div>
              <div className="lp-role-title">{r.t}</div>
              <p>{r.b}</p>
              <div className="lp-role-stats">
                <div><span className="mono-val">{r.stat}</span></div>
                <div><span className="mono-val">{r.stat2}</span></div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Pipeline strip */}
      <section className="lp-pipeline">
        <div className="lp-section-hd">
          <span className="mono-lbl" style={{ color: 'var(--accent)' }}>§ 03 · Pipeline</span>
          <h2 className="lp-h2">Four engines. One outcome.</h2>
        </div>
        <div className="lp-pipe-grid">
          {[
            ['ClientSynth',  'v3.2', 'Synthesises twin participants from market priors and observed deltas.'],
            ['KnowledgeSlot','v2.1', 'Grounds domain ontology; closes data gaps and lifts match confidence.'],
            ['Cosolvent',    'v7.4', 'Runs bidirectional evaluation and confidentiality-preserving scoring.'],
            ['MarketForge',  '—',    'Orchestrates the pipeline, gates identity, assembles the deal brief.'],
          ].map(([t, v, b], i) => (
            <div key={t} className="lp-pipe">
              <div className="lp-pipe-n">0{i+1}</div>
              <div className="lp-pipe-body">
                <div className="lp-pipe-title">
                  <span>{t}</span>
                  <span className="mono-lbl">{v}</span>
                </div>
                <p>{b}</p>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Footer */}
      <footer className="lp-foot">
        <div className="lp-brand">
          <span className="mark" />
          <span className="name">MarketForge</span>
        </div>
        <div className="lp-foot-meta">
          <span className="mono-lbl">© 2026 · Simulation environment · sim / read-only</span>
          <span className="mono-lbl">Build 2026.04.22 · SOC 2 Type II · ITAR-registered infrastructure</span>
        </div>
        <div className="lp-foot-links">
          <a>Privacy</a><a>Terms</a><a>Security</a><a>Status</a>
        </div>
      </footer>
    </div>
  );
}

// ---- Login ------------------------------------------------------------

const DEMO_ACCOUNTS = [
  { email: 'joana.mendes@ardent-precision.com',   role: 'shop',      initials: 'JM' },
  { email: 'lena.park@helios-aero.com',           role: 'buyer',     initials: 'LP' },
  { email: 'dmitri.volkov@meridian-metrology.com',role: 'inspector', initials: 'DV' },
];

function LoginPage({ onBack, onSignedIn }) {
  const [email, setEmail] = React.useState(DEMO_ACCOUNTS[0].email);
  const [password, setPassword] = React.useState('•••••••••••••');
  const [showDemo, setShowDemo] = React.useState(true);
  const [busy, setBusy] = React.useState(false);

  const submit = (e) => {
    if (e) e.preventDefault();
    setBusy(true);
    setTimeout(() => { setBusy(false); onSignedIn(); }, 650);
  };

  return (
    <div className="lg-root">
      <div className="lg-left">
        <div className="lg-left-top">
          <div className="lp-brand">
            <span className="mark" />
            <span className="name">MarketForge</span>
          </div>
          <button className="mf-btn sm ghost" onClick={onBack}>← Back to site</button>
        </div>

        <div className="lg-form-wrap">
          <div className="mono-lbl" style={{ color: 'var(--accent)', marginBottom: 14 }}>§ SIGN IN · SIM-4F82A</div>
          <h2 className="lp-h2" style={{ marginBottom: 6 }}>Welcome back.</h2>
          <p style={{ color: 'var(--ink-3)', fontSize: 13.5, margin: '0 0 28px', maxWidth: 420 }}>
            Signing in loads the twin in read-only simulation mode. No changes persist outside your session.
          </p>

          <form className="lg-form" onSubmit={submit}>
            <label className="lg-field">
              <span className="mono-lbl">Work email</span>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                autoComplete="username"
                spellCheck="false"
              />
            </label>
            <label className="lg-field">
              <span className="mono-lbl">
                Password
                <span className="forgot">forgot?</span>
              </span>
              <input
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                autoComplete="current-password"
              />
            </label>

            <div className="lg-row-remember">
              <label className="lg-check">
                <input type="checkbox" defaultChecked />
                <span>Keep me signed in on this device</span>
              </label>
              <span className="mono-lbl">SSO · SAML 2.0</span>
            </div>

            <button type="submit" className="mf-btn primary" style={{ width: '100%', padding: '10px 14px', marginTop: 8 }} disabled={busy}>
              {busy ? 'Verifying credentials…' : 'Sign in →'}
            </button>

            <div className="lg-sso">
              <div className="lg-div"><span>or continue with</span></div>
              <div className="lg-sso-row">
                <button type="button" className="mf-btn">
                  <span className="sso-mark" style={{ background: '#2f6fed' }} /> Okta
                </button>
                <button type="button" className="mf-btn">
                  <span className="sso-mark" style={{ background: '#161616' }} /> Microsoft Entra
                </button>
                <button type="button" className="mf-btn">
                  <span className="sso-mark" style={{ background: '#c2410c' }} /> Hardware key
                </button>
              </div>
            </div>
          </form>

          {showDemo && (
            <div className="lg-demo">
              <div className="lg-demo-hd">
                <span className="mono-lbl" style={{ color: 'var(--accent)' }}>◆ DEMO · pre-seeded accounts</span>
                <button className="mf-btn sm ghost" onClick={() => setShowDemo(false)}>hide</button>
              </div>
              <div className="lg-demo-grid">
                {DEMO_ACCOUNTS.map(a => (
                  <button key={a.email} type="button" className={`lg-demo-acc ${email === a.email ? 'on' : ''}`}
                    onClick={() => setEmail(a.email)}>
                    <span className="av">{a.initials}</span>
                    <span className="em">{a.email}</span>
                    <span className="mono-lbl role">{a.role}</span>
                  </button>
                ))}
              </div>
              <div className="mono-lbl" style={{ marginTop: 10, color: 'var(--ink-4)' }}>
                password is pre-filled · any value signs you in
              </div>
            </div>
          )}
        </div>

        <div className="lg-foot">
          <span className="mono-lbl">© 2026 MarketForge · SOC 2 · ITAR-registered infrastructure</span>
          <span className="mono-lbl"><a>Privacy</a> · <a>Terms</a> · <a>Status</a></span>
        </div>
      </div>

      <div className="lg-right">
        <div className="lg-right-panel">
          <div className="mono-lbl" style={{ color: 'rgba(247,245,239,0.55)' }}>§ TWIN FABRIC</div>
          <div className="lg-quote serif">
            "We cleared a Tier-2 aerospace buyer in four hours. Nothing about us was disclosed until
            the match held on both sides."
          </div>
          <div className="lg-attrib">
            <div className="av">RK</div>
            <div>
              <div style={{ fontWeight: 500 }}>R. Kowalski</div>
              <div className="mono-lbl" style={{ color: 'rgba(247,245,239,0.55)' }}>
                COO · Ardent Precision Works
              </div>
            </div>
          </div>

          <div className="lg-stats">
            {[
              ['12,478', 'entities in twin'],
              ['1,204',  'active matches'],
              ['4.2h',   'avg. time-to-match'],
              ['312',    'deals assembled Q2'],
            ].map(([v,l]) => (
              <div key={l}>
                <div className="mono-val" style={{ fontSize: 18, color: 'var(--paper)' }}>{v}</div>
                <div className="mono-lbl" style={{ color: 'rgba(247,245,239,0.55)' }}>{l}</div>
              </div>
            ))}
          </div>

          {/* Blueprint grid decoration */}
          <div className="lg-grid-dec" />
        </div>
      </div>
    </div>
  );
}

// ---- Persona picker ---------------------------------------------------

function PersonaPick({ onPick, onBack }) {
  const [hover, setHover] = React.useState(null);
  const personas = [
    {
      key: 'shop',
      email: 'joana.mendes@ardent-precision.com',
      callsign: 'MS-0417',
      name: 'Joana Mendes',
      title: 'Operations lead',
      org: 'Ardent Precision Works',
      side: 'Supply side',
      blurb: '5-axis shop, 34 heads. AS9100D + ITAR. Inconel 718 stocking position. Q3 capacity 38% open.',
      stats: [['41%', 'capacity open'], ['6', 'active matches'], ['2', 'knowledge gaps']],
      seen: '3 min ago · Grand Rapids, MI',
    },
    {
      key: 'buyer',
      email: 'lena.park@helios-aero.com',
      callsign: 'BU-2208',
      name: 'Lena Park',
      title: 'Strategic procurement',
      org: 'Helios Aerospace Systems',
      side: 'Demand side',
      blurb: 'Tier-2 aerospace. 210 heads. 12-part Inconel 718 program Q3. Requires AS9100D + ITAR.',
      stats: [['12', 'parts in scope'], ['4', 'candidate shops'], ['1', 'mutual match']],
      seen: 'Yesterday · Torrance, CA',
    },
    {
      key: 'inspector',
      email: 'dmitri.volkov@meridian-metrology.com',
      callsign: 'IN-0091',
      name: 'Dmitri Volkov',
      title: 'Metrology lead',
      org: 'Meridian Metrology Services',
      side: 'Verification side',
      blurb: 'ISO/IEC 17025 lab. Zeiss Prismo CMM. ±0.0001" uncertainty budget. 5-day FAI turnaround.',
      stats: [['±0.0001"', 'uncertainty'], ['5 d', 'turnaround'], ['89', 'FAIs in flight']],
      seen: '12 min ago · Independence, OH',
    },
  ];

  return (
    <div className="pp-root">
      <header className="pp-top">
        <div className="lp-brand">
          <span className="mark" />
          <span className="name">MarketForge</span>
        </div>
        <div className="pp-top-meta">
          <span className="mono-lbl">Live demo · choose a seat to enter</span>
          <button className="mf-btn sm ghost" onClick={onBack}>← Back to landing</button>
        </div>
      </header>

      <div className="pp-body">
        <div className="pp-hd">
          <div className="mono-lbl" style={{ color: 'var(--accent)' }}>§ ENTER AS · 1 OF 3 SEATS</div>
          <h1 className="lp-h1" style={{ fontSize: 40, margin: '8px 0 10px' }}>Which seat are you taking today?</h1>
          <p className="lp-lede" style={{ maxWidth: 680 }}>
            Your workspace gives you three demo seats — one per side of the market. Pick a seat to enter
            the twin. You can switch anytime from the topbar.
          </p>
        </div>

        <div className="pp-grid">
          {personas.map(p => (
            <button
              key={p.key}
              className={`pp-card ${hover === p.key ? 'hov' : ''}`}
              onMouseEnter={() => setHover(p.key)}
              onMouseLeave={() => setHover(null)}
              onClick={() => onPick(p.key)}
            >
              <div className="pp-card-top">
                <div className="pp-av">
                  {p.name.split(' ').map(s => s[0]).join('')}
                </div>
                <div style={{ flex: 1 }}>
                  <div className="mono-lbl">{p.side} · {p.callsign}</div>
                  <div className="pp-name">{p.name}</div>
                  <div className="pp-sub">{p.title} · {p.org}</div>
                </div>
                <div className="pp-enter-arrow">→</div>
              </div>
              <p className="pp-blurb">{p.blurb}</p>
              <div className="pp-stats">
                {p.stats.map(([v, l], i) => (
                  <div key={l} style={{ borderRight: i < 2 ? '1px solid var(--line)' : 'none' }}>
                    <div className="mono-val">{v}</div>
                    <div className="mono-lbl">{l}</div>
                  </div>
                ))}
              </div>
              <div className="pp-card-foot">
                <span className="mono-lbl">
                  <span className="lp-dot ok" /> last seen {p.seen}
                </span>
                <span className="mono-lbl">enter →</span>
              </div>
            </button>
          ))}
        </div>

        <div className="pp-hint">
          <span className="mono-lbl" style={{ color: 'var(--ink-3)' }}>
            ◆ Every seat sees a different market. Matches, confidence scores, and deal briefs are role-specific.
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LandingPage, PersonaPick });
