const { useState: useStateX, useEffect: useEffectX, useMemo: useMemoX } = React;

// ============================================================
// SCENARIOS — vertical-specific vignettes
// ============================================================
function Scenarios() {
  const scenarios = [
    {
      tag: 'Engineering · 200-person firm',
      title: 'Staffing a $40M controls engagement.',
      problem: 'You need three structural leads with FAA experience, four mid-level controls engineers, and bench capacity to absorb a 14-week scope. Your last answer to "who could lead this?" took three days and four Slack threads.',
      with: 'Eloreum returns the shortlist in eleven seconds — with attested capabilities, current allocation, recent project receipts, and a confidence band on each name.',
      metric: '3 days → 11 seconds',
    },
    {
      tag: 'Health system · Reorganizing oncology',
      title: 'Two service lines merging in eight weeks.',
      problem: 'Who has dual privileges? Whose CME aligns? Who has actually run the new protocol — not just trained on it? Today the answers live in five binders and three department heads\' memories.',
      with: 'Eloreum threads credentialing, scheduling, and clinical history into one queryable map — and surfaces the four people whose departures would put the merger at risk.',
      metric: 'Hidden risk surfaced in <1 minute',
    },
    {
      tag: 'Research lab · Defending a federal audit',
      title: 'Six years of provenance, ten days to compile.',
      problem: 'The auditor wants every decision, every approval, every revision — sourced. Your records exist. Finding them is the problem.',
      with: 'Eloreum reconstructs the chain across documents, calendars, and email threads — every claim cited to its original artifact. Your team spends the ten days reviewing, not searching.',
      metric: 'Hours to first audit-ready packet',
    },
  ];

  return (
    <section className="scenarios" id="scenarios">
      <div className="diagram-head">
        <span className="section-eyebrow">
          <span className="eyebrow-dash" />
          <span>§ 02b — built for the work you actually do</span>
        </span>
        <h3>Concrete. Specific. Yours.</h3>
        <p className="diagram-deck">
          Eloreum is opinionated about the verticals where it earns its keep. Here's what that looks like.
        </p>
      </div>

      <div className="scenarios-grid">
        {scenarios.map((s, i) => (
          <article className="scenario-card" key={i}>
            <div className="scenario-tag">{s.tag}</div>
            <h4 className="scenario-title">{s.title}</h4>

            <div className="scenario-block">
              <div className="scenario-label">— today</div>
              <p className="scenario-text">{s.problem}</p>
            </div>

            <div className="scenario-block scenario-with">
              <div className="scenario-label">— with eloreum</div>
              <p className="scenario-text">{s.with}</p>
            </div>

            <div className="scenario-metric">
              <span className="metric-arrow">→</span>
              <span>{s.metric}</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

// ============================================================
// ROI CALCULATOR — what is your org leaving on the table?
// ============================================================
function ROICalculator() {
  const [headcount, setHeadcount] = useStateX(200);
  const [minutes, setMinutes] = useStateX(45);
  const [salary, setSalary] = useStateX(120);

  // Per-person, per-week time burned answering "where is X / who knows Y / has anyone done Z"
  const annual = useMemoX(() => {
    const hoursPerYear = (minutes / 60) * 48; // 48 working weeks
    const cost = hoursPerYear * (salary * 1000 / 2000); // hourly cost
    return Math.round(headcount * cost);
  }, [headcount, minutes, salary]);

  const recovered = Math.round(annual * 0.7); // assume eloreum recovers 70%

  return (
    <section className="calc-section" id="calculator">
      <div className="diagram-head">
        <span className="section-eyebrow">
          <span className="eyebrow-dash" />
          <span>§ 04b — the cost of asking</span>
        </span>
        <h3>How much is your org spending on <em>"who knows this?"</em></h3>
        <p className="diagram-deck">
          A rough model of time burned every week chasing answers your organization already has. Not consulting fees. Not software licenses. Just the asking.
        </p>
      </div>

      <div className="calc-stage">
        <div className="calc-inputs">
          <CalcInput label="Headcount" suffix="people" min={10} max={5000} step={10} value={headcount} onChange={setHeadcount} />
          <CalcInput label="Minutes per person per week chasing answers" suffix="min" min={5} max={240} step={5} value={minutes} onChange={setMinutes} />
          <CalcInput label="Average fully-loaded salary" suffix="$K" min={50} max={400} step={5} value={salary} onChange={setSalary} />
        </div>

        <div className="calc-output">
          <div className="calc-row">
            <div className="calc-row-label">Annual cost · today</div>
            <div className="calc-row-value">${annual.toLocaleString()}</div>
          </div>
          <div className="calc-divider" />
          <div className="calc-row calc-recovered">
            <div className="calc-row-label">Recoverable with Eloreum</div>
            <div className="calc-row-value highlight">${recovered.toLocaleString()}</div>
          </div>
          <div className="calc-foot">
            Conservative model. 70% recovery rate based on early deployment benchmarks. Doesn't count what you're missing — only what you're spending.
          </div>
        </div>
      </div>
    </section>
  );
}

function CalcInput({ label, suffix, min, max, step, value, onChange }) {
  return (
    <label className="calc-input">
      <div className="calc-input-head">
        <span className="calc-input-label">{label}</span>
        <span className="calc-input-value">{value.toLocaleString()} {suffix}</span>
      </div>
      <input
        type="range"
        min={min} max={max} step={step}
        value={value}
        onChange={e => onChange(Number(e.target.value))}
      />
      <div className="calc-input-range">
        <span>{min.toLocaleString()}</span>
        <span>{max.toLocaleString()}</span>
      </div>
    </label>
  );
}

// ============================================================
// FOUNDERS / STORY
// ============================================================
function Founders() {
  return (
    <section className="founders-section" id="team">
      <div className="founders-grid">
        <div className="founders-copy">
          <div className="section-eyebrow">
            <span className="eyebrow-dash" />
            <span>§ 06 — who's building this</span>
          </div>
          <h2 className="founders-title">
            Built by people who've<br />
            <span className="founders-title-accent">run the org charts in question.</span>
          </h2>
          <p className="founders-text">
            Eloreum started inside a workforce intelligence problem that wouldn't go away: in skilled-labor organizations, the value lives in the people, the work lives in their heads, and the answers move slower than the questions. The platform you see here is what we wished existed.
          </p>
          <p className="founders-text">
            We're a small, opinionated team — built for the long game. Every customer in 2026 talks directly to the people writing the platform.
          </p>
          <div className="founders-cta">
            <a href="#access" className="founders-link">Talk to a founder →</a>
          </div>
        </div>

        <div className="founders-people">
          <FounderCard initials="JT" name="Founder Name" role="Founder & CEO" />
          <FounderCard initials="AB" name="Founder Name" role="Co-founder & CTO" />
          <FounderCard initials="MS" name="Founder Name" role="Head of Platform" />
        </div>
      </div>
    </section>
  );
}

function FounderCard({ initials, name, role }) {
  return (
    <div className="founder-card">
      <div className="founder-avatar">
        <span>{initials}</span>
      </div>
      <div className="founder-name">{name}</div>
      <div className="founder-role">{role}</div>
    </div>
  );
}

// ============================================================
// FAQ
// ============================================================
function FAQ() {
  const faqs = [
    {
      q: 'What is Eloreum, in one sentence?',
      a: 'An enterprise AI agent operating system that turns what your people actually know into something your whole organization can ask — with sources, in seconds.',
    },
    {
      q: 'Is my data really private?',
      a: 'Yes. Your data lives inside a tenant enclave that only you can reach. It is never trained into shared models, never visible to other customers, and never visible to us. Encryption at rest and in transit. Every action signed and audit-logged.',
    },
    {
      q: 'How are answers verified?',
      a: 'Every response is reviewed by an independent agent for accuracy, tone, and boundary compliance before it reaches a human. Nothing untrue or unsafe slips through. You see what\'s right — not what\'s first.',
    },
    {
      q: 'Who is Eloreum built for?',
      a: 'Organizations whose value depends on what their people know. Engineering firms, health systems, professional services, defense contractors, research labs, manufacturing, the trades. Anywhere expertise, certification, capacity, and judgment drive outcomes.',
    },
    {
      q: 'What does it cost?',
      a: 'Pricing is anchored to organization size and use case. 2026 design partners get pricing locked for v1.x. We don\'t publish a number publicly because we won\'t quote you without understanding the work — and we won\'t take you on if the fit isn\'t real.',
    },
    {
      q: 'How quickly can we be up and running?',
      a: 'Days, not quarters. Tenant provisioning is automated. The first agent meets your team in week one. The knowledge map deepens with every interaction.',
    },
    {
      q: 'What if we want to leave?',
      a: 'Export the graph, the conversation history, the audit trail — at any time, in open formats. Nothing about Eloreum is designed to lock you in. Your knowledge is yours.',
    },
    {
      q: 'Do you sign NDAs and BAAs?',
      a: 'Yes. For healthcare and regulated industries, we sign appropriate agreements before any data crosses the line.',
    },
  ];
  const [open, setOpen] = useStateX(0);
  return (
    <section className="faq-section" id="faq">
      <div className="faq-head">
        <div className="section-eyebrow">
          <span className="eyebrow-dash" />
          <span>§ 07 — frequently asked</span>
        </div>
        <h2 className="faq-title">Common questions.</h2>
      </div>
      <div className="faq-list">
        {faqs.map((f, i) => (
          <div className={`faq-item ${open === i ? 'open' : ''}`} key={i}>
            <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
              <span className="faq-q-num">0{i + 1}</span>
              <span className="faq-q-text">{f.q}</span>
              <span className="faq-q-toggle">{open === i ? '−' : '+'}</span>
            </button>
            <div className="faq-a-wrap">
              <div className="faq-a">{f.a}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============================================================
// FIELD GUIDE — secondary lead magnet
// ============================================================
function FieldGuide() {
  const [email, setEmail] = useStateX('');
  const [sent, setSent] = useStateX(false);
  function submit(e) {
    e.preventDefault();
    if (!email) return;
    setSent(true);
  }
  return (
    <section className="fieldguide" id="fieldguide">
      <div className="fg-inner">
        <div className="fg-left">
          <div className="fg-eyebrow">
            <span className="eyebrow-dash" />
            <span>§ 08 — not ready to talk?</span>
          </div>
          <h2 className="fg-title">
            Take the field guide instead.
          </h2>
          <p className="fg-text">
            A short, plainspoken brief on how Eloreum works, what changes in your org, and the trade-offs most buyers ask about by week three. Read in fifteen minutes. No demo required.
          </p>
          <ul className="fg-list">
            <li>— What Eloreum changes in a 200-person firm</li>
            <li>— The security posture, in language your CISO speaks</li>
            <li>— What deployment week one actually looks like</li>
            <li>— Where Eloreum is the wrong tool</li>
          </ul>
        </div>
        <div className="fg-right">
          {!sent ? (
            <form className="fg-form" onSubmit={submit}>
              <div className="fg-form-icon">
                <svg width="40" height="48" viewBox="0 0 40 48" fill="none">
                  <rect x="3" y="3" width="30" height="40" rx="2" stroke="currentColor" strokeWidth="1.5" />
                  <rect x="8" y="3" width="30" height="40" rx="2" stroke="currentColor" strokeWidth="1.5" fill="currentColor" fillOpacity="0.1" />
                  <line x1="14" y1="14" x2="32" y2="14" stroke="currentColor" strokeWidth="1" />
                  <line x1="14" y1="20" x2="32" y2="20" stroke="currentColor" strokeWidth="1" />
                  <line x1="14" y1="26" x2="28" y2="26" stroke="currentColor" strokeWidth="1" />
                  <line x1="14" y1="32" x2="32" y2="32" stroke="currentColor" strokeWidth="1" />
                </svg>
              </div>
              <div className="fg-form-meta">
                <span>PDF · 12 pages · 4MB</span>
              </div>
              <label className="fg-label">
                <span>your work email</span>
                <input
                  type="email"
                  required
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  placeholder="you@yourorg.com"
                />
              </label>
              <button type="submit" className="btn-primary btn-block">
                <span>Send me the guide</span>
                <span className="btn-arrow">↓</span>
              </button>
              <div className="fg-foot">No follow-up unless you ask for it.</div>
            </form>
          ) : (
            <div className="fg-form fg-form-sent">
              <div className="fg-sent-glyph">✓</div>
              <div className="fg-sent-title">On its way.</div>
              <div className="fg-sent-text">Check your inbox in the next few minutes.</div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// STICKY CTA BAR — appears after scroll past hero
// ============================================================
function StickyCTA({ onRequestAccess }) {
  const [show, setShow] = useStateX(false);
  const [dismissed, setDismissed] = useStateX(false);
  useEffectX(() => {
    function onScroll() {
      const y = window.scrollY;
      const threshold = window.innerHeight * 0.9;
      const docH = document.documentElement.scrollHeight;
      const nearEnd = y + window.innerHeight > docH - 600;
      setShow(y > threshold && !nearEnd);
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (dismissed) return null;
  return (
    <div className={`sticky-cta ${show ? 'visible' : ''}`}>
      <div className="sticky-cta-inner">
        <div className="sticky-cta-text">
          <span className="pulse-dot" />
          <span><strong>14 design-partner slots.</strong> Pricing locked for v1.x.</span>
        </div>
        <div className="sticky-cta-actions">
          <button className="sticky-cta-btn" onClick={onRequestAccess}>
            <span>Request Access</span>
            <span className="btn-arrow">→</span>
          </button>
          <button className="sticky-cta-close" onClick={() => setDismissed(true)} aria-label="Dismiss">×</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Scenarios, ROICalculator, Founders, FAQ, FieldGuide, StickyCTA });
