// Vecorps — shared components across all pages. Depends on React (global).
// Device mockups (window.TauChat etc.) are loaded by pages that need them.
const { useState } = React;

// ── Waitlist endpoint ────────────────────────────────────────────────────────
// Posts to our own serverless function (Vercel), which holds the ConvertKit
// API key server-side via env vars. No secret ever ships to the browser.
const WAITLIST_ENDPOINT = '/api/subscribe';

// ── Scaled device mock (TauDevice is 402 x 874) ─────────────────────────────
function Mock({ scale = 0.62, children }) {
  return (
    <div style={{ width: 402 * scale, height: 874 * scale, position: 'relative' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, transformOrigin: 'top left', transform: `scale(${scale})` }}>
        {children}
      </div>
    </div>
  );
}

// ── Email capture · wired to ConvertKit (Kit) ───────────────────────────────
function Capture({ center = false }) {
  const [status, setStatus] = useState('idle'); // idle | loading | done | error
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');
  const c = center ? ' is-center' : '';

  async function submit(e) {
    e.preventDefault();
    const value = email.trim();
    if (!value || status === 'loading') return;
    setStatus('loading');
    setError('');
    try {
      const res = await fetch(WAITLIST_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: value }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) {
        setEmail('');
        setStatus('done');
      } else {
        setError((data && data.error) || "That didn't go through. Please try again.");
        setStatus('error');
      }
    } catch (err) {
      setError('Network error — please check your connection and try again.');
      setStatus('error');
    }
  }

  if (status === 'done') {
    return (
      <div className={'capture-done' + c}>
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
          <circle cx="9" cy="9" r="8" stroke="currentColor" strokeWidth="1.3" />
          <path d="M5.5 9.2l2.3 2.3L12.5 6.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        <span>You're on the waitlist. We'll email you once — <b>at launch.</b></span>
      </div>
    );
  }

  const loading = status === 'loading';
  return (
    <div>
      <form className={'capture' + c} onSubmit={submit} noValidate>
        <input type="email" required placeholder="you@email.com" value={email}
          disabled={loading} autoComplete="email"
          onChange={(e) => { setEmail(e.target.value); if (status === 'error') setStatus('idle'); }} />
        <button className="cta" type="submit" disabled={loading}>{loading ? 'Joining…' : 'Get early access'}</button>
      </form>
      {status === 'error' && <div className={'capture-err' + c}>{error}</div>}
      <div className={'capture-note' + c}>By joining the waitlist, you agree to receive emails about the product launch.</div>
    </div>
  );
}

// ── Nav (shared across pages) ───────────────────────────────────────────────
function Nav({ active, ctaHref = '#access' }) {
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a href="index.html" aria-label="Vecorps home"><img className="nav-logo" src="vecorps-logo.png" alt="Vecorps" /></a>
        <div className="nav-right">
          <a href="TAU.html" className={'nav-link' + (active === 'tau' ? ' is-active' : '')}>TAU</a>
          <a href="Approach.html" className={'nav-link' + (active === 'approach' ? ' is-active' : '')}>Approach</a>
          <a href={ctaHref} className="cta">Get early access</a>
        </div>
      </div>
    </nav>
  );
}

// ── Masterbrand framing line (sub-pages) ────────────────────────────────────
function Frame({ children }) {
  return (
    <div className="frame">
      <div className="wrap frame-inner">
        <span className="lead">Vecorps</span>
        <span className="sep">/</span>
        <span>{children || 'The private intelligence layer for personal AI'}</span>
      </div>
    </div>
  );
}

// ── Final waitlist CTA ──────────────────────────────────────────────────────
function FinalCTA({ heading = 'Be among the first to make an AI truly yours.' }) {
  return (
    <section className="final" id="access">
      <div className="wrap">
        <h2 className="final-h2">{heading}</h2>
        <Capture center />
      </div>
    </section>
  );
}

// ── Footer (shared) ─────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap footer-inner">
        <div className="footer-left">
          <img className="footer-logo" src="vecorps-logo.png" alt="Vecorps" />
          <span>© 2026 Vecorps Technologies</span>
          <span>·</span>
          <span>Private by design</span>
        </div>
        <div className="footer-right">
          <a href="Privacy.html">Privacy Policy</a>
          <a href="https://www.instagram.com/vecorps.hq/" target="_blank" rel="noopener">Instagram</a>
          <a href="https://x.com/vecorps" target="_blank" rel="noopener">X</a>
          <a href="mailto:contact@vecorps.com">contact@vecorps.com</a>
        </div>
      </div>
    </footer>
  );
}

// arrow glyph for hairline buttons
function Arr() { return <span className="arr">→</span>; }

Object.assign(window, { Mock, Capture, Nav, Frame, FinalCTA, Footer, Arr });
