// Landing page — top-level app. Owns the nav, sponsor strip, final CTA, footer,
// and the shared DeployModal / companion state. Content sections live in
// landing-sections.jsx; hero in landing-hero.jsx.

// ---- top nav (transparent over hero, glass once scrolled) ----
const NAV_LINKS = [
  { href: '#how', label: 'How it works' },
  { href: '#apps', label: 'Apps' },
  { href: 'Community.html', label: 'Community' },
  { label: 'AI Labs', children: [
    { href: '#labs', label: 'Browse AI Labs' },
    { href: '#research', label: 'Tune a model' },
    { href: '#maturity', label: 'Maturity' },
    { href: '#proof', label: 'Proof' },
  ] },
];

const LandingNav = ({ onExploreLabs }) => {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`lp-nav ${scrolled ? 'scrolled' : ''}`} data-screen-label="Landing Nav">
      <div className="lp-wrap lp-nav-inner">
        <a className="lp-brand" href="#top" aria-label="ActionBoard.ai">
          <img className="lp-brand-icon" src="assets/actionboard-app-logo.png" alt="ActionBoard.ai" />
        </a>
        <div className="lp-nav-links">
          {NAV_LINKS.map(l => l.children ? (
            <div className="lp-nav-drop" key={l.label}>
              <button type="button" className="lp-nav-drop-btn">{l.label}<svg className="lp-caret" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6" /></svg></button>
              <div className="lp-nav-menu">
                {l.children.map(c => <a key={c.href} href={c.href}>{c.label}</a>)}
              </div>
            </div>
          ) : (
            <a key={l.href} href={l.href}>{l.label}</a>
          ))}
        </div>
        <div className="lp-nav-mech" aria-hidden="true">
          <span className="lp-mech-gear lp-mech-gear-1"><I.Settings size={20} /></span>
          <span className="lp-mech-gear lp-mech-gear-2"><I.Settings size={14} /></span>
          <span className="lp-mech-lever">
            <svg width="30" height="20" viewBox="0 0 30 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              <line x1="4" y1="16" x2="26" y2="16" />
              <g className="lp-lever-arm"><line x1="15" y1="16" x2="24" y2="6" /><circle cx="24" cy="6" r="2.4" fill="currentColor" stroke="none" /></g>
              <circle cx="15" cy="16" r="2" fill="currentColor" stroke="none" />
            </svg>
          </span>
        </div>
        <div className="lp-nav-cta">
          <a className="lp-nav-signin" href="Signup.html">Sign in</a>
          <a className="lp-btn lp-btn-primary lp-btn-sm" href="Signup.html">
            <I.Sparkles size={13} /> Sign up
          </a>
        </div>
      </div>
    </nav>
  );
};

// ---- final CTA ----
const ACTION_PRO_FEATURES = [
  { icon: 'Link', title: 'Linked Action Board', body: 'Your public SME profile wires to a private Action Board that auto-triages incoming work-order requests.' },
  { icon: 'Card', title: 'Stripe Wallet', body: 'Get paid on completion — a Stripe-backed wallet settles SME work orders in your currency.' },
  { icon: 'User', title: 'B2B Payment Agents', body: 'Agents negotiate scope, raise invoices, and reconcile payments between businesses for you.' },
];
const ActionProSection = () => (
  <section id="pro" className="lp-pro lp-has-gears" data-screen-label="Action Pro">
    <SectionGears />
    <div className="lp-wrap lp-pro-grid">
      <div className="lp-pro-copy">
        <div className="lp-eyebrow"><I.Sparkle2 size={12} /> ACTION PRO <span className="lp-pro-soon">COMING SOON</span></div>
        <h2 className="lp-pro-title">Register your public AIOps SME Profile ActionPanel.</h2>
        <p className="lp-pro-lead text-pretty">Under development — a public profile that turns your expertise into an automated service. Incoming SME work-order requests route to a linked Action Board, while a Stripe Wallet and B2B Payment Agents handle the money.</p>
        <div className="lp-pro-feats">
          {ACTION_PRO_FEATURES.map(f => { const Ico = I[f.icon] || I.Sparkle2; return (
            <div className="lp-pro-feat" key={f.title}>
              <span className="lp-pro-feat-ico"><Ico size={16} /></span>
              <div><h4>{f.title}</h4><p className="text-pretty">{f.body}</p></div>
            </div>); })}
        </div>
        <div className="lp-pro-cta">
          <button className="lp-btn lp-btn-primary lp-btn-lg" disabled><I.Lock size={14} /> Register interest — soon</button>
          <a className="lp-btn lp-btn-ghost lp-btn-lg" href="SME-Profile.html">Preview a sample profile <I.ArrowRight size={14} /></a>
        </div>
      </div>
      <div className="lp-pro-preview">
        <span className="lp-pro-ribbon">Coming soon</span>
        <div className="lp-pro-card">
          <div className="lp-pro-card-head">
            <span className="lp-pro-ava">🦁</span>
            <div>
              <div className="lp-pro-name">Your SME Profile <span className="lp-pro-verif"><I.Check size={10} strokeWidth={3} /> VERIFIED SME</span></div>
              <div className="lp-pro-mcp mono">mcp://actionboard.ai/pro/your-handle</div>
            </div>
          </div>
          <div className="lp-pro-stats">
            <div><b>Level 4</b><span>maturity</span></div>
            <div><b>4.9</b><span>SME rating</span></div>
            <div><b>Auto</b><span>work orders</span></div>
          </div>
          <div className="lp-pro-flow">
            <span className="lp-pro-chip">New work order</span>
            <I.ArrowRight size={13} />
            <span className="lp-pro-chip on">Linked board</span>
            <I.ArrowRight size={13} />
            <span className="lp-pro-chip pay">Stripe payout</span>
          </div>
          <div className="lp-pro-badges">
            <span className="badge badge-violet">Linked board</span>
            <span className="badge badge-emerald">Stripe wallet</span>
            <span className="badge badge-sky">B2B agents</span>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const EnterpriseSection = () => {
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const submit = (e) => { e.preventDefault(); const v = ((e.target.elements && e.target.elements.entEmail && e.target.elements.entEmail.value) || email).trim(); if (!v) return; setEmail(v); setSent(true); };
  return (
    <section id="enterprise" className="lp-ent lp-has-gears" data-screen-label="Enterprise Cohort">
      <SectionGears />
      <div className="lp-wrap lp-ent-inner">
        <div className="lp-eyebrow" style={{ justifyContent: 'center' }}><I.Castle size={12} /> ENTERPRISE COHORT</div>
        <h2 className="lp-ent-title">Ready to test-drive Enterprise AIOps for your team?</h2>
        <p className="lp-ent-lead text-pretty">Drop your work email and we'll send an ActionBoard Enterprise AI Labs onboarding ActionList straight to your inbox. Open the email and click <strong>Start ActionList</strong> — your Castle spins up from there.</p>
        {!sent ? (
          <form className="lp-ent-form" onSubmit={submit}>
            <input type="email" name="entEmail" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" className="lp-ent-input" aria-label="Work email" />
            <button type="submit" className="lp-btn lp-btn-primary lp-btn-lg"><I.Sparkles size={15} /> Send my onboarding ActionList</button>
          </form>
        ) : (
          <div className="lp-ent-sent">
            <span className="lp-ent-check"><I.Check size={16} strokeWidth={3} /></span>
            <div>
              <div className="lp-ent-sent-title">ActionList on its way to {email}</div>
              <div className="lp-ent-sent-sub">Open your email and click <strong>Start ActionList</strong> to launch your Enterprise cohort onboarding.</div>
            </div>
          </div>
        )}
        <div className="lp-ent-meta mono">SOC2-ready · SSO / SCIM · dedicated onboarding partner · no card required</div>
      </div>
    </section>
  );
};

const CtaSection = () => (
  <section className="lp-cta" data-screen-label="Landing CTA">
    <div className="lp-cta-glow" />
    <div className="lp-wrap lp-cta-inner">
      <div className="lp-eyebrow" style={{ color: '#c4b5fd', justifyContent: 'center' }}>
        <I.Sparkle2 size={12} /> PILOT · FOUNDING ACCESS
      </div>
      <h2 className="lp-cta-title">Form your first Voltron today.</h2>
      <p className="lp-cta-lead text-pretty">
        Configure a Castle, deploy a sponsor lab, and run a full RAOARA loop before the day is out.
        Pilot seats include a starter token wallet and founding-member pricing.
      </p>
      <div className="lp-cta-actions">
        <button className="lp-btn lp-btn-primary lp-btn-lg" type="button" onClick={() => window.__openWaitlist && window.__openWaitlist()}><I.Castle size={15} /> Build your Castle</button>
        <a className="lp-btn lp-btn-ghost-light lp-btn-lg" href="Labs.html"><I.Lab size={15} /> Start from a lab</a>
      </div>
      <div className="lp-cta-meta mono">
        <span><span className="dot pulse" style={{ background: '#10b981' }} /> {PROFILE_USER.waitlistPosition ? `#${PROFILE_USER.waitlistPosition} on the pilot list` : 'pilot open'}</span>
        <span className="lp-cta-sep">·</span>
        <span>{`${formatTokens(PROFILE_USER.wallet || 240000)} starter tokens`}</span>
        <span className="lp-cta-sep">·</span>
        <span>no card required</span>
      </div>
    </div>
  </section>
);

// ---- footer ----
const FOOTER_COLS = [
  { title: 'Platform', links: [['Overview', 'Welcome.html'], ['Voltron', 'Voltron.html'], ['AI Pods', 'Pods.html'], ['Wallet', 'Wallet.html']] },
  { title: 'Labs', links: [['Browse labs', 'Labs.html'], ['How it works', '#how'], ['Maturity', '#maturity'], ['Ask the guide', '#ask']] },
  { title: 'Community', links: [['Join the AI SME community', 'Community.html'], ['Platform user guide', 'User-Guide.html'], ['Sample SME profile', 'SME-Profile.html'], ['YouTube channel', 'https://www.youtube.com/@ActionboardAI']] },
  { title: 'Company', links: [['Charter', '#'], ['Research', 'Labs.html'], ['Careers', '#'], ['Contact', 'mailto:support@actionboard.ai']] },
  { title: 'Legal', links: [['Terms of Service', 'Terms.html'], ['Security Policy', 'Security.html'], ['Data ownership', 'Security.html#ownership'], ['Proof-of-Thought', 'Security.html#audit']] },
];

const LandingFooter = () => (
  <footer className="lp-footer" data-screen-label="Landing Footer">
    <div className="lp-wrap lp-footer-grid">
      <div className="lp-foot-brand">
        <a className="lp-brand" href="#top" style={{ color: '#fff' }} aria-label="ActionBoard.ai">
          <img className="lp-brand-logo" src="assets/actionboard-logo.png" alt="ActionBoard.ai" />
        </a>
        <p className="lp-foot-tagline text-pretty">The AIOps orchestration platform. Recognize, Acquire, Organize, Act, Review, Adapt — as one loop.</p>
        <div className="lp-foot-social">
          {[['Youtube', 'https://www.youtube.com/@ActionboardAI'], ['Github', '#'], ['Twitter', '#'], ['Linkedin', '#'], ['Globe', 'Landing.html']].map(([k, href]) => {
            const Ico = I[k];
            const ext = /^https?:/.test(href);
            return <a key={k} href={href} className="lp-foot-soc" aria-label={k} {...(ext ? { target: '_blank', rel: 'noopener' } : {})}><Ico size={15} /></a>;
          })}
        </div>
      </div>
      {FOOTER_COLS.map(col => (
        <div className="lp-footer-col" key={col.title}>
          <div className="lp-foot-col-title">{col.title}</div>
          {col.links.map(([label, href]) => /^https?:/.test(href) ? <a key={label} href={href} target="_blank" rel="noopener">{label}</a> : <a key={label} href={href}>{label}</a>)}
        </div>
      ))}
    </div>
    <div className="lp-wrap lp-foot-bottom">
      <span>© 2026 ActionBoard.ai · A CloudsCockpit Inc. product · Pilot preview</span>
      <nav className="lp-foot-legal">
        <a href="Terms.html">Terms of Service</a>
        <span aria-hidden="true">·</span>
        <a href="Security.html">Security Policy</a>
      </nav>
    </div>
  </footer>
);

// ---- waitlist modal (opens from hero "Join the pilot") ----
const WAITLIST_PERKS = [
  'Founding-member pricing, locked for life',
  '240K starter token wallet on day one',
  'Priority Castle onboarding with a Voltron guide',
];

const WaitlistModal = ({ onClose }) => {
  const [email, setEmail] = React.useState('');
  const [phase, setPhase] = React.useState('form'); // form | sending | done
  const [err, setErr] = React.useState(false);
  const pos = (PROFILE_USER.waitlistPosition || 247) + 1;
  React.useEffect(() => {
    const k = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', k);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', k); document.body.style.overflow = ''; };
  }, [onClose]);
  const valid = (v) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v);
  const submit = (e) => {
    e.preventDefault();
    const v = email.trim();
    if (!valid(v)) { setErr(true); return; }
    setErr(false); setPhase('sending');
    setTimeout(() => setPhase('done'), 900);
  };
  const sending = phase === 'sending';
  return (
    <div className="wl-scrim" onClick={onClose}>
      <div className="wl-card" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" data-screen-label="Waitlist">
        <button className="wl-x" onClick={onClose} aria-label="Close">✕</button>
        {phase === 'done' ? (
          <div className="wl-check"><I.Check size={32} strokeWidth={3} /></div>
        ) : (
          <div className={'wl-env ' + (phase === 'form' ? 'is-open' : 'is-sending')} aria-hidden="true">
            <div className="wl-env-shadow" />
            <div className="wl-env-back" />
            <div className="wl-letter"><i /><i /><i /></div>
            <div className="wl-env-front" />
            <div className="wl-env-flap" />
          </div>
        )}
        {phase !== 'done' ? (
          <React.Fragment>
            <div className="lp-eyebrow" style={{ justifyContent: 'center', color: 'var(--violet)' }}><I.Sparkle2 size={12} /> PILOT · FOUNDING ACCESS</div>
            <h3 className="wl-title">Join the ActionBoard pilot</h3>
            <p className="wl-lead text-pretty">Founding seats are limited. Drop your email and we’ll send your onboarding ActionList the moment your seat opens.</p>
            <form className="wl-form" onSubmit={submit}>
              <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); setErr(false); }} placeholder="you@company.com" className={'wl-input' + (err ? ' err' : '')} aria-label="Email address" autoFocus disabled={sending} />
              <button type="submit" className="lp-btn lp-btn-primary lp-btn-lg wl-submit" disabled={sending}>
                {sending ? 'Sending…' : <React.Fragment><I.Sparkles size={15} /> Join the waitlist</React.Fragment>}
              </button>
            </form>
            {err && <div className="wl-err">Please enter a valid email address.</div>}
            <ul className="wl-perks">
              {WAITLIST_PERKS.map((p) => <li key={p}><span className="wl-perk-check"><I.Check size={11} strokeWidth={3} /></span>{p}</li>)}
            </ul>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <h3 className="wl-title">You’re on the list</h3>
            <p className="wl-lead text-pretty">We sent a confirmation to <strong>{email}</strong>. Open it and click <strong>Start ActionList</strong> when your seat opens.</p>
            <div className="wl-pos">
              <div className="wl-pos-badge mono">#{pos}</div>
              <div>
                <div className="wl-pos-title">Your spot on the pilot list</div>
                <div className="wl-pos-sub mono">240K starter tokens reserved · no card required</div>
              </div>
            </div>
            <button className="lp-btn lp-btn-primary lp-btn-lg wl-submit" onClick={onClose}>Done</button>
          </React.Fragment>
        )}
      </div>
    </div>
  );
};

// ---- composition ----
const LandingApp = () => {
  const [deployLab, setDeployLab] = React.useState(null);
  const [waitlistOpen, setWaitlistOpen] = React.useState(false);
  const [companionQuery, setCompanionQuery] = React.useState('');
  const [t, setTweak] = useTweaks(window.__LP_TWEAKS || {});
  React.useEffect(() => {
    if (!t.accent) return;
    document.documentElement.style.setProperty('--violet', t.accent);
    document.documentElement.style.setProperty('--violet-2', t.accent);
  }, [t.accent]);
  // Preview: desktop/installer CTAs across the page funnel into the waitlist.
  React.useEffect(() => {
    window.__openWaitlist = () => { window.location.href = 'Signup.html'; };
    return () => { if (window.__openWaitlist) delete window.__openWaitlist; };
  }, []);
  const gotoLabs = () => { window.location.hash = 'labs'; };
  const askAbout = (post) => { setCompanionQuery(`What does "${post.title}" mean for the ${post.relatedLabs[0]} lab?`); window.location.hash = 'ask'; };

  return (
    <div className="lp-root" data-screen-label="Landing">
      <GearFieldBG />
      <LandingNav onExploreLabs={gotoLabs} />
      <LandingHero onExploreLabs={gotoLabs} onJoinPilot={() => { window.location.href = 'Signup.html'; }} copy={t} />
      <GearsSection />
      <AppsSection />
      <TuneSection />
      <LabsSection onDeploy={setDeployLab} />
      <MaturitySection />
      <ProofSection />
      <CompanionSection companionQuery={companionQuery} setCompanionQuery={setCompanionQuery} onDeploy={setDeployLab} />
      <ActionProSection />
      <EnterpriseSection />
      <LandingFooter />

      {deployLab && (
        <DeployModal lab={deployLab} onClose={() => setDeployLab(null)} onConfirm={() => setDeployLab(null)} />
      )}

      {waitlistOpen && <WaitlistModal onClose={() => setWaitlistOpen(false)} />}

      <TweaksPanel title="Landing tweaks">
        <TweakSection label="Hero copy" />
        <TweakText label="Kicker" value={t.heroKicker} onChange={(v) => setTweak('heroKicker', v)} />
        <TweakText label="Headline" value={t.heroTitle} onChange={(v) => setTweak('heroTitle', v)} />
        <TweakText label="Highlight" value={t.heroAccent} onChange={(v) => setTweak('heroAccent', v)} />
        <TweakText label="Subhead" value={t.heroLead} onChange={(v) => setTweak('heroLead', v)} />
        <TweakText label="Primary CTA" value={t.ctaPrimary} onChange={(v) => setTweak('ctaPrimary', v)} />
        <TweakText label="Secondary CTA" value={t.ctaSecondary} onChange={(v) => setTweak('ctaSecondary', v)} />
        <TweakSection label="Theme" />
        <TweakColor label="Accent" value={t.accent} options={['#6d28d9', '#2563eb', '#059669', '#e11d48']} onChange={(v) => setTweak('accent', v)} />
      </TweaksPanel>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<LandingApp />);
