/* ─── Sterna landing components ─── */

const SternaLogo = ({ size = 38 }) => (
  <img src="/landing/assets/Logo.png" alt="Sterna" style={{ height: size, width: 'auto' }} />
);

const Brand = ({ module = 'Nexus' }) => (
  <div className="nav-brand">
    <SternaLogo size={38} />
    <div className="stack">
      <div className="brand-mark name">STERNA</div>
      {module && <div className="brand-sub sub">{module}</div>}
    </div>
  </div>
);

/* ── Trial banner ── */
const TrialBanner = () => (
  <div className="trial-banner">
    <span className="pulse" aria-hidden="true"></span>
    <span><b>Trial release</b> – Sterna is a proof-of-concept tool intended for feasibility evaluation only. Its features are still limited and subject to change.</span>
    <span className="spacer"></span>
    <a href="#feedback">Share feedback →</a>
  </div>
);

/* ── Top nav ── */
const Nav = ({ onSignIn, onRegister }) => (
  <nav className="nav">
    <div className="nav-inner">
      <Brand module="Initiative" />
      <div className="nav-links">
        <a className="nav-link" href="#nexus">Sterna Nexus</a>
        <a className="nav-link" href="#how">How it works</a>
        <a className="nav-link" href="#suite">The Suite</a>
        <a className="nav-link" href="#feedback">Feedback</a>
      </div>
      <div className="nav-actions">
        <button className="btn btn-ghost-light btn-sm" onClick={onSignIn}>Sign in</button>
        <button className="btn btn-primary btn-sm" onClick={onRegister}>Request access</button>
      </div>
    </div>
  </nav>
);

/* ── Hero ── */
const HeroProductMock = () => (
  <div className="hero-visual" aria-hidden="true">
    <div className="product-card">
      <div className="product-titlebar">
        <div className="dots"><span></span><span></span><span></span></div>
        <div className="label">STERNA · NEXUS</div>
        <div className="crumb">/ acme-group / Q3-2026</div>
      </div>
      <div className="product-body">
        <div className="product-side">
          <div className="group">Workspaces</div>
          <div className="item"><span className="glyph">▸</span> Acme Group</div>
          <div className="item active"><span className="glyph">▾</span> Q3-2026 Close</div>
          <div className="item" style={{ paddingLeft: 18 }}><span className="glyph">·</span> Intercompany</div>
          <div className="item" style={{ paddingLeft: 18 }}><span className="glyph">·</span> Bank vs Ledger</div>
          <div className="group">Status</div>
          <div className="item"><span className="glyph">●</span> 248 records</div>
          <div className="item"><span className="glyph">●</span> 6 mismatches</div>
        </div>
        <div className="product-main">
          <div className="product-summary">
            <div className="summary-pill ok"><div className="num">238</div><div className="lbl">Auto-matched</div></div>
            <div className="summary-pill warn"><div className="num">4</div><div className="lbl">Suggested</div></div>
            <div className="summary-pill err"><div className="num">6</div><div className="lbl">Unmatched</div></div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="match-row ok"><span className="glyph">✓</span><div className="left">ALPHA → BETA <span className="ref">INV-44218</span></div><div className="amt">€ 184,250.00</div><div className="pill">Matched</div></div>
            <div className="match-row fx"><span className="glyph">⇄</span><div className="left">ALPHA → GAMMA <span className="ref">INV-44109</span></div><div className="amt">$ 92,418.00</div><div className="pill">FX OK</div></div>
            <div className="match-row warn"><span className="glyph">!</span><div className="left">DELTA → BETA <span className="ref">INV-44232</span></div><div className="amt">€ 17,500.00</div><div className="pill">Δ 25.00</div></div>
            <div className="match-row err"><span className="glyph">✕</span><div className="left">GAMMA → DELTA <span className="ref">INV-44301</span></div><div className="amt">€ 42,800.00</div><div className="pill">Orphan</div></div>
            <div className="match-row ok"><span className="glyph">✓</span><div className="left">DELTA → ALPHA <span className="ref">INV-44188</span></div><div className="amt">€ 6,140.20</div><div className="pill">Matched</div></div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

const Hero = ({ headline, lede, onRegister }) => (
  <section className="hero" id="top">
    <div className="hero-inner">
      <div>
        <div className="hero-eyebrow">The Sterna Initiative</div>
        <h1 dangerouslySetInnerHTML={{ __html: headline }} />
        <p className="lede">{lede}</p>
        <div className="hero-ctas">
          <button className="btn btn-primary btn-lg" onClick={onRegister}>
            Request access
          </button>
        </div>
        <div className="hero-meta">
          <div><strong>Tool 1 of N</strong><br />Sterna Nexus — available now</div>
          <div><strong>Built for</strong><br />CFOs, Controllers, Group Reporting</div>
          <div><strong>Status</strong><br />Trial release · feedback wanted</div>
        </div>
      </div>
      <HeroProductMock />
    </div>
  </section>
);

/* ── Product overview ── */
const Product = () => (
  <section className="section-product" id="nexus">
    <div className="section-inner">
      <div className="section-eyebrow">Tool 1 · Sterna Nexus</div>
      <h2 className="section-title">Two reconciliation problems, one engine.</h2>
      <p className="section-lede">
        Nexus auto-matches transactions across ledgers and flags every discrepancy with a clear,
        auditable explanation. Drop in your files — Excel, CSV, bank extracts — and the engine
        figures out the column mappings on its own.
      </p>
      <div className="product-grid">
        <div className="feature-card"><div className="icon">⇋</div><h3>Intercompany matching</h3><p>Pair receivables with payables across group entities. Nexus matches by invoice ID first, then falls back to fuzzy logic on amount, currency, and counterparty.</p></div>
        <div className="feature-card"><div className="icon">≋</div><h3>Bank vs ledger reconciliation</h3><p>Compare any two statement sources — bank vs GL, broker vs treasury, sub-ledger vs consolidation. Suggested matches surface for review; auto-matches close themselves.</p></div>
        <div className="feature-card"><div className="icon">⚑</div><h3>Mismatches, explained</h3><p>Every flag carries a reason: amount delta, missing counterparty, FX inconsistency, date slip, orphan entry. Click through to the exact rows and export the report to Excel.</p></div>
        <div className="feature-card"><div className="icon">⌬</div><h3>Workspaces &amp; access</h3><p>Each organization gets a private workspace. Invite teammates with one-time keys; admins manage roles. Your data never crosses tenant boundaries.</p></div>
        <div className="feature-card"><div className="icon">⌥</div><h3>Field mapping memory</h3><p>Nexus learns your column names — "Customer Ref", "Doc N°", "Amount" — and applies the same mapping next month, on the same files, automatically.</p></div>
        <div className="feature-card"><div className="icon">✦</div><h3>Multiple languages, one report.</h3><p>Six languages are currently supported (EN, IT, FR, ES, DE, NL) but more can be added on request. Run analyses in your team's language and export reports your auditors can read without translation overhead.</p></div>
      </div>
    </div>
  </section>
);

/* ── How it works ── */
const HowItWorks = () => (
  <section className="section-how" id="how">
    <div className="section-inner">
      <div className="section-eyebrow">In three steps</div>
      <h2 className="section-title">From two spreadsheets to a clean report — in minutes.</h2>
      <p className="section-lede">No setup project, no schema design. Drop your files in, run the analysis, review the exceptions. The tool handles the matching; you handle the judgment calls.</p>
      <div className="how-steps">
        <div className="how-step">
          <div className="step-num">Step 01 — Upload</div>
          <h3>Drop your files into a workspace folder.</h3>
          <p>One file per company, or two statements to reconcile. Nexus reads Excel, CSV, and most accounting exports.</p>
          <div className="step-visual mono">
            <div style={{ color: 'var(--ink-500)' }}># /q3-2026-close/</div>
            <div>alpha_ledger.xlsx&nbsp;&nbsp;&nbsp;&nbsp;<span style={{ color: 'var(--tern-700)' }}>148 KB</span></div>
            <div>beta_ledger.xlsx&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style={{ color: 'var(--tern-700)' }}>121 KB</span></div>
            <div>gamma_ledger.xlsx&nbsp;&nbsp;&nbsp;<span style={{ color: 'var(--tern-700)' }}>183 KB</span></div>
          </div>
        </div>
        <div className="how-step">
          <div className="step-num">Step 02 — Match</div>
          <h3>Click Run. The engine handles the rest.</h3>
          <p>Auto-detects column mappings, matches by invoice ID and amount, and reconciles cross-currency entries.</p>
          <div className="step-visual">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{ flex: 1, background: '#dbe7e0', height: 5, borderRadius: 3, overflow: 'hidden' }}>
                <span style={{ display: 'block', width: '78%', height: '100%', background: 'var(--wing-400)' }}></span>
              </span>
              <span className="mono" style={{ fontSize: '0.75rem', color: 'var(--ink-500)' }}>78%</span>
            </div>
            <div style={{ fontSize: '0.78rem', color: 'var(--ink-500)' }}>Reconciling 1,840 rows · 6 unmatched so far</div>
          </div>
        </div>
        <div className="how-step">
          <div className="step-num">Step 03 — Review</div>
          <h3>Approve, investigate, export.</h3>
          <p>Walk through the mismatches with one-click drill-down. Export the final report to Excel, ready for the close.</p>
          <div className="step-visual" style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.78rem' }}><span style={{ color: '#138a4f' }}>✓ Auto-matched</span><strong>238</strong></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.78rem' }}><span style={{ color: '#b6741a' }}>⚠ Suggested</span><strong>4</strong></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.78rem' }}><span style={{ color: '#b3372a' }}>✕ Needs action</span><strong>6</strong></div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* ── Suite roadmap ── */
const Suite = ({ tools, onSignIn }) => (
  <section className="section-suite" id="suite">
    <div className="section-inner">
      <div className="section-eyebrow">The Sterna Suite</div>
      <h2 className="section-title">A growing toolkit for the office of the CFO.</h2>
      <p className="section-lede">Nexus is the first tool released for trial. More are in preparation — each one targeting a recurring, manual finance task that should already be automated.</p>
      <div className="suite-grid">
        {tools.map((tool, i) => (
          <div key={i} className={`suite-card ${tool.live ? 'live' : ''}`}>
            <span className={`suite-status ${tool.statusClass}`}>{tool.status}</span>
            <div className="suite-name">{tool.name}</div>
            <div className="suite-desc">{tool.desc}</div>
            {tool.live
              ? <button className="open-link" style={{background:'none',border:'none',cursor:'pointer',padding:0}} onClick={onSignIn}>Try it now →</button>
              : <span style={{ fontSize: '0.74rem', color: 'rgba(255,255,255,0.4)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{tool.eta}</span>
            }
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ── Feedback / Survey ── */
const FeedbackSection = ({ onSubmit }) => {
  const INIT = {
    role: '', work_type: '', scope: '',
    pain_interco: 0, pain_bank: 0,
    tool_support: '', tool_adequacy: 0,
    nexus_fit: 0, pmf: 0,
    must_do: '',
    suite_suggestions: '',
    email: '', additional: '', optin: false,
  };

  const [form, setForm] = React.useState(INIT);
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [expanded, setExpanded] = React.useState(false);

  const set = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(e => { const n = { ...e }; delete n[k]; return n; });
  };

  const cancel = () => { setExpanded(false); setForm(INIT); setErrors({}); };

  const RatingField = ({ field, error, lowLabel, highLabel }) => (
    <div>
      <div className="rating-row">
        {[1,2,3,4,5].map(n => (
          <button key={n} type="button"
            className={'rating-btn' + (form[field] === n ? ' active' : '')}
            onClick={() => set(field, n)}
          >{n}</button>
        ))}
      </div>
      <div className="rating-labels">
        <span>{lowLabel}</span><span>{highLabel}</span>
      </div>
      {error && <div className="field-error">{error}</div>}
    </div>
  );

  const needsToolAdequacy = form.tool_support === 'Partially' || form.tool_support === 'Fully covered';

  const validate = () => {
    const e = {};
    if (!form.role) e.role = 'Please select your role.';
    if (!form.work_type) e.work_type = 'Please select how you work.';
    if (!form.scope) e.scope = 'Please select your scope.';
    if (!form.pain_interco) e.pain_interco = 'Please rate this.';
    if (!form.pain_bank) e.pain_bank = 'Please rate this.';
    if (!form.tool_support) e.tool_support = 'Please select one.';
    if (needsToolAdequacy && !form.tool_adequacy) e.tool_adequacy = 'Please rate this.';
    if (!form.nexus_fit) e.nexus_fit = 'Please rate this.';
    if (!form.pmf) e.pmf = 'Please rate this.';
    if (!form.must_do.trim() || form.must_do.trim().length < 8) e.must_do = 'Please share at least a few words.';
    if (!form.email.trim()) e.email = 'Email is required.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "That doesn't look like a valid email.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setBusy(true);
    await fetch('/feedback', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    }).catch(() => {});
    setBusy(false);
    setSent(true);
    onSubmit && onSubmit('Thank you — your responses have been recorded.');
  };

  if (sent) return (
    <section className="section-feedback" id="feedback">
      <div className="section-inner" style={{ textAlign: 'center', padding: '80px 24px' }}>
        <div style={{ fontSize: '3rem', marginBottom: 16, color: 'var(--wing-400)' }}>✓</div>
        <h2 className="section-title">Thank you for your input.</h2>
        <p className="section-lede">Your responses help shape the Sterna roadmap. We'll be in touch if you opted in.</p>
      </div>
    </section>
  );

  if (!expanded) return (
    <section className="section-feedback" id="feedback">
      <div className="section-inner">
        <div className="section-eyebrow">We're listening</div>
        <h2 className="section-title">Tell us what works — and what gets in the way.</h2>
        <p className="section-lede">
          A short questionnaire to help us understand real finance workflows and prioritise what to build next.
          It covers your current setup, pain points, and first impressions of Nexus. Under 3 minutes.
        </p>
        <div className="survey-hint">
          <span>&#x1f4a1;</span>
          <span>
            For the most meaningful responses, we suggest <a href="/app">trying Nexus</a> first — but you're
            welcome to share your perspective at any stage.
          </span>
        </div>
        <button className="btn btn-primary btn-lg" onClick={() => setExpanded(true)} style={{ marginTop: 32 }}>
          Take the questionnaire &nbsp;→
        </button>
      </div>
    </section>
  );

  return (
    <section className="section-feedback" id="feedback">
      <div className="section-inner">
        <div className="section-eyebrow">We're listening</div>
        <h2 className="section-title">Tell us what works — and what gets in the way.</h2>
        <p className="section-lede">Under 3 minutes. All fields marked <span className="req">*</span> are required.</p>

        <form className="survey-form" onSubmit={submit} noValidate>

          {/* Section 1 */}
          <div className="survey-section">
            <div className="survey-section-hdr">Section 1 — About you</div>

            <div className="field">
              <label htmlFor="q-role">1. Your role <span className="req">*</span></label>
              <select id="q-role" value={form.role} className={errors.role ? 'invalid' : ''}
                onChange={e => set('role', e.target.value)}>
                <option value="">— select —</option>
                <option>CFO / Finance Director</option>
                <option>Fractional CFO</option>
                <option>Controller</option>
                <option>Finance Manager</option>
                <option>Finance professional</option>
                <option>IT / Systems</option>
                <option>Other</option>
              </select>
              {errors.role && <div className="field-error">{errors.role}</div>}
            </div>

            <div className="field">
              <label htmlFor="q-work">2. How you work <span className="req">*</span></label>
              <select id="q-work" value={form.work_type} className={errors.work_type ? 'invalid' : ''}
                onChange={e => set('work_type', e.target.value)}>
                <option value="">— select —</option>
                <option>In-house (single group)</option>
                <option>External advisor or consultant</option>
                <option>Both</option>
              </select>
              {errors.work_type && <div className="field-error">{errors.work_type}</div>}
            </div>

            <div className="field">
              <label htmlFor="q-scope">3. How many legal entities or client groups does your work cover? <span className="req">*</span></label>
              <select id="q-scope" value={form.scope} className={errors.scope ? 'invalid' : ''}
                onChange={e => set('scope', e.target.value)}>
                <option value="">— select —</option>
                <option>1–5</option>
                <option>6–20</option>
                <option>21–50</option>
                <option>51+</option>
              </select>
              {errors.scope && <div className="field-error">{errors.scope}</div>}
            </div>
          </div>

          {/* Section 2 */}
          <div className="survey-section">
            <div className="survey-section-hdr">Section 2 — Your current situation</div>

            <div className="field">
              <label>4. How significant a pain point is <strong>intercompany reconciliation</strong> in your current close process? <span className="req">*</span></label>
              <RatingField field="pain_interco" error={errors.pain_interco} lowLabel="1 — minor irritant" highLabel="5 — major blocker" />
            </div>

            <div className="field">
              <label>5. How much manual effort does your team spend on <strong>bank-vs-ledger reconciliation</strong> each period? <span className="req">*</span></label>
              <RatingField field="pain_bank" error={errors.pain_bank} lowLabel="1 — almost none" highLabel="5 — days of work" />
            </div>

            <div className="field">
              <label htmlFor="q-toolsupport">6. Are these processes currently supported by dedicated tools? <span className="req">*</span></label>
              <select id="q-toolsupport" value={form.tool_support} className={errors.tool_support ? 'invalid' : ''}
                onChange={e => set('tool_support', e.target.value)}>
                <option value="">— select —</option>
                <option>Not at all</option>
                <option>Partially</option>
                <option>Fully covered</option>
              </select>
              {errors.tool_support && <div className="field-error">{errors.tool_support}</div>}
            </div>

            {needsToolAdequacy && (
              <div className="field">
                <label>7. How well do those tools address your needs? <span className="req">*</span></label>
                <RatingField field="tool_adequacy" error={errors.tool_adequacy} lowLabel="1 — poorly" highLabel="5 — fully" />
              </div>
            )}
          </div>

          {/* Section 3 */}
          <div className="survey-section">
            <div className="survey-section-hdr">Section 3 — Fit &amp; intent</div>

            <div className="field">
              <label>8. How well does Nexus seem to address your needs? <span className="req">*</span></label>
              <RatingField field="nexus_fit" error={errors.nexus_fit} lowLabel="1 — poor fit" highLabel="5 — exactly what we need" />
            </div>

            <div className="field">
              <label>9. How disappointed would you be if a tool like Nexus were no longer available? <span className="req">*</span></label>
              <RatingField field="pmf" error={errors.pmf} lowLabel="1 — not at all" highLabel="5 — very disappointed" />
            </div>

            <div className="field">
              <label htmlFor="q-mustdo">10. What is the single most important thing Nexus would need to do well for you to adopt it? <span className="req">*</span></label>
              <textarea id="q-mustdo" value={form.must_do} className={errors.must_do ? 'invalid' : ''}
                onChange={e => set('must_do', e.target.value)}
                placeholder="e.g. Handle multi-currency FX differences automatically…"
                rows={3} />
              {errors.must_do && <div className="field-error">{errors.must_do}</div>}
            </div>
          </div>

          {/* Section 4 */}
          <div className="survey-section">
            <div className="survey-section-hdr">Section 4 — The Sterna initiative</div>

            <div className="field">
              <label htmlFor="q-suite">11. Do you have suggestions for other tools or capabilities you'd like to see added to the Sterna suite? <span className="opt">(optional)</span></label>
              <textarea id="q-suite" value={form.suite_suggestions}
                onChange={e => set('suite_suggestions', e.target.value)}
                placeholder="e.g. Cash flow forecasting, automated disclosure drafting…"
                rows={3} />
            </div>
          </div>

          {/* Contact */}
          <div className="survey-section">
            <div className="survey-section-hdr">Contact</div>

            <div className="field survey-email-field">
              <label htmlFor="q-email">Email address <span className="req">*</span></label>
              <input id="q-email" type="email" value={form.email} className={errors.email ? 'invalid' : ''}
                onChange={e => set('email', e.target.value)} placeholder="you@company.com" />
              {errors.email && <div className="field-error">{errors.email}</div>}
            </div>

            <div className="field">
              <label htmlFor="q-additional">Any additional considerations on the Sterna initiative? <span className="opt">(optional)</span></label>
              <textarea id="q-additional" value={form.additional}
                onChange={e => set('additional', e.target.value)}
                placeholder="Anything else you'd like us to know…"
                rows={3} />
            </div>

            <label className="optin-row">
              <input type="checkbox" checked={form.optin} onChange={e => set('optin', e.target.checked)} />
              <span>I'm happy to be contacted about Nexus updates and early-access offers</span>
            </label>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginTop: 8 }}>
            <button type="submit" className="btn btn-primary btn-lg" disabled={busy}>
              {busy ? 'Sending…' : 'Submit questionnaire →'}
            </button>
            <button type="button" onClick={cancel}
              style={{ background: 'none', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--ink-500)', fontSize: '0.9rem', fontWeight: 500, cursor: 'pointer', padding: '10px 22px' }}>
              Cancel
            </button>
          </div>

        </form>
      </div>
    </section>
  );
};

/* ── Footer ── */
const Footer = ({ onSignIn, onRegister }) => (
  <footer>
    <div className="footer-inner">
      <div className="footer-top">
        <div className="footer-brand">
          <div className="row">
            <SternaLogo size={42} />
            <div>
              <div className="brand-mark" style={{ color: '#fff', fontSize: '1rem' }}>STERNA</div>
              <div className="brand-sub" style={{ color: 'var(--wing-300)' }}>INITIATIVE</div>
            </div>
          </div>
          <p>A growing suite of focused tools for the office of the CFO. Nexus is the first release — built to automate intercompany matching and statement reconciliation.</p>
        </div>
        <div className="footer-col">
          <h4>Suite</h4>
          <a href="#nexus">Sterna Nexus</a>
          <a href="#suite">Sterna Atlas</a>
          <a href="#suite">Sterna Echo</a>
          <a href="#suite">Sterna Compass</a>
        </div>
        <div className="footer-col">
          <h4>Resources</h4>
          <a href="#how">How it works</a>
          <a href="#feedback">Feedback</a>
          <a href="mailto:info@sternainitiative.com">Contact us</a>
          <a href="#feedback">Questionnaire</a>
        </div>
        <div className="footer-col">
          <h4>Account</h4>
          <a href="/app">Open Nexus</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onSignIn(); }}>Sign in</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onRegister(); }}>Register</a>
        </div>
      </div>
      <div className="footer-bottom">
        <div className="legal">
          <strong>Trial / feasibility release.</strong> This site and the Sterna tools are provided for evaluation only and are subject to change without notice. No warranty is offered; uploaded data is processed in private workspaces but should not be considered production-grade. © 2026 Sterna Initiative. · For inquiries: <a href="mailto:info@sternainitiative.com" style={{color:'rgba(255,255,255,0.5)'}}>info@sternainitiative.com</a>
        </div>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: '0.74rem', color: 'rgba(255,255,255,0.35)' }}>
          v0.4.2 · trial
        </div>
      </div>
    </div>
  </footer>
);

/* ── Auth modals ── */
const Modal = ({ children, onClose }) => {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-hdr">
          <SternaLogo size={32} />
          <div className="stack"><div className="name">STERNA</div><div className="sub">INITIATIVE</div></div>
          <button className="close" onClick={onClose} aria-label="Close">✕</button>
        </div>
        {children}
      </div>
    </div>
  );
};

const SignInModal = ({ onClose, onSwap }) => {
  const [step, setStep]           = React.useState('credentials');
  const [username, setUsername]   = React.useState('');
  const [password, setPassword]   = React.useState('');
  const [tenants, setTenants]     = React.useState([]);
  const [workspace, setWorkspace] = React.useState('');
  const [err, setErr]             = React.useState('');
  const [busy, setBusy]           = React.useState(false);
  const [forgotEmail, setForgotEmail] = React.useState('');
  const [forgotSent, setForgotSent]   = React.useState(false);

  const submitForgot = async (e) => {
    e.preventDefault();
    if (!forgotEmail.trim()) return;
    setBusy(true);
    await fetch('/auth/forgot-password', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: forgotEmail.trim() }),
    }).catch(() => {});
    setBusy(false);
    setForgotSent(true);
  };

  const submitCredentials = async (e) => {
    e.preventDefault();
    setErr('');
    if (!username.trim() || !password) { setErr('Please enter your username and password.'); return; }
    setBusy(true);
    const r = await fetch('/auth/login', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: username.trim(), password }),
    }).then(x => x.json()).catch(() => ({ detail: 'Cannot reach server' }));
    setBusy(false);
    if (r.choose_tenant) {
      setTenants(r.tenants || []);
      setWorkspace(r.tenants?.[0]?.id || '');
      setStep('workspace');
      return;
    }
    if (!r.ok || r.detail) { setErr(r.detail || 'Invalid credentials.'); return; }
    window.location.href = '/app';
  };

  const submitWorkspace = async (e) => {
    e.preventDefault();
    setErr('');
    setBusy(true);
    const r = await fetch('/auth/login', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password, tenant_id: workspace }),
    }).then(x => x.json()).catch(() => ({ detail: 'Cannot reach server' }));
    setBusy(false);
    if (!r.ok || r.detail) { setErr(r.detail || 'Something went wrong.'); return; }
    window.location.href = '/app';
  };

  if (step === 'forgot') return (
    <Modal onClose={onClose}>
      <div className="modal-body">
        <h2>Reset your password</h2>
        <p className="sub">Enter your email and we'll send you a reset link.</p>
        {forgotSent
          ? <div className="alert ok">✓ If an account exists for that email, a reset link has been sent.</div>
          : <form onSubmit={submitForgot} noValidate>
              <div className="field">
                <label htmlFor="si-forgot-email">Email address</label>
                <input id="si-forgot-email" type="email" value={forgotEmail}
                  onChange={(e) => setForgotEmail(e.target.value)} autoFocus />
              </div>
              <div className="submit-row">
                <button type="submit" className="btn btn-primary" disabled={busy}>{busy ? 'Sending…' : 'Send reset link'}</button>
                <button type="button" className="btn btn-ghost" onClick={() => setStep('credentials')}>Back</button>
              </div>
            </form>
        }
        {forgotSent && <div className="swap"><a onClick={() => setStep('credentials')} style={{ cursor: 'pointer' }}>← Back to sign in</a></div>}
      </div>
    </Modal>
  );

  return (
    <Modal onClose={onClose}>
      <div className="modal-body">
        <h2>{step === 'credentials' ? 'Sign in to Sterna' : 'Choose a workspace'}</h2>
        <p className="sub">
          {step === 'credentials'
            ? 'Enter your credentials to continue.'
            : `Signed in as ${username}. Select a workspace to continue.`}
        </p>
        {err && <div className="alert err">{err}</div>}
        <form onSubmit={step === 'credentials' ? submitCredentials : submitWorkspace} noValidate>
          {step === 'credentials' ? (
            <React.Fragment>
              <div className="field">
                <label htmlFor="si-user">Username</label>
                <input id="si-user" type="text" value={username}
                  onChange={(e) => setUsername(e.target.value)} autoComplete="username" autoFocus />
              </div>
              <div className="field">
                <label htmlFor="si-pass">Password</label>
                <input id="si-pass" type="password" value={password}
                  onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
              </div>
            </React.Fragment>
          ) : (
            <div className="field">
              <label htmlFor="si-ws">Workspace</label>
              <select id="si-ws" value={workspace} onChange={(e) => setWorkspace(e.target.value)} autoFocus>
                {tenants.map(t => (
                  <option key={t.id} value={t.id}>{t.name}</option>
                ))}
              </select>
            </div>
          )}
          <div className="submit-row">
            <button type="submit" className="btn btn-primary" disabled={busy}>
              {busy ? 'Working…' : step === 'credentials' ? 'Continue →' : 'Sign in'}
            </button>
            {step === 'workspace' && (
              <button type="button" className="btn btn-ghost" onClick={() => setStep('credentials')}>Back</button>
            )}
          </div>
        </form>
        {step === 'workspace' && (
          <div className="swap">Need a new workspace? <a href="/register" style={{ cursor: 'pointer' }}>Create one →</a></div>
        )}
        {step === 'credentials' && (
          <div className="swap">
            No account? <a onClick={onSwap} style={{ cursor: 'pointer' }}>Request access →</a>
            &nbsp;·&nbsp;
            <a onClick={() => setStep('forgot')} style={{ cursor: 'pointer' }}>Forgot password?</a>
          </div>
        )}
      </div>
    </Modal>
  );
};

const RegisterModal = ({ onClose, onSwap }) => {
  const [mode, setMode] = React.useState('create');
  const [form, setForm] = React.useState({ username: '', email: '', password: '', password2: '', wsName: '', wsCode: '', invite: '' });
  const [errors, setErrors] = React.useState({});
  const [busy, setBusy]   = React.useState(false);
  const [done, setDone]   = React.useState(false);
  const [doneMsg, setDoneMsg] = React.useState('');

  const slug = (s) => s.toLowerCase().replace(/[^a-z0-9\s-]/g, '').trim().replace(/\s+/g, '-').slice(0, 50);

  const validate = () => {
    const e = {};
    if (!form.username.trim()) e.username = 'Required.';
    if (!form.email.trim()) e.email = 'Required.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Invalid email.';
    if (!form.password) e.password = 'Required.';
    else if (form.password.length < 8) e.password = 'At least 8 characters.';
    if (form.password !== form.password2) e.password2 = "Passwords don't match.";
    if (mode === 'create') {
      if (!form.wsName.trim()) e.wsName = 'Workspace name required.';
      if (!form.wsCode.trim()) e.wsCode = 'Workspace code required.';
    } else {
      if (!form.invite.trim()) e.invite = 'Invite key required.';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setBusy(true);
    const r = await fetch('/auth/register', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username:      form.username.trim(),
        email:         form.email.trim().toLowerCase(),
        password:      form.password,
        tenant_action: mode,
        tenant_id:     form.wsCode.trim(),
        tenant_name:   form.wsName.trim(),
        invite_key:    form.invite.trim(),
      }),
    }).then(x => x.json()).catch(() => ({ detail: 'Cannot reach server' }));
    setBusy(false);
    if (!r.ok || r.detail) {
      setErrors({ _api: r.detail || 'Registration failed. Please try again.' });
      return;
    }
    setDone(true);
    setDoneMsg(mode === 'create'
      ? `Account created! Workspace code: ${form.wsCode}. You can now sign in.`
      : `Account created! You have joined the workspace. You can now sign in.`);
    setTimeout(() => onSwap(), 2500);
  };

  const set = (k, v) => setForm({ ...form, [k]: v });

  return (
    <Modal onClose={onClose}>
      <div className="modal-body">
        <h2>Request trial access</h2>
        <p className="sub">Set up an account in seconds — create a private workspace, or join a colleague's with an invite key.</p>
        {done && <div className="alert ok">✓ {doneMsg}</div>}
        {errors._api && <div className="alert err">{errors._api}</div>}
        {!done && (
          <form onSubmit={submit} noValidate>
            <div className="field-row" style={{ marginBottom: 14 }}>
              <div className="field">
                <label htmlFor="rg-user">Username</label>
                <input id="rg-user" type="text" value={form.username} className={errors.username ? 'invalid' : ''}
                  onChange={(e) => set('username', e.target.value)} placeholder="jordan_park" autoFocus />
                {errors.username && <div className="field-error">{errors.username}</div>}
              </div>
              <div className="field">
                <label htmlFor="rg-email">Work email</label>
                <input id="rg-email" type="email" value={form.email} className={errors.email ? 'invalid' : ''}
                  onChange={(e) => set('email', e.target.value)} placeholder="jordan@company.com" />
                {errors.email && <div className="field-error">{errors.email}</div>}
              </div>
            </div>
            <div className="field-row" style={{ marginBottom: 14 }}>
              <div className="field">
                <label htmlFor="rg-pass">Password</label>
                <input id="rg-pass" type="password" value={form.password} className={errors.password ? 'invalid' : ''}
                  onChange={(e) => set('password', e.target.value)} placeholder="Min 8 characters" />
                {errors.password && <div className="field-error">{errors.password}</div>}
              </div>
              <div className="field">
                <label htmlFor="rg-pass2">Confirm</label>
                <input id="rg-pass2" type="password" value={form.password2} className={errors.password2 ? 'invalid' : ''}
                  onChange={(e) => set('password2', e.target.value)} placeholder="Repeat" />
                {errors.password2 && <div className="field-error">{errors.password2}</div>}
              </div>
            </div>
            <div className="ws-toggle">
              <button type="button" className={mode === 'create' ? 'active' : ''} onClick={() => setMode('create')}>＋ Create workspace</button>
              <button type="button" className={mode === 'invite' ? 'active' : ''} onClick={() => setMode('invite')}>→ Join with invite key</button>
            </div>
            {mode === 'create' ? (
              <React.Fragment>
                <div className="field">
                  <label htmlFor="rg-wsname">Workspace name</label>
                  <input id="rg-wsname" type="text" value={form.wsName} className={errors.wsName ? 'invalid' : ''}
                    onChange={(e) => { set('wsName', e.target.value); if (!form.wsCode || form.wsCode === slug(form.wsName)) set('wsCode', slug(e.target.value)); }}
                    placeholder="e.g. Acme Group 2026" />
                  {errors.wsName && <div className="field-error">{errors.wsName}</div>}
                </div>
                <div className="field">
                  <label htmlFor="rg-wscode">Workspace code <span style={{ color: 'var(--ink-400)', fontWeight: 400 }}>· auto-suggested</span></label>
                  <input id="rg-wscode" type="text" value={form.wsCode} className={errors.wsCode ? 'invalid' : ''}
                    onChange={(e) => set('wsCode', e.target.value)} placeholder="acme-group-2026" />
                  {errors.wsCode && <div className="field-error">{errors.wsCode}</div>}
                </div>
              </React.Fragment>
            ) : (
              <div className="field">
                <label htmlFor="rg-invite">Invite key</label>
                <input id="rg-invite" type="text" value={form.invite} className={errors.invite ? 'invalid' : ''}
                  onChange={(e) => set('invite', e.target.value)} placeholder="Paste the one-time key from your workspace admin" />
                {errors.invite && <div className="field-error">{errors.invite}</div>}
              </div>
            )}
            <div className="submit-row">
              <button type="submit" className="btn btn-primary" disabled={busy}>
                {busy ? 'Submitting…' : mode === 'create' ? 'Create account' : 'Join workspace'}
              </button>
            </div>
          </form>
        )}
        <div className="swap">Already have an account? <a onClick={onSwap} style={{ cursor: 'pointer' }}>Sign in →</a></div>
      </div>
    </Modal>
  );
};

/* ── Toast ── */
const Toast = ({ message }) => message ? <div className="toast">{message}</div> : null;
