// sections.jsx — Page sections for Blind Vision website

// ─── NAV ────────────────────────────────────────────────────────────────────
function Nav({ onCTAClick }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`bv-nav ${scrolled ? 'is-scrolled' : ''}`}>
      <a href="#top" className="bv-nav-brand" aria-label="Blind Vision home">
        <BVLockup size={32} subtle={false} />
      </a>
      <div className="bv-nav-links">
        <a href="#features">Features</a>
        <a href="#how">How it works</a>
        <a href="#glasses"><span className="bv-nav-soon">Soon</span>Glasses</a>
        <a href="#faq">FAQ</a>
      </div>
      <div className="bv-nav-cta">
        <button className="bv-btn bv-btn-primary" onClick={onCTAClick}>
          Join waitlist
          <span className="bv-btn-arrow">→</span>
        </button>
      </div>
    </nav>
  );
}

// ─── HERO ───────────────────────────────────────────────────────────────────
function Hero({ heroVariant, headline, subhead, onCTAClick }) {
  const orbsRef = React.useRef(null);
  React.useEffect(() => {
    const onMove = (e) => {
      if (!orbsRef.current) return;
      const x = (e.clientX / window.innerWidth - 0.5) * 24;
      const y = (e.clientY / window.innerHeight - 0.5) * 24;
      orbsRef.current.style.setProperty('--mx', `${x}px`);
      orbsRef.current.style.setProperty('--my', `${y}px`);
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  return (
    <header className={`bv-hero bv-hero--${heroVariant}`} id="top">
      <div className="bv-hero-orbs" ref={orbsRef} aria-hidden="true">
        <div className="bv-orb bv-orb-1" />
        <div className="bv-orb bv-orb-2" />
        <div className="bv-orb bv-orb-3" />
        <div className="bv-orb bv-orb-4" />
      </div>

      <div className="bv-hero-inner">
        <div className="bv-hero-eyebrow">
          <span className="bv-dot" />
          <span>Private beta · iOS & Android · Meta Glasses support coming soon</span>
        </div>

        <h1 className="bv-hero-title">
          {headline.split('\n').map((line, i) => (
            <span key={i} className="bv-hero-line" style={{ animationDelay: `${0.1 + i * 0.12}s` }}>
              {line}
            </span>
          ))}
        </h1>

        <p className="bv-hero-sub">{subhead}</p>

        <div className="bv-hero-actions">
          <button className="bv-btn bv-btn-primary bv-btn-lg" onClick={onCTAClick}>
            Join the waitlist
            <span className="bv-btn-arrow">→</span>
          </button>
          <a href="#features" className="bv-btn bv-btn-ghost bv-btn-lg">
            What it does
          </a>
        </div>

        <div className="bv-hero-meta">
          <div className="bv-hero-meta-item">
            <strong>iOS & Android</strong>
            <span>mobile app, free to install</span>
          </div>
          <div className="bv-hero-meta-divider" />
          <div className="bv-hero-meta-item">
            <strong>Meta Glasses</strong>
            <span>support coming soon</span>
          </div>
          <div className="bv-hero-meta-divider" />
          <div className="bv-hero-meta-item">
            <strong>Built with</strong>
            <span>blind & low-vision users</span>
          </div>
        </div>
      </div>

      {/* Decorative floating logo mark */}
      <div className="bv-hero-mark" aria-hidden="true">
        <BVLogo size={420} glow />
      </div>
    </header>
  );
}

// ─── MISSION ────────────────────────────────────────────────────────────────
function Mission() {
  return (
    <section className="bv-section bv-mission" id="mission">
      <div className="bv-section-inner">
        <div className="bv-eyebrow">Mission</div>
        <h2 className="bv-section-title">
          Independence,<br />
          <em>at your fingertips.</em>
        </h2>
        <p className="bv-section-lede">
          Blind Vision is a mobile app for blind and low-vision users. Point your
          phone at the world — a sign, a face, a barcode, a doorway — and the app
          describes, reads, recognizes, and guides. Soon, the same intelligence will
          run hands-free on Meta Glasses.
        </p>
      </div>
    </section>
  );
}

// ─── FEATURES ───────────────────────────────────────────────────────────────
function Features() {
  const features = [
    {
      title: 'Ask about anything',
      body: 'Take a photo or short video and ask the app a question about what it sees. "What\'s on this shelf?" "Is this can dented?" Answers in plain language.',
      tag: 'Photo & video',
    },
    {
      title: 'Document & screen reading',
      body: 'OCR for mail, menus, prescriptions, and printed pages — including multi-column layouts and handwriting where legible.',
      tag: 'OCR',
    },
    {
      title: 'Barcode scanning',
      body: 'Identify groceries, medications, and packaged goods. Hold your phone near the label and the app finds the barcode for you.',
      tag: 'Identify',
    },
    {
      title: 'Faces of friends & family',
      body: 'Train the app on the people you choose so it can let you know when they\'re nearby. Stays on your device, never shared.',
      tag: 'Recognize',
    },
    {
      title: 'Indoor navigation at home',
      body: 'Map familiar spaces — your apartment, your office — and get spoken cues to find a room, a chair, the front door.',
      tag: 'Navigate',
    },
    {
      title: 'Read any website aloud',
      body: 'Paste a link and Blind Vision strips the clutter, restructures the page, and reads it in a voice tuned for long-form listening.',
      tag: 'Web reader',
    },
    {
      title: 'Path navigation outside',
      body: 'Walking directions described as a route, not as a list of street names — landmarks, turns, and what to expect ahead.',
      tag: 'Outdoors',
    },
    {
      title: 'Built for screen readers',
      body: 'Every screen, every control works with VoiceOver and TalkBack. Tested with the people who actually rely on them.',
      tag: 'A11y',
    },
  ];
  return (
    <section className="bv-section bv-features" id="features">
      <div className="bv-section-inner">
        <div className="bv-eyebrow">Features</div>
        <h2 className="bv-section-title">
          Everything you needed,<br />
          <em>in one app.</em>
        </h2>
        <div className="bv-feat-grid">
          {features.map((f, i) => (
            <article className="bv-feat" key={f.title} style={{ '--i': i }}>
              <div className="bv-feat-tag">{f.tag}</div>
              <h3>{f.title}</h3>
              <p>{f.body}</p>
              <div className="bv-feat-glow" aria-hidden="true" />
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── HOW IT WORKS ───────────────────────────────────────────────────────────
function HowItWorks() {
  const steps = [
    {
      n: '01',
      title: 'Install on your phone',
      body: 'Download Blind Vision on iOS or Android. The whole app is built to be navigated by VoiceOver and TalkBack from the first launch.',
    },
    {
      n: '02',
      title: 'Point, scan, or ask',
      body: 'Capture a photo, scan a barcode, paste a link, or open a saved space. Use your voice or any control you prefer — your screen reader is welcome here.',
    },
    {
      n: '03',
      title: 'Hear back what matters',
      body: 'Descriptions, OCR, recognized faces, navigation cues — spoken at the pace and verbosity you set. Replay, dig deeper, or move on.',
    },
  ];
  return (
    <section className="bv-section bv-how" id="how">
      <div className="bv-section-inner">
        <div className="bv-eyebrow">How it works</div>
        <h2 className="bv-section-title">Three steps. No learning curve.</h2>
        <ol className="bv-steps">
          {steps.map((s, i) => (
            <li className="bv-step" key={s.n} style={{ '--i': i }}>
              <div className="bv-step-num">{s.n}</div>
              <div className="bv-step-body">
                <h3>{s.title}</h3>
                <p>{s.body}</p>
              </div>
              <div className="bv-step-art" aria-hidden="true">
                <StepArt index={i} />
              </div>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

function StepArt({ index }) {
  if (index === 0) {
    return (
      <svg viewBox="0 0 240 180" width="100%" height="100%">
        <defs>
          <radialGradient id="sa1" cx="50%" cy="50%" r="60%">
            <stop offset="0%" stopColor="#FFD66B" stopOpacity="0.6" />
            <stop offset="100%" stopColor="#FFD66B" stopOpacity="0" />
          </radialGradient>
        </defs>
        <rect x="80" y="30" width="80" height="120" rx="16" fill="#fff" stroke="rgba(0,0,0,.08)" />
        <rect x="92" y="48" width="56" height="74" rx="6" fill="#1a1a1f" />
        <circle cx="120" cy="85" r="22" fill="url(#sa1)" />
        <circle cx="120" cy="85" r="10" fill="#fff" opacity="0.3" />
        <rect x="106" y="135" width="28" height="3" rx="1.5" fill="rgba(0,0,0,.15)" />
      </svg>
    );
  }
  if (index === 1) {
    return (
      <svg viewBox="0 0 240 180" width="100%" height="100%">
        <defs>
          <linearGradient id="sa2" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#7DC4FF" />
            <stop offset="100%" stopColor="#9F7DFF" />
          </linearGradient>
        </defs>
        {[0, 1, 2, 3, 4, 5, 6].map((i) => (
          <rect key={i} x={70 + i * 14} y={90 - (i % 3) * 14 - 10}
                width="6" height={28 + (i % 3) * 14} rx="3"
                fill="url(#sa2)" opacity={0.4 + (i % 3) * 0.2}>
            <animate attributeName="height"
                     values={`${28 + (i % 3) * 14}; ${44 + (i % 3) * 14}; ${28 + (i % 3) * 14}`}
                     dur={`${1.6 + (i % 3) * 0.2}s`} repeatCount="indefinite" />
          </rect>
        ))}
        <text x="120" y="150" textAnchor="middle" fontFamily="ui-sans-serif"
              fontSize="11" fill="rgba(0,0,0,.45)">"What's on this shelf?"</text>
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 240 180" width="100%" height="100%">
      <defs>
        <radialGradient id="sa3" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#9F7DFF" stopOpacity="0.6" />
          <stop offset="100%" stopColor="#9F7DFF" stopOpacity="0" />
        </radialGradient>
      </defs>
      <circle cx="120" cy="90" r="60" fill="url(#sa3)" />
      <circle cx="120" cy="90" r="40" fill="none" stroke="#9F7DFF" strokeWidth="0.5" opacity="0.4">
        <animate attributeName="r" values="40;55;40" dur="3s" repeatCount="indefinite" />
        <animate attributeName="opacity" values="0.4;0;0.4" dur="3s" repeatCount="indefinite" />
      </circle>
      <circle cx="120" cy="90" r="50" fill="none" stroke="#9F7DFF" strokeWidth="0.5" opacity="0.3">
        <animate attributeName="r" values="50;70;50" dur="3s" begin="0.5s" repeatCount="indefinite" />
        <animate attributeName="opacity" values="0.3;0;0.3" dur="3s" begin="0.5s" repeatCount="indefinite" />
      </circle>
      <g transform="translate(120 90)">
        <BVLogo size={48} glow={false} />
      </g>
    </svg>
  );
}

// ─── GLASSES (Coming Soon) ─────────────────────────────────────────────────
function Glasses() {
  const capabilities = [
    { icon: 'obstacle', label: 'Real-time obstacle detection', body: 'Curbs, posts, doorframes, low branches — heard the moment they appear in front of you.' },
    { icon: 'nav', label: 'Turn-by-turn navigation', body: 'Spoken route guidance through the glasses\' speakers, so your hands and your phone stay free.' },
    { icon: 'safety', label: 'Safety alerts', body: 'Heads-up cues for oncoming traffic, sudden movement, and drop-offs in your path.' },
    { icon: 'read', label: 'Read & describe', body: 'Look at a sign, a menu, or the room — ask for a description or have it read aloud, no phone in hand.' },
  ];

  return (
    <section className="bv-section bv-glasses" id="glasses">
      <div className="bv-section-inner">
        <div className="bv-glasses-head">
          <div className="bv-eyebrow">Coming soon</div>
          <h2 className="bv-section-title">
            Hands-free, on<br />
            <em>Meta Glasses.</em>
          </h2>
          <p className="bv-section-lede">
            We're bringing Blind Vision to Meta Glasses so you don't have to hold a
            phone to see the world. The same features you use today — obstacle
            detection, navigation, reading, scene description, face recognition —
            running on the smart glasses you already wear.
          </p>
        </div>

        <div className="bv-cap-grid">
          {capabilities.map((c) => (
            <article className="bv-cap" key={c.label}>
              <CapIcon kind={c.icon} />
              <h3>{c.label}</h3>
              <p>{c.body}</p>
            </article>
          ))}
        </div>

        <div className="bv-glasses-cta">
          <a href="#contact" className="bv-btn bv-btn-primary bv-btn-lg">
            Get notified when it launches
            <span className="bv-btn-arrow">→</span>
          </a>
          <span className="bv-glasses-fine">Snap Spectacles and other platforms under exploration.</span>
        </div>
      </div>
    </section>
  );
}

function GlassesArt() {
  // Frameless smart glasses — just the lens shapes and tiny temple stubs.
  // Lenses are subtle rounded rectangles with a faint stroke so they read
  // as glass rather than empty boxes; bridge is a single thin curve.
  return (
    <svg className="bv-glasses-svg" viewBox="0 0 800 260" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"
         fill="none" strokeLinejoin="round" strokeLinecap="round">

      {/* Left lens (frameless — soft glassy fill, faint outline) */}
      <rect x="200" y="100" width="180" height="80" rx="18" ry="18"
            fill="rgba(180,196,212,0.18)" stroke="rgba(31,27,20,0.35)" strokeWidth="1.2" />

      {/* Right lens */}
      <rect x="420" y="100" width="180" height="80" rx="18" ry="18"
            fill="rgba(180,196,212,0.18)" stroke="rgba(31,27,20,0.35)" strokeWidth="1.2" />

      {/* Bridge — single thin arch, no acetate */}
      <path d="M 380 130 Q 400 122, 420 130"
            stroke="#1F1B14" strokeWidth="2" />

      {/* Tiny temple stubs — barely there */}
      <path d="M 188 130 L 200 130" stroke="#1F1B14" strokeWidth="2" />
      <path d="M 600 130 L 612 130" stroke="#1F1B14" strokeWidth="2" />

      {/* Camera dot — left lens upper-outer */}
      <circle cx="222" cy="118" r="3.5" fill="#1F1B14" />

      {/* Status LED — right lens upper-outer */}
      <circle cx="578" cy="118" r="1.8" fill="#F5A524">
        <animate attributeName="opacity" values="0.4;1;0.4" dur="2.6s" repeatCount="indefinite" />
      </circle>
    </svg>
  );
}

function CapIcon({ kind }) {
  const common = { width: 28, height: 28, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'obstacle') return (
    <svg {...common}><path d="M3 19h18" /><path d="M7 19V9l5-5 5 5v10" /><path d="M10 19v-5h4v5" /></svg>
  );
  if (kind === 'nav') return (
    <svg {...common}><circle cx="12" cy="12" r="9" /><path d="M14 8l-4 8 2-2 4 0z" fill="currentColor" /></svg>
  );
  if (kind === 'safety') return (
    <svg {...common}><path d="M12 3l8 4v5c0 5-3.5 8-8 9-4.5-1-8-4-8-9V7z" /><path d="M9 12l2 2 4-4" /></svg>
  );
  return (
    <svg {...common}><path d="M4 5h12a4 4 0 014 4v10" /><path d="M4 5v14h14" /><path d="M8 9h6M8 13h6M8 17h4" /></svg>
  );
}

// ─── FAQ ────────────────────────────────────────────────────────────────────
function FAQ() {
  const items = [
    {
      q: 'What is Blind Vision, exactly?',
      a: 'A mobile app for iOS and Android, designed for blind and low-vision users. It uses your phone\'s camera and AI to describe scenes, read text, scan barcodes, recognize friends and family, navigate familiar spaces, and read websites aloud.',
    },
    {
      q: 'Is it available right now?',
      a: 'Blind Vision is in private beta. Join the waitlist and we\'ll reach out as we open more spots. There\'s no cost to test the beta.',
    },
    {
      q: 'How does the Meta Glasses version work?',
      a: 'It\'s in development. Once released, the same capabilities you use on your phone — obstacle detection, navigation, reading, scene description — will work hands-free through Meta Glasses.',
    },
    {
      q: 'Is Blind Vision a replacement for a cane or guide dog?',
      a: 'No. It\'s a companion that fills in context — what a sign says, who\'s in the room, what\'s on the shelf. Your primary mobility tools stay your primary mobility tools.',
    },
    {
      q: 'How does it work with VoiceOver and TalkBack?',
      a: 'Every screen and control is built to be operated by your screen reader of choice. We test the app with the assistive tech our users rely on.',
    },
    {
      q: 'What does it cost?',
      a: 'Pricing is still being finalized. Beta access is free, and we\'re committed to keeping core features accessible.',
    },
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <section className="bv-section bv-faq" id="faq">
      <div className="bv-section-inner bv-faq-inner">
        <div>
          <div className="bv-eyebrow">FAQ</div>
          <h2 className="bv-section-title">
            Honest answers,<br />
            <em>before you ask.</em>
          </h2>
          <p className="bv-section-lede" style={{ maxWidth: 360 }}>
            Don't see your question? Email <a href="mailto:hello@blindvision.app">hello@blindvision.app</a> and we'll get back to you.
          </p>
        </div>
        <ul className="bv-faq-list">
          {items.map((it, i) => (
            <li className={`bv-faq-item ${open === i ? 'is-open' : ''}`} key={i}>
              <button className="bv-faq-q" onClick={() => setOpen(open === i ? -1 : i)}
                      aria-expanded={open === i}>
                <span>{it.q}</span>
                <span className="bv-faq-icon" aria-hidden="true">{open === i ? '−' : '+'}</span>
              </button>
              <div className="bv-faq-a">
                <p>{it.a}</p>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

// ─── CTA + FOOTER ───────────────────────────────────────────────────────────
function CTA() {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // 'idle' | 'sending' | 'ok' | 'error'
  const [message, setMessage] = React.useState('');

  async function onSubmit(e) {
    e.preventDefault();
    if (status === 'sending') return;
    setStatus('sending');
    setMessage('');
    try {
      const r = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) {
        setStatus('error');
        setMessage(data.error || 'Something went wrong. Please try again.');
        return;
      }
      setStatus('ok');
      setMessage("You're on the list. We'll be in touch.");
      setEmail('');
    } catch (err) {
      setStatus('error');
      setMessage('Network error. Please try again.');
    }
  }

  return (
    <section className="bv-section bv-cta" id="contact">
      <div className="bv-cta-card">
        <div className="bv-cta-mark" aria-hidden="true">
          <BVLogo size={200} glow />
        </div>
        <div className="bv-eyebrow">Join the waitlist</div>
        <h2 className="bv-section-title">
          Be one of the first<br /><em>on the beta.</em>
        </h2>
        <form className="bv-cta-form" onSubmit={onSubmit}>
          <input
            type="email"
            placeholder="you@somewhere.com"
            aria-label="Email address"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={status === 'sending' || status === 'ok'}
          />
          <button className="bv-btn bv-btn-primary bv-btn-lg" type="submit"
                  disabled={status === 'sending' || status === 'ok'}>
            {status === 'sending' ? 'Sending…' : status === 'ok' ? 'Added ✓' : 'Request access'}
            {status === 'idle' && <span className="bv-btn-arrow">→</span>}
          </button>
        </form>
        <p className="bv-cta-fine" role="status" aria-live="polite">
          {message || "We'll only email when there's beta news to share."}
        </p>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="bv-footer">
      <div className="bv-footer-inner">
        <div className="bv-footer-brand">
          <BVLockup size={32} subtle />
          <p>An accessibility-first app for blind and low-vision users.</p>
        </div>
        <div className="bv-footer-cols">
          <div>
            <h4>Product</h4>
            <a href="#features">Features</a>
            <a href="#how">How it works</a>
            <a href="#glasses">Meta Glasses</a>
            <a href="#faq">FAQ</a>
          </div>
          <div>
            <h4>Connect</h4>
            <a href="mailto:hello@blindvision.app">hello@blindvision.app</a>
            <a href="#contact">Join waitlist</a>
          </div>
        </div>
      </div>
      <div className="bv-footer-base">
        <span>© 2026 Blind Vision.</span>
        <span><a href="#">Privacy</a> · <a href="#">Accessibility</a> · <a href="#">Terms</a></span>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Mission, HowItWorks, Features, FAQ, CTA, Footer, Glasses });
