// siteSections.jsx — non-video sections of the Terra website

// ───── Reusable ─────
function SectionHeader({ eyebrow, title, titleAccent, kicker }) {
  return (
    <div className="t-section-head">
      <div className="t-eyebrow">
        <span className="t-eyebrow-dot" />
        {eyebrow}
      </div>
      <h2 className="t-h2">
        {title}{titleAccent && <span className="t-accent"> {titleAccent}</span>}
      </h2>
      {kicker && <p className="t-kicker">{kicker}</p>}
    </div>
  );
}

// ───── Top nav ─────
function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const close = () => setOpen(false);
  return (
    <>
      <nav className={`t-nav ${scrolled ? 't-nav-scrolled' : ''}`}>
        <div className="t-nav-inner">
          <a href="#top" className="t-logo">
            <span className="t-logo-dot" />
            TERRA.
          </a>
          <div className="t-nav-links">
            <a href="#services">Services</a>
            <a href="#receptionist">AI Receptionist</a>
            <a href="#results">Results</a>
            <a href="#process">Process</a>
            <a href="#testimonials">Clients</a>
          </div>
          <div style={{display:'flex',alignItems:'center',gap:12}}>
            <a href="#contact" className="t-nav-cta">Book a call <span>→</span></a>
            <button className="t-hamburger" onClick={() => setOpen(o => !o)} aria-label="Menu">
              <span /><span /><span />
            </button>
          </div>
        </div>
      </nav>
      <div className={`t-mobile-menu${open ? ' is-open' : ''}`}>
        <button className="t-close" onClick={close} aria-label="Close">✕</button>
        <a href="#services" onClick={close}>Services</a>
        <a href="#receptionist" onClick={close}>AI Receptionist</a>
        <a href="#results" onClick={close}>Results</a>
        <a href="#process" onClick={close}>Process</a>
        <a href="#testimonials" onClick={close}>Clients</a>
        <a href="#contact" onClick={close} style={{color:'var(--lime)'}}>Book a call →</a>
      </div>
    </>
  );
}

// ───── Stats strip (between videos) ─────
function StatsStrip() {
  const stats = [
    { v: '150+', l: 'Clients served' },
    { v: '3.2x', l: 'Avg. ROI increase' },
    { v: '24/7', l: 'AI support' },
    { v: '98%', l: 'Client retention' },
  ];
  return (
    <section className="t-stats-strip">
      {stats.map((s, i) => (
        <div key={i} className="t-stat-cell">
          <div className="t-stat-v">{s.v}</div>
          <div className="t-stat-l">{s.l}</div>
        </div>
      ))}
    </section>
  );
}

// ───── Video preview card (under services grid) ─────
// Architecture notes:
//   - Preview video: muted/autoplay/loop with preload="metadata" (keeps page light — no 5x MP4 preloads).
//   - Modal is always in the DOM (display toggled) so the <video> element survives across opens.
//   - On click we SYNCHRONOUSLY unmute, build the AudioContext + 8x GainNode, and call v.play() —
//     iOS Safari requires play() within the user-gesture stack frame; any await/useEffect hop breaks it.
//   - We NEVER call v.load() (it resets currentTime and kills startTime).
//   - startTime is applied on loadedmetadata and enforced via timeupdate so users can't scrub before it.
function VideoPreviewCard({ src = 'IMG_1914.mp4', title = 'Behind the receipts.', subtitle = 'Terra · Studio cut · 00:30', tag = 'CLIP / 01', startTime = 0, modalStartTime }) {
  const [open, setOpen] = React.useState(false);
  const previewRef = React.useRef(null);
  const modalVideoRef = React.useRef(null);
  const audioSetup = React.useRef(false);

  const effectiveStart = (modalStartTime != null ? modalStartTime : startTime) || 0;

  // Click handler — MUST run fully synchronously inside the user gesture for iOS Safari.
  const handleOpen = React.useCallback(() => {
    const v = modalVideoRef.current;
    if (v) {
      // 1) Unmute + full volume (the GainNode will multiply this by 8).
      v.muted = false;
      v.volume = 1;

      // 2) Build AudioContext + 8x GainNode once, inside the gesture so mobile unlocks it.
      if (!audioSetup.current) {
        try {
          const Ctx = window.AudioContext || window.webkitAudioContext;
          if (Ctx) {
            const ctx = new Ctx();
            const source = ctx.createMediaElementSource(v);
            const gain = ctx.createGain();
            gain.gain.value = 8;
            source.connect(gain);
            gain.connect(ctx.destination);
            if (ctx.state === 'suspended') ctx.resume();
            audioSetup.current = true;
          }
        } catch (e) { /* ignore — some browsers reject a second createMediaElementSource */ }
      }

      // 3) Apply startTime. Safe now if metadata is ready, otherwise set on loadedmetadata.
      //    NOTE: never call v.load() here — it would reset currentTime to 0.
      const applyStart = () => {
        if (effectiveStart > 0) {
          try { v.currentTime = effectiveStart; } catch (e) {}
        }
      };
      if (v.readyState >= 1) applyStart();
      else v.addEventListener('loadedmetadata', applyStart, { once: true });

      // 4) play() — synchronous call inside gesture. iOS Safari unlocks audio here.
      const p = v.play();
      if (p && typeof p.catch === 'function') p.catch(() => {});
    }
    setOpen(true);
  }, [effectiveStart]);

  // Close / cleanup effect. Does NOT call play() — that belongs in the click handler only.
  React.useEffect(() => {
    if (!open) {
      const v = modalVideoRef.current;
      if (v) {
        v.pause();
        v.muted = true;
        // Reset to startTime (not 0 — so the preview loop stays in-clip next time).
        try { v.currentTime = effectiveStart; } catch (e) {}
      }
      document.body.style.overflow = '';
      return;
    }

    document.body.style.overflow = 'hidden';

    const v = modalVideoRef.current;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    const onTimeUpdate = () => {
      if (effectiveStart > 0 && v && v.currentTime < effectiveStart - 0.1) {
        try { v.currentTime = effectiveStart; } catch (e) {}
      }
    };
    const onSeeking = onTimeUpdate;

    window.addEventListener('keydown', onKey);
    if (v) {
      v.addEventListener('timeupdate', onTimeUpdate);
      v.addEventListener('seeking', onSeeking);
    }

    return () => {
      window.removeEventListener('keydown', onKey);
      if (v) {
        v.removeEventListener('timeupdate', onTimeUpdate);
        v.removeEventListener('seeking', onSeeking);
      }
    };
  }, [open, effectiveStart]);

  const onOverlayClick = (e) => {
    if (e.target === e.currentTarget) setOpen(false);
  };

  return (
    <>
      <div className="t-vpreview-wrap">
        <div
          className="t-vpreview"
          role="button"
          tabIndex={0}
          onClick={handleOpen}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleOpen(); } }}
          aria-label="Play clip with sound"
        >
          <div className="t-vpreview-head">
            <span className="t-vpreview-head-k">LIVE PREVIEW</span>
            <span>{tag}</span>
          </div>
          <div className="t-vpreview-frame">
            <video
              ref={previewRef}
              src={src}
              muted
              autoPlay
              loop
              playsInline
              preload="metadata"
              onLoadedMetadata={(e) => { if (startTime) e.currentTarget.currentTime = startTime; }}
              onPlay={(e) => { if (startTime && e.currentTarget.currentTime < startTime) e.currentTarget.currentTime = startTime; }}
              onTimeUpdate={(e) => { if (startTime && e.currentTarget.currentTime < startTime - 0.1) e.currentTarget.currentTime = startTime; }}
            />
            <div className="t-vpreview-play" aria-hidden="true">
              <div className="t-vpreview-play-btn">
                <svg width="22" height="22" viewBox="0 0 22 22" fill="currentColor" aria-hidden="true">
                  <path d="M6 4.5 L17 11 L6 17.5 Z" />
                </svg>
              </div>
            </div>
          </div>
          <div className="t-vpreview-foot">
            <div>
              <div className="t-vpreview-title">{title}</div>
              <div className="t-vpreview-sub">{subtitle}</div>
            </div>
            <div className="t-vpreview-cta">Tap to play with sound →</div>
          </div>
        </div>
      </div>

      {/* Modal stays mounted (display toggled) so the <video> ref is stable across opens. */}
      <div
        className="t-vmodal"
        onClick={onOverlayClick}
        role="dialog"
        aria-modal="true"
        aria-label="Video player"
        style={{ display: open ? 'flex' : 'none' }}
      >
        <div className="t-vmodal-inner">
          <div className="t-vmodal-head">
            <span className="t-vmodal-head-k">NOW PLAYING</span>
            <button
              type="button"
              className="t-vmodal-close"
              onClick={() => setOpen(false)}
              aria-label="Close video"
            >
              CLOSE ✕
            </button>
          </div>
          <div className="t-vmodal-frame">
            <video
              ref={modalVideoRef}
              src={src}
              controls
              playsInline
              preload="metadata"
            />
          </div>
        </div>
      </div>
    </>
  );
}

// ───── Services grid ─────
function Services() {
  const services = [
    { tag: 'MOST POPULAR', name: 'AI Voice Receptionist', desc: 'Never miss a call. Answers 24/7, qualifies leads, transfers calls & books appointments.', feats: ['24/7 availability', 'Call transfer', 'Calendar booking', 'SMS follow-up'], featured: true },
    { name: 'AI Chatbot', desc: 'Engages visitors instantly — captures leads, answers FAQs, guides prospects through your sales funnel.', feats: ['Lead capture', 'FAQ automation', 'Live chat handoff', 'CRM integration'] },
    { name: 'Paid Advertising', desc: 'Data-driven Google & Meta campaigns. Every dollar optimized to maximize return on ad spend.', feats: ['Google Ads', 'Meta Ads', 'Retargeting', 'A/B testing'] },
    { name: 'SEO & Content', desc: 'Rank higher and attract organic traffic with strategic content and technical SEO that compounds.', feats: ['Keyword research', 'On-page SEO', 'Link building', 'Content strategy'] },
    { name: 'Email & SMS', desc: 'Nurture leads and retain customers with automated sequences and targeted SMS campaigns that convert.', feats: ['Automation flows', 'Segmentation', 'SMS campaigns', 'Analytics'] },
    { name: 'Brand & Web Design', desc: 'From logo to landing page — visuals that communicate value and convert visitors into clients.', feats: ['Brand identity', 'Landing pages', 'UI/UX design', 'Conversion optimization'] },
    { name: 'Social Media', desc: 'Consistent, engaging presence across every platform. Content that builds audience and drives results.', feats: ['Content creation', 'Scheduling', 'Community mgmt', 'Analytics'] },
    { name: 'Analytics & Reporting', desc: 'Clear, actionable reports so you always know what\'s working. Full-funnel tracking from click to closed deal.', feats: ['Dashboard setup', 'Monthly reports', 'Attribution', 'Funnel analysis'] },
  ];
  return (
    <section id="services" className="t-section t-section-dark">
      <SectionHeader
        eyebrow="01 — SERVICES"
        title="Eight services."
        titleAccent="One strategist. Zero silos."
        kicker="Every channel, every tool — coordinated by one team that knows your Barbados market."
      />
      <div className="t-services-grid">
        {services.map((s, i) => (
          <div key={i} className={`t-service ${s.featured ? 't-service-featured' : ''}`}>
            {s.tag && <div className="t-service-tag">{s.tag}</div>}
            <div className="t-service-num">{String(i + 1).padStart(2, '0')}</div>
            <h3 className="t-service-name">
              {s.name}
            </h3>
            <p className="t-service-desc">{s.desc}</p>
            <ul className="t-service-feats">
              {s.feats.map((f, j) => (
                <li key={j}><span className="t-feat-dot" />{f}</li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div className="t-vpreview-deck">
        <VideoPreviewCard
          src="IMG_1914.mp4"
          title="See the stack in motion."
          subtitle="Terra · Field reel · Click for sound"
          tag="CLIP / 01"
        />
        <VideoPreviewCard
          src="IMG_1927.mp4"
          title="Go viral. Get seen."
          subtitle="Terra · Social & Growth · Click for sound"
          tag="CLIP / 02"
          startTime={4}
        />
        <VideoPreviewCard
          src="IMG_1928.mp4"
          title="Long-term growth. Real partnership."
          subtitle="Terra · Strategy & Retention · Click for sound"
          tag="CLIP / 03"
          startTime={5}
        />
        <VideoPreviewCard
          src="IMG_1921.mp4"
          title="AI agent in action."
          subtitle="Terra · Voice AI · Click for sound"
          tag="CLIP / 04"
        />
        <VideoPreviewCard
          src="IMG_1926.mp4"
          title="Web & SEO. Built to rank."
          subtitle="Terra · Web Dev & SEO · Click for sound"
          tag="CLIP / 05"
        />
      </div>
    </section>
  );
}

// ───── Results — case cards ─────
function Results() {
  const cases = [
    { vert: 'Home Services', metric: '$127K', label: 'tracked revenue / 90 days', client: 'Summit Roofing Co.', detail: 'Launched, tested & scaled to 3.8x ROAS in 90 days from a cold account.' },
    { vert: 'HVAC & Plumbing', metric: '0', label: 'missed calls — ever', client: 'Prestige Home Services', detail: 'From 15 lost calls a day to a fully automated front desk — 24/7.' },
    { vert: 'Legal Services', metric: '4.1x', label: 'return on ad spend', client: 'ClearPath Law Group', detail: 'Rebuilt Google Ads, added AI chatbot, cut cost-per-consultation by 61%.' },
    { vert: 'Aesthetics & Wellness', metric: '+340%', label: 'organic enquiries', client: 'Luxe Skin Clinic', detail: 'Ranked #1 locally in 90 days — booked 6 weeks out via SEO, Meta & social.' },
    { vert: 'Real Estate', metric: '#1', label: 'for 14 local keywords', client: 'NestFinder Realty', detail: 'Rebuilt content around buyer intent; organic now outperforms every paid channel.' },
    { vert: 'Financial Services', metric: '−61%', label: 'cost per lead', client: 'LoanBridge Financial', detail: 'Restructured paid media, tightened targeting, added email nurturing.' },
  ];
  return (
    <section id="results" className="t-section">
      <SectionHeader
        eyebrow="02 — PROVEN RESULTS"
        title="Real clients."
        titleAccent="Real numbers."
        kicker="Six markets. Six operators. Six receipts."
      />
      <div className="t-case-grid">
        {cases.map((c, i) => (<CaseCard key={i} c={c} i={i} />))}
      </div>
    </section>
  );
}

function CaseCard({ c, i }) {
  const ref = React.useRef(null);
  const seen = useInViewOnce(ref, 0.18);
  const delay = i * 110;
  return (
    <article
      ref={ref}
      className={'t-case' + (seen ? ' is-seen' : '')}
      style={{ transitionDelay: seen ? `${delay}ms` : '0ms' }}
    >
      <span className="t-case-corner t-case-corner-tl" />
      <span className="t-case-corner t-case-corner-tr" />
      <span className="t-case-corner t-case-corner-bl" />
      <span className="t-case-corner t-case-corner-br" />
      <div className="t-case-head">
        <span className="t-case-vert">
          <span className="t-case-vert-dot" />
          {c.vert}
        </span>
        <span className="t-case-num">CASE / {String(i + 1).padStart(2, '0')}</span>
      </div>
      <div className="t-case-metric">{c.metric}</div>
      <div className="t-case-label">{c.label}</div>
      <div className="t-case-rule" />
      <div className="t-case-client">{c.client}</div>
      <p className="t-case-detail">{c.detail}</p>
    </article>
  );
}

// ───── Process ─────
function Process() {
  const steps = [
    { n: '01', t: 'Discovery Call', d: 'Deep-dive into your goals, audience, and biggest gaps. You leave with a written 1-page growth audit — whether you hire us or not.' },
    { n: '02', t: 'Custom Strategy', d: 'Tailored growth plan with specific channels, timelines, and KPIs. You get a written proposal with exact deliverables before signing anything.' },
    { n: '03', t: 'Build & Launch', d: 'Campaigns live, AI configured, assets designed fast. Most clients are live within 2 weeks and receive a launch report on day one.' },
    { n: '04', t: 'Optimize & Scale', d: 'Monthly performance reports, live dashboard access, and a strategy call every 30 days. Real data drives every decision.' },
  ];
  return (
    <section id="process" className="t-section t-section-dark">
      <SectionHeader
        eyebrow="03 — THE METHOD"
        title="How we get"
        titleAccent="you results."
      />
      <div className="t-process">
        {steps.map((s, i) => (<StepCard key={i} s={s} i={i} isLast={i === steps.length - 1} />))}
      </div>
    </section>
  );
}

function StepCard({ s, i, isLast }) {
  const ref = React.useRef(null);
  const seen = useInViewOnce(ref, 0.25);
  const delay = i * 160;
  return (
    <div
      ref={ref}
      className={'t-step' + (seen ? ' is-seen' : '')}
      style={{ transitionDelay: seen ? `${delay}ms` : '0ms' }}
    >
      <div className="t-step-num">{s.n}</div>
      <div className="t-step-track">
        <div className="t-step-dot">
          <span className="t-step-dot-core" />
          <span className="t-step-dot-ring" />
        </div>
        {!isLast && <div className="t-step-line"><span className="t-step-line-fill" style={{ transitionDelay: seen ? `${delay + 300}ms` : '0ms' }} /></div>}
      </div>
      <div className="t-step-body">
        <h3 className="t-step-title">{s.t}</h3>
        <p className="t-step-desc">{s.d}</p>
      </div>
    </div>
  );
}

// ───── Testimonials ─────
// Hook: fires true once the element is visible, then stays true.
function useInViewOnce(ref, threshold = 0.15) {
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current || seen) return;
    const io = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) { setSeen(true); io.disconnect(); }
      },
      { threshold }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [seen, threshold]);
  return seen;
}

// Prints text character-by-character once visible (receipt printer vibe)
function TypePrint({ text, delay = 0, speed = 28, className, as = 'span', onDone }) {
  const ref = React.useRef(null);
  const seen = useInViewOnce(ref);
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    if (!seen) return;
    let raf, start = null;
    const total = text.length;
    const step = (ts) => {
      if (start == null) start = ts;
      const elapsed = ts - start - delay;
      if (elapsed < 0) { raf = requestAnimationFrame(step); return; }
      const chars = Math.min(total, Math.floor(elapsed / speed));
      setN(chars);
      if (chars < total) raf = requestAnimationFrame(step);
      else if (onDone) onDone();
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [seen, text, speed, delay]);
  const Tag = as;
  return (
    <Tag ref={ref} className={className}>
      {text.slice(0, n)}
      {seen && n < text.length && <span className="t-typecaret">▍</span>}
    </Tag>
  );
}

function QuoteCard({ qt, i }) {
  const ref = React.useRef(null);
  const seen = useInViewOnce(ref, 0.2);
  const delay = i * 140;
  return (
    <blockquote
      ref={ref}
      className={'t-quote' + (seen ? ' is-seen' : '')}
      style={{ transitionDelay: seen ? `${delay}ms` : '0ms' }}
    >
      <div className="t-quote-stamp">
        <span className="t-quote-stamp-k">RECEIPT №</span>
        <span className="t-quote-stamp-v">{String(i + 1).padStart(4, '0')}</span>
      </div>
      <div className="t-quote-mark" style={{ transitionDelay: `${delay + 120}ms` }}>“</div>
      <p className="t-quote-text" style={{ transitionDelay: `${delay + 180}ms` }}>{qt.q}</p>
      <div className="t-quote-foot" style={{ transitionDelay: `${delay + 260}ms` }}>
        <div>
          <div className="t-quote-name">{qt.name}</div>
          <div className="t-quote-role">{qt.role}</div>
        </div>
        <div className="t-quote-stat">
          <span className="t-quote-stat-dot" />
          {qt.stat}
        </div>
      </div>
    </blockquote>
  );
}

function Testimonials() {
  const quotes = [
    { q: "We went from drowning in missed calls to a fully booked schedule in three weeks. The AI receptionist paid for itself the first week.", name: 'Denise M.', role: 'Owner, Prestige Home Services', stat: '0 missed calls' },
    { q: "I've worked with five agencies. Terra is the first one that actually gives a damn about the number next to my name.", name: 'Marcus T.', role: 'Managing Partner, ClearPath Law', stat: '4.1x ROAS' },
    { q: "Fully booked six weeks out. From basically invisible to the #1 clinic in my zip code in 90 days. Not hype — that's my calendar.", name: 'Amelia K.', role: 'Founder, Luxe Skin Clinic', stat: '+340% enquiries' },
    { q: "They don't sell you a package. They build the thing you actually need, then they keep tuning it. That's why I stayed.", name: 'Ray P.', role: 'CEO, Summit Roofing Co.', stat: '$127K / 90 days' },
  ];
  const headRef = React.useRef(null);
  const seen = useInViewOnce(headRef, 0.2);
  return (
    <section id="testimonials" className="t-section">
      <div ref={headRef} className="t-section-head t-testi-head">
        <div className={'t-eyebrow t-eyebrow-anim' + (seen ? ' is-seen' : '')}>
          <span className="t-eyebrow-dot" />
          04 — WHAT CLIENTS SAY
        </div>
        <h2 className="t-h2">
          <span className={'t-testi-line' + (seen ? ' is-seen' : '')}>Not reviews.</span>
          <br/>
          {seen ? (
            <TypePrint
              className="t-accent"
              text="Receipts with names on them."
              delay={380}
              speed={32}
            />
          ) : (
            <span className="t-accent" style={{ opacity: 0 }}>Receipts with names on them.</span>
          )}
        </h2>
      </div>
      <div className="t-quote-grid">
        {quotes.map((qt, i) => (
          <QuoteCard key={i} qt={qt} i={i} />
        ))}
      </div>
    </section>
  );
}

// ───── Why Terra ─────
function WhyCard({ p, i }) {
  const ref = React.useRef(null);
  const seen = useInViewOnce(ref, 0.2);
  const delay = i * 140;
  return (
    <div
      ref={ref}
      className={'t-why-card' + (seen ? ' is-seen' : '')}
      style={{ transitionDelay: seen ? `${delay}ms` : '0ms' }}
    >
      <span className="t-why-wipe" />
      <div className="t-why-num">0{i + 1}</div>
      <div className="t-why-big-num" aria-hidden="true">0{i + 1}</div>
      <h3 className="t-why-title">{p.t}</h3>
      <p className="t-why-desc">{p.d}</p>
      <span className="t-why-arrow" aria-hidden="true">
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <path d="M5 17 L17 5" />
          <path d="M8 5 H17 V14" />
        </svg>
      </span>
    </div>
  );
}

function WhyTerra() {
  const points = [
    { t: 'Barbados-Based', d: 'We know your market, your customers, and the local competitive landscape. No guessing from overseas.' },
    { t: 'AI-Native', d: 'You get the AI Voice Receptionist as part of your stack — not as an upsell. It\'s built into how we operate.' },
    { t: 'Founder-Led', d: 'You work directly with Dmitri — not a junior account manager. Your strategy never gets lost in handoffs.' },
  ];
  return (
    <section className="t-section t-why">
      <SectionHeader
        eyebrow="05 — WHY TERRA"
        title="We don't win"
        titleAccent="unless you do."
      />
      <div className="t-why-grid">
        {points.map((p, i) => (<WhyCard key={i} p={p} i={i} />))}
      </div>
    </section>
  );
}

// ───── CTA + footer ─────
function Contact() {
  const [sent, setSent] = React.useState(false);
  const handleSubmit = (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);
    const name = fd.get('name');
    const biz = fd.get('business');
    const msg = fd.get('issue');
    window.location.href = `mailto:d.defreitas@wustl.edu?subject=Terra Enquiry from ${encodeURIComponent(name)} — ${encodeURIComponent(biz)}&body=${encodeURIComponent(`Name: ${name}\nBusiness: ${biz}\n\nWhat's not working:\n${msg}`)}`;
    setSent(true);
  };
  return (
    <section id="contact" className="t-section t-contact">
      <div className="t-contact-inner">
        <div className="t-contact-eyebrow">
          <span className="t-eyebrow-dot" /> 06 — LET'S TALK
        </div>
        <h2 className="t-contact-h">
          Ready to grow?<br/>
          <span className="t-accent">Let's find out if we fit.</span>
        </h2>
        <p className="t-contact-sub">
          30 minutes. We listen. You leave with a plan — hire us or don't.
        </p>
        <div className="t-contact-row">
          <div className="t-contact-left">
            <a className="t-cta-big" href="https://calendly.com" target="_blank" rel="noopener">BOOK A FREE CALL <span>→</span></a>
            <div className="t-contact-meta">
              <div><span className="t-meta-k">Email</span><span className="t-meta-v">d.defreitas@wustl.edu</span></div>
              <div><span className="t-meta-k">Phone</span><span className="t-meta-v">314·646·9845</span></div>
              <div><span className="t-meta-k">Web</span><span className="t-meta-v">dmitridefreitas.com</span></div>
            </div>
          </div>
          <form className="t-lead-form" onSubmit={handleSubmit}>
            <div className="t-lead-form-title">Or send a quick note</div>
            <input className="t-lead-input" name="name" type="text" placeholder="Your name" required />
            <input className="t-lead-input" name="business" type="text" placeholder="Business name" required />
            <textarea className="t-lead-input t-lead-textarea" name="issue" placeholder="What's not working?" rows={4} required />
            {sent ? (
              <div className="t-lead-sent">Opening your email client... we'll reply within 24h.</div>
            ) : (
              <button className="t-lead-submit" type="submit">Send message →</button>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="t-footer">
      <div className="t-footer-inner">
        <div className="t-footer-brand">
          <div className="t-logo"><span className="t-logo-dot" />TERRA.</div>
          <p>Real people. Real results. No BS.</p>
        </div>
        <div className="t-footer-cols">
          <div>
            <div className="t-footer-k">Services</div>
            <a href="#services">AI Receptionist</a>
            <a href="#services">AI Chatbot</a>
            <a href="#services">Paid Ads</a>
            <a href="#services">SEO & Content</a>
          </div>
          <div>
            <div className="t-footer-k">Company</div>
            <a href="#results">Results</a>
            <a href="#process">Process</a>
            <a href="#testimonials">Clients</a>
          </div>
          <div>
            <div className="t-footer-k">Contact</div>
            <a href="#contact">Book a call</a>
            <a href="mailto:d.defreitas@wustl.edu">Email</a>
            <a href="tel:3146469845">Phone</a>
          </div>
        </div>
      </div>
      <div className="t-footer-bottom">
        <span>© 2026 Terra. All receipts — no fluff.</span>
        <span>BRIDGETOWN · BARBADOS</span>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, StatsStrip, Services, Results, Process, Testimonials, WhyTerra, Contact, Footer,
  useInViewOnce, TypePrint, VideoPreviewCard,
});
