// 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);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  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>
        <a href="#contact" className="t-nav-cta">
          Book a call <span>→</span>
        </a>
      </div>
    </nav>
  );
}

// ───── 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>
  );
}

// ───── 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="Full-service growth,"
        titleAccent="powered by AI."
        kicker="Every lever pulled — and pulled in sync. No agency tennis, no channel silos."
      />
      <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">
              <span className="t-service-name-accent">{s.name.split(' ')[0]}</span>
              {s.name.split(' ').length > 1 ? ' ' + s.name.split(' ').slice(1).join(' ') : ''}
            </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>
    </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, current marketing & biggest growth opportunities.' },
    { n: '02', t: 'Custom Strategy', d: 'Tailored growth plan combining digital marketing, AI automation, and the right channels for your market.' },
    { n: '03', t: 'Build & Launch', d: 'Campaigns live, AI configured, assets designed fast. Most clients are live within 2 weeks.' },
    { n: '04', t: 'Optimize & Scale', d: 'Real data drives every decision — cut what doesn\'t work, double down on what does.' },
  ];
  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: 'Fast Onboarding', d: 'Most clients are live within 2 weeks of signing. No long setup timelines.' },
    { t: 'Dedicated Account Manager', d: 'One point of contact who knows your business inside and out.' },
    { t: 'No Long-Term Lock-In', d: 'Month-to-month agreements. We earn your business every single month.' },
  ];
  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() {
  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">
          Free strategy call for Barbados businesses. No commitment. No pressure. 30 minutes to tell us what's broken — we'll tell you if we can fix it.
        </p>
        <div className="t-contact-row">
          <a className="t-cta-big" href="#">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>
      </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,
});
