/* Platform / ApexBridge detail page */
const { useState, useEffect, useRef, useCallback } = React;

/* ---------- Reveal ---------- */
const useReveal = () => {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -80px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
};

/* ---------- Nav ---------- */
const Nav = ({ onDemoClick }) => {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href="index.html" className="logo">
          <img src="assets/atc-mark.png" alt="ATC" />
          <span className="logo-text">ATC<span className="dim">·</span></span>
        </a>
        <div className="nav-links">
          <a className="nav-link" href="platform.html" style={{color: 'var(--text)'}}>Platform</a>
          <a className="nav-link" href="index.html#solutions">Solutions</a>
          <a className="nav-link" href="index.html#customers">Customers</a>
          <a className="nav-link" href="index.html#news">News</a>
          <a className="nav-link" href="index.html#about">About</a>
          <button className="btn btn-primary nav-cta" onClick={onDemoClick}>Request Demo →</button>
        </div>
      </div>
    </nav>
  );
};

/* ---------- Hero ---------- */
const PlatformHero = ({ onDemoClick }) => (
  <section className="platform-hero">
    <div className="hero-grid" />
    <div className="container">
      <div className="breadcrumb">
        <a href="index.html">ATC</a><span className="sep">/</span>
        <a href="platform.html">Platform</a><span className="sep">/</span>
        <span style={{color: 'var(--accent)'}}>ApexBridge</span>
      </div>
      <div className="layout">
        <div>
          <div className="product-tag">
            <span className="accent">●</span> Flagship · Production · v2.4
          </div>
          <h1>Apex<br/><span className="accent">Bridge</span>.</h1>
          <p className="lede">
            The AI-native migration system for Oracle Forms and Oracle VBCS.
            Deterministic AST translator, agentic repair loop, end-to-end APEX delivery.
            Engineers review, they don't rewrite.
          </p>
          <div className="hero-actions">
            <button className="btn btn-primary" onClick={onDemoClick}>Request a Demo →</button>
            <a className="btn btn-ghost" href="#how-it-works">How it works ↓</a>
          </div>
        </div>
        <div className="product-mark">
          <div className="ring" />
          <div className="core">
            <div className="glyph">
              <div className="glyph-inner" />
            </div>
            <div className="label">ApexBridge<span className="v"> v2.4</span></div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* ---------- Stats banner ---------- */
const Counter = ({ to, suffix = '', duration = 1500 }) => {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(to * eased));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{val.toLocaleString()}{suffix && <span className="suffix">{suffix}</span>}</span>;
};

const Stats = () => (
  <section className="stats-banner reveal">
    <div className="container">
      <div className="stats-grid">
        <div className="stat-cell">
          <div className="num"><Counter to={99} suffix="%" /></div>
          <div className="label">Component coverage on real engagements</div>
        </div>
        <div className="stat-cell">
          <div className="num"><Counter to={2400000} /></div>
          <div className="label">Lines of legacy code in production</div>
        </div>
        <div className="stat-cell">
          <div className="num"><Counter to={60} suffix="%" /></div>
          <div className="label">Faster than a manual rewrite</div>
        </div>
        <div className="stat-cell">
          <div className="num"><Counter to={9} /></div>
          <div className="label">Months — typical end-to-end timeline</div>
        </div>
      </div>
    </div>
  </section>
);

/* ---------- How it works ---------- */
const STEPS = [
  { n: '01', t: 'Ingest', d: 'Connect to your Oracle Forms / VBCS source. ApexBridge parses .fmb, .pll, .mmb, and VBCS app metadata into a typed AST.', meta: 'Forms · PL/SQL · LOVs · Triggers' },
  { n: '02', t: 'Translate', d: 'Deterministic translator maps each AST node to its APEX equivalent — pages, regions, dynamic actions, processes, computations.', meta: '99% deterministic · 1% AI repair' },
  { n: '03', t: 'Repair', d: 'Agentic AI loop handles edge cases the deterministic translator flags. Every change is logged, reviewable, and reversible.', meta: 'Auditable · Reproducible' },
  { n: '04', t: 'Validate', d: 'Generated APEX app runs through your existing test suite plus our 200+ migration validation rules. Zero-error builds.', meta: 'CI / CD · Test coverage gates' },
];
const HowItWorks = () => (
  <section className="pipeline-section" id="how-it-works">
    <div className="container">
      <div className="section-header reveal">
        <div className="left">
          <span className="eyebrow eyebrow-accent">/ How It Works</span>
          <h2>Four stages.<br/>One pipeline.</h2>
        </div>
        <div className="right">
          ApexBridge is not a chat interface. It's a deterministic compiler with an AI repair loop —
          built for engineers who need provable, reproducible migrations.
        </div>
      </div>
      <div className="pipeline-steps reveal">
        {STEPS.map(s => (
          <div className="pipeline-step" key={s.n}>
            <div className="step-num">{s.n}</div>
            <h4>{s.t}</h4>
            <p>{s.d}</p>
            <div className="meta">{s.meta}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- Live pipeline visual ---------- */
const LiveVisual = () => (
  <section style={{ padding: '120px 0', borderTop: '1px solid var(--border)' }}>
    <div className="container">
      <div className="section-header reveal">
        <div className="left">
          <span className="eyebrow eyebrow-accent">/ Live System</span>
          <h2>Pipeline,<br/>in motion.</h2>
        </div>
        <div className="right">
          A real-time view of one form moving through the ApexBridge pipeline. From Oracle Forms binary to a production-ready APEX page.
        </div>
      </div>
      <div className="reveal" style={{
        background: 'var(--bg-2)', border: '1px solid var(--border)',
        borderRadius: 4, position: 'relative', height: 520, overflow: 'hidden',
      }}>
        <window.ApexBridgeVisual variant="pipeline" />
      </div>
    </div>
  </section>
);

/* ---------- Architecture ---------- */
const Architecture = () => (
  <section className="arch-section">
    <div className="container">
      <div className="section-header reveal">
        <div className="left">
          <span className="eyebrow eyebrow-accent">/ Architecture</span>
          <h2>Inside<br/>ApexBridge.</h2>
        </div>
        <div className="right">
          A deterministic core, an AI repair loop, and an APEX-native output stage. Each layer is auditable, replayable, and runs in your environment.
        </div>
      </div>
      <div className="arch-diagram reveal">
        <div className="arch-row">
          <div className="arch-cell">
            <div className="layer">Layer 01</div>
            <h5>Source Adapters</h5>
            <p>Oracle Forms (.fmb / .pll / .mmb), VBCS metadata, custom PL/SQL packages.</p>
          </div>
          <div className="arch-cell">
            <div className="layer">Layer 01</div>
            <h5>AST Parser</h5>
            <p>Typed abstract syntax tree of every form, trigger, LOV, and program unit.</p>
          </div>
          <div className="arch-cell">
            <div className="layer">Layer 01</div>
            <h5>Inventory</h5>
            <p>Complete pre-flight inventory: complexity, dependencies, custom logic surface.</p>
          </div>
        </div>
        <div className="arch-divider"><span>↓ DETERMINISTIC TRANSLATION ↓</span></div>
        <div className="arch-row">
          <div className="arch-cell core">
            <div className="layer core">CORE / 02</div>
            <h5>Deterministic Translator</h5>
            <p>Rule-based mapping of AST nodes to APEX components. Reproducible, byte-stable output.</p>
          </div>
          <div className="arch-cell core">
            <div className="layer core">CORE / 02</div>
            <h5>Agentic Repair Loop</h5>
            <p>AI agents resolve flagged edge cases. Every action is logged with reasoning + diff.</p>
          </div>
          <div className="arch-cell core">
            <div className="layer core">CORE / 02</div>
            <h5>Validation Engine</h5>
            <p>200+ migration rules + your CI suite. Builds gated on green.</p>
          </div>
        </div>
        <div className="arch-divider"><span>↓ APEX-NATIVE OUTPUT ↓</span></div>
        <div className="arch-row">
          <div className="arch-cell">
            <div className="layer">Layer 03</div>
            <h5>APEX Pages</h5>
            <p>Standard Oracle APEX pages, regions, and dynamic actions. No proprietary runtime.</p>
          </div>
          <div className="arch-cell">
            <div className="layer">Layer 03</div>
            <h5>PL/SQL Processes</h5>
            <p>Triggers and program units rebuilt as APEX processes and computations.</p>
          </div>
          <div className="arch-cell">
            <div className="layer">Layer 03</div>
            <h5>Audit Bundle</h5>
            <p>Per-form provenance, reasoning, and diff history — handed to your auditors.</p>
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* ---------- Coverage matrix ---------- */
const COVERAGE = [
  { feat: 'Forms (.fmb)', pct: 100, note: 'Full coverage including modal/non-modal canvases' },
  { feat: 'PL/SQL Triggers', pct: 99, note: 'Mapped to APEX processes, validations, dynamic actions' },
  { feat: 'LOVs (Lists of Values)', pct: 100, note: 'Static, dynamic, and dependent LOVs' },
  { feat: 'Program Units / Libraries', pct: 98, note: 'Rebuilt as PL/SQL packages on the schema' },
  { feat: 'Menus (.mmb)', pct: 100, note: 'Mapped to APEX navigation menus' },
  { feat: 'VBCS Applications', pct: 96, note: 'Visual Builder pages, flows, and components' },
  { feat: 'Custom OLE / WebUtil', pct: 70, note: 'Most cases auto-converted; complex OLE flagged for review' },
  { feat: 'Reports (.rdf)', pct: 92, note: 'Migrated to APEX classic / interactive reports' },
];
const Coverage = () => (
  <section className="coverage-section">
    <div className="container">
      <div className="section-header reveal">
        <div className="left">
          <span className="eyebrow eyebrow-accent">/ Coverage Matrix</span>
          <h2>What gets<br/>migrated.</h2>
        </div>
        <div className="right">
          A line-by-line accounting of what ApexBridge handles automatically, where you stay in the loop, and the rare cases that need engineering attention.
        </div>
      </div>
      <table className="coverage-table reveal">
        <thead>
          <tr>
            <th style={{width: '28%'}}>Feature</th>
            <th style={{width: '34%'}}>Automation</th>
            <th>Notes</th>
          </tr>
        </thead>
        <tbody>
          {COVERAGE.map(c => (
            <tr key={c.feat}>
              <td className="feat">{c.feat}</td>
              <td className="pct">
                {c.pct}%
                <span className="coverage-bar"><span className="fill" style={{width: `${c.pct}%`}} /></span>
              </td>
              <td className="note">{c.note}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </section>
);

/* ---------- Final CTA ---------- */
const FinalCTA = ({ onDemoClick }) => (
  <section className="final-cta">
    <div className="final-cta-bg" />
    <div className="container">
      <div className="final-cta-inner reveal">
        <h2>Ship to APEX.<br/><span className="accent">In months, not years.</span></h2>
        <p>Bring your Forms repo. We'll bring an engineer.<br/>30 minutes. No slides.</p>
        <div className="actions">
          <button className="btn btn-primary" onClick={onDemoClick}>Request a Demo →</button>
          <a className="btn btn-ghost" href="index.html">← Back to home</a>
        </div>
      </div>
    </div>
  </section>
);

/* ---------- Footer (reused) ---------- */
const Footer = () => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div className="footer-brand">
          <a href="index.html" className="logo">
            <img src="assets/atc-mark.png" alt="ATC" />
            <span className="logo-text">ATC<span className="dim">·</span></span>
          </a>
          <p>AI Tech Cloud. Enterprise AI engineering & automation. We build the future of AI for the systems that already run the world.</p>
        </div>
        <div className="footer-col">
          <h5>Platform</h5>
          <ul>
            <li><a href="platform.html">ApexBridge</a></li>
            <li><a href="#">Agentic AI</a></li>
            <li><a href="#">Data Exploration</a></li>
            <li><a href="#">Automation</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Solutions</h5>
          <ul>
            <li><a href="#">Banking</a></li>
            <li><a href="#">Telecom</a></li>
            <li><a href="#">Government</a></li>
            <li><a href="#">Insurance</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Company</h5>
          <ul>
            <li><a href="index.html">Home</a></li>
            <li><a href="#">Careers</a></li>
            <li><a href="#">News</a></li>
            <li><a href="#">Contact</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Resources</h5>
          <ul>
            <li><a href="#">Documentation</a></li>
            <li><a href="#">Whitepapers</a></li>
            <li><a href="#">Security</a></li>
            <li><a href="#">Status</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <div>© 2026 AI Tech Cloud · ATC. All rights reserved.</div>
        <div className="legal">
          <a href="#">Privacy</a>
          <a href="#">Terms</a>
          <a href="#">Cookies</a>
        </div>
      </div>
    </div>
  </footer>
);

/* ---------- Demo Modal (lightweight reuse) ---------- */
const DemoModal = ({ open, onClose }) => {
  const [form, setForm] = useState({ name: '', email: '', company: '', forms: '', notes: '' });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [open]);
  useEffect(() => { if (!open) setTimeout(() => { setSubmitted(false); setForm({ name: '', email: '', company: '', forms: '', notes: '' }); setErrors({}); }, 250); }, [open]);

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Valid email required';
    if (!form.company.trim()) e.company = 'Required';
    if (!form.forms) e.forms = 'Pick a range';
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const submit = (ev) => { ev.preventDefault(); if (validate()) setSubmitted(true); };

  return (
    <div className={`modal-overlay ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={ev => ev.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">✕</button>
        {!submitted ? (
          <>
            <h3>Request a Demo</h3>
            <p className="sub">30-minute scoping call. We'll bring an engineer, you bring your Forms repo.</p>
            <form onSubmit={submit} noValidate>
              <div className="field-row">
                <div className={`field ${errors.name ? 'error' : ''}`}>
                  <label>Name</label>
                  <input value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
                  {errors.name && <div className="err">{errors.name}</div>}
                </div>
                <div className={`field ${errors.email ? 'error' : ''}`}>
                  <label>Work email</label>
                  <input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                  {errors.email && <div className="err">{errors.email}</div>}
                </div>
              </div>
              <div className={`field ${errors.company ? 'error' : ''}`}>
                <label>Company</label>
                <input value={form.company} onChange={e => setForm({...form, company: e.target.value})} />
                {errors.company && <div className="err">{errors.company}</div>}
              </div>
              <div className={`field ${errors.forms ? 'error' : ''}`}>
                <label>Forms in scope</label>
                <select value={form.forms} onChange={e => setForm({...form, forms: e.target.value})}>
                  <option value="">Select a range…</option>
                  <option value="1-25">1–25 forms</option>
                  <option value="25-100">25–100 forms</option>
                  <option value="100-500">100–500 forms</option>
                  <option value="500+">500+ forms</option>
                  <option value="vbcs">VBCS application</option>
                </select>
                {errors.forms && <div className="err">{errors.forms}</div>}
              </div>
              <div className="field">
                <label>Anything else? <span style={{textTransform:'none', letterSpacing:0, color:'var(--text-3)'}}>(optional)</span></label>
                <textarea rows="3" value={form.notes} onChange={e => setForm({...form, notes: e.target.value})} />
              </div>
              <div className="submit-row">
                <button type="submit" className="btn btn-primary">Submit Request →</button>
                <span style={{fontSize: 12, color: 'var(--text-3)'}}>We reply within 1 business day.</span>
              </div>
            </form>
          </>
        ) : (
          <div className="success">
            <div className="check">✓</div>
            <h3 style={{textAlign:'center'}}>Request received</h3>
            <p className="sub" style={{textAlign:'center'}}>An ATC engineer will reach out to <strong style={{color:'var(--text)'}}>{form.email}</strong> within 1 business day.</p>
            <div style={{textAlign:'center', marginTop: 24}}>
              <button className="btn btn-ghost" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

/* ---------- App ---------- */
const App = () => {
  const [demoOpen, setDemoOpen] = useState(false);
  useReveal();
  const onDemoClick = useCallback(() => setDemoOpen(true), []);
  return (
    <>
      <Nav onDemoClick={onDemoClick} />
      <PlatformHero onDemoClick={onDemoClick} />
      <Stats />
      <HowItWorks />
      <LiveVisual />
      <Architecture />
      <Coverage />
      <FinalCTA onDemoClick={onDemoClick} />
      <Footer />
      <DemoModal open={demoOpen} onClose={() => setDemoOpen(false)} />
    </>
  );
};

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