// zp-sections.jsx — content sections

// Animated counter
function Counter({to, duration=1400, prefix="", suffix="", decimals=0}) {
  const [v, setV] = React.useState(0);
  const ref = React.useRef(null);
  const started = React.useRef(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started.current) {
        started.current = true;
        const start = performance.now();
        function tick(now) {
          const t = Math.min(1, (now - start) / duration);
          const eased = 1 - Math.pow(1 - t, 3);
          setV(to * eased);
          if (t < 1) requestAnimationFrame(tick);
          else setV(to);
        }
        requestAnimationFrame(tick);
      }
    }, {threshold: 0.4});
    io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  const formatted = decimals > 0 ? v.toFixed(decimals)
    : Math.round(v).toLocaleString();
  return <span ref={ref} className="counter">{prefix}{formatted}{suffix}</span>;
}

// Reveal wrapper
function Reveal({children, stagger=false, as:Tag='div', className='', ...rest}) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        ref.current.classList.add('in');
        io.disconnect();
      }
    }, {threshold: 0.15});
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const cls = (stagger ? 'reveal-stagger ' : 'reveal ') + className;
  return <Tag ref={ref} className={cls} {...rest}>{children}</Tag>;
}

function Nav({ctaText}) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <a href="#" className="logo">
          <span className="logo-mark"><Ic.bolt style={{color:'#FFD60A'}}/></span>
          Zap Pilot
        </a>
        <div className="nav-links">
          <a href="#services">Services</a>
          <a href="#demo">Live demo</a>
          <a href="#results">Results</a>
          <a href="#roi">ROI</a>
          <a href="#pricing">Pricing</a>
        </div>
        <div className="nav-cta">
          <a href="https://api.leadconnectorhq.com/widget/bookings/zappilot" target="_blank" rel="noopener" className="btn btn-ghost" style={{height:38,padding:'0 14px',fontSize:13}}>Sign in</a>
          <a href="https://api.leadconnectorhq.com/widget/bookings/zappilot" target="_blank" rel="noopener" className="btn btn-primary" style={{height:38,padding:'0 16px',fontSize:13}}>
            {ctaText}<Ic.arrow className="arr" style={{width:14,height:14}}/>
          </a>
        </div>
      </div>
    </nav>
  );
}

function Hero({heroVariant, ctaText}) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) ref.current.classList.add('in');
    }, {threshold:0.2});
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  return (
    <header ref={ref} className="hero reveal">
      <div className="hero-bg"/>
      <div className="container">
        <div className="hero-grid">
          <div>
            <span className="eyebrow">AI growth partner for trades</span>
            <h1>
              Turn missed calls into <span className="accent">booked jobs</span>—on autopilot.
            </h1>
            <p className="lede">
              We build conversion-tuned websites, AI follow-up, and automatic appointment booking
              for plumbers, roofers, electricians, and landscapers. Less chasing, more revenue.
            </p>
            <div className="ctas">
              <a href="https://api.leadconnectorhq.com/widget/bookings/zappilot" target="_blank" rel="noopener" className="btn btn-primary">
                {ctaText}<Ic.arrow className="arr" style={{width:16,height:16}}/>
              </a>
              <a href="#demo" className="btn btn-ghost">Try the live demo</a>
            </div>
            <div className="trust">
              <span className="stars" aria-label="5 stars">
                {[...Array(5)].map((_,i) => <Ic.star key={i}/>)}
              </span>
              <span className="trust-text">
                <b>4.9/5</b> from <b>120+</b> trades operators · No long contracts
              </span>
            </div>
          </div>
          <div className="phone-wrap">
            <ScriptedPhone/>
            <div className="badge-float badge-1">
              <div className="icon"><Ic.check style={{width:14,height:14}}/></div>
              <div>
                <b>Job booked</b>
                <small>+£2,400 pipeline</small>
              </div>
            </div>
            <div className="badge-float badge-2">
              <div className="icon"><Ic.zap style={{width:14,height:14}}/></div>
              <div>
                <b>Replied in 12s</b>
                <small>Avg human: 47 min</small>
              </div>
            </div>
          </div>
        </div>

        <div className="strip">
          <div className="strip-inner">
            <span className="lbl">Trusted by trades pros</span>
            <div className="logos">
              <span>APEX&nbsp;ROOFING</span>
              <span>BLUEFLOW&nbsp;PLUMBING</span>
              <span>OAK&nbsp;&amp;&nbsp;IVY&nbsp;LANDSCAPE</span>
              <span>CIRCUIT&nbsp;PROS</span>
              <span>NORTHSTAR&nbsp;HVAC</span>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

function ProblemSection() {
  const items = [
    { pct: 78, label: "of leads call a competitor", body:"if you don't reply within 5 minutes — they're gone for good.", src:"Harvard Business Review" },
    { pct: 62, label: "of calls go unanswered", body:"during real jobs, on the road, or after hours. Each one is revenue walking out the door.", src:"FieldPulse, 2024" },
    { pct: 31, label: "average win-rate gap", body:"between top quartile trades operators and everyone else. Fast follow-up is the #1 driver.", src:"ServiceTitan benchmark" },
  ];
  return (
    <section id="problem" style={{paddingBottom:48}}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="eyebrow">The problem</span>
          <h2>Every missed message is a booked job for your competitor.</h2>
          <p>Trades businesses lose 6-figures a year to slow follow-up, missed calls, and websites that don't convert. AI fixes all three at once.</p>
        </Reveal>
        <Reveal className="problem-grid" stagger>
          {items.map((x,i) => (
            <div key={i} className="pain">
              <div className="pct"><sup>—</sup><Counter to={x.pct} suffix="%"/></div>
              <h4>{x.label}</h4>
              <p>{x.body}</p>
              <div className="src">Source · {x.src}</div>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function ServicesSection() {
  const svcs = [
    { n:"01", icon:<Ic.globe style={{width:20,height:20}}/>, title:"High-converting websites",
      body:"Fast, mobile-first sites built for trades — designed to turn cold visitors into hot leads.",
      pts:["Sub-2s page loads","Quote forms that auto-route","SEO for local searches","Built in 2 weeks"]},
    { n:"02", icon:<Ic.chat style={{width:20,height:20}}/>, title:"AI follow-up that closes",
      body:"Replies to texts, DMs, missed calls, and form fills in under a minute — 24/7. Sounds human.",
      pts:["Replies in seconds","Trained on your voice","Hands off to humans cleanly","SMS, email, web chat"]},
    { n:"03", icon:<Ic.cal style={{width:20,height:20}}/>, title:"Auto-booking & quoting",
      body:"Leads pick a slot, get a confirmation, and land on your schedule — all without a human touching it.",
      pts:["Self-serve scheduling","Instant ballpark quotes","Calendar + CRM sync","Reminders + no-show recovery"]},
    { n:"04", icon:<Ic.zap style={{width:20,height:20}}/>, title:"Revenue automations",
      body:"Review requests, repeat-customer winbacks, invoice nudges. The unglamorous stuff that prints money.",
      pts:["5-star review engine","Job-completion winbacks","Invoice & payment nudges","Referral programs"]},
  ];
  return (
    <section id="services">
      <div className="container">
        <Reveal className="sec-head">
          <span className="eyebrow">What we build</span>
          <h2>Four systems that compound your revenue.</h2>
          <p>We don't sell software. We install a complete growth machine, then tune it until it pays for itself.</p>
        </Reveal>
        <Reveal className="services" stagger>
          {svcs.map((s,i) => (
            <div key={i} className="svc">
              <span className="svc-num">{s.n}</span>
              <div className="svc-icon">{s.icon}</div>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
              <ul>{s.pts.map(p => <li key={p}>{p}</li>)}</ul>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function DemoSection() {
  return (
    <section id="demo" style={{background:'linear-gradient(180deg,#FAFAF7,#F4F2EC)'}}>
      <div className="container">
        <div className="demo-grid">
          <Reveal>
            <span className="eyebrow">Live demo · try it</span>
            <h2 style={{fontSize:'clamp(32px,4vw,52px)',lineHeight:1.05,letterSpacing:'-.03em',margin:'10px 0 18px',fontWeight:600}}>
              Text the AI like you're a customer.
            </h2>
            <p style={{fontSize:18,color:'var(--ink-2)',maxWidth:520,lineHeight:1.5,margin:0}}>
              This is the same AI that will answer your leads. Try asking about price, an emergency,
              or what times you're free. It'll book you in.
            </p>
            <ul className="feat-list">
              <li>
                <span className="check"><Ic.check style={{width:13,height:13,color:'#0A0A0F'}}/></span>
                <span><b>Trained on 1,200+ trades calls</b> — knows scope, urgency, and pricing tiers.</span>
              </li>
              <li>
                <span className="check"><Ic.check style={{width:13,height:13,color:'#0A0A0F'}}/></span>
                <span><b>Hands off to you when it should</b> — never confidently invents pricing or commitments.</span>
              </li>
              <li>
                <span className="check"><Ic.check style={{width:13,height:13,color:'#0A0A0F'}}/></span>
                <span><b>Books straight into your calendar</b> — Jobber, Housecall Pro, ServiceTitan, Google Cal.</span>
              </li>
            </ul>
          </Reveal>
          <Reveal style={{display:'grid',placeItems:'center'}}>
            <InteractivePhone/>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function HowSection() {
  const steps = [
    { n:"Step 01", title:"Audit & strategy", body:"30-min call, full audit of your funnel, and a custom plan you keep either way.", time:"Day 1" },
    { n:"Step 02", title:"Build & connect", body:"We design your site, train the AI on your business, and wire up your calendar + CRM.", time:"Days 2–10" },
    { n:"Step 03", title:"Launch & test", body:"We send real leads through the system end-to-end before you flip it on for customers.", time:"Day 11" },
    { n:"Step 04", title:"Tune & scale", body:"Weekly tuning, ad spend optimization, and new automations as your business grows.", time:"Ongoing" },
  ];
  return (
    <section id="how" style={{paddingTop:60}}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="eyebrow">How it works</span>
          <h2>Live in two weeks. Profitable in one quarter.</h2>
        </Reveal>
        <Reveal className="steps" stagger>
          {steps.map(s => (
            <div key={s.n} className="step">
              <div className="step-n">{s.n}</div>
              <h4>{s.title}</h4>
              <p>{s.body}</p>
              <span className="step-time">{s.time}</span>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function StatsSection() {
  return (
    <section id="results">
      <div className="container">
        <Reveal>
          <div className="stats-band">
            <span className="stats-eyebrow">Real results · case studies</span>
            <h2>Operators using Zap Pilot book 38% more jobs in their first 90 days.</h2>
            <div className="stats-grid">
              <div className="stat">
                <div className="num"><span className="pre">+</span><Counter to={38}/><span className="suf">%</span></div>
                <p>more booked jobs in the first 90 days, on average.</p>
              </div>
              <div className="stat">
                <div className="num"><Counter to={12}/><span className="suf">s</span></div>
                <p>median lead response time, day or night.</p>
              </div>
              <div className="stat">
                <div className="num"><span className="pre">£</span><Counter to={184}/><span className="suf">k</span></div>
                <p>average added pipeline per partner, year one.</p>
              </div>
              <div className="stat">
                <div className="num"><Counter to={4.9} decimals={1}/><span className="suf">★</span></div>
                <p>average review rating after our review engine kicks in.</p>
              </div>
            </div>

            <div className="case-row">
              <div className="case">
                <span className="trade">Roofing · Tampa</span>
                <h5>Apex Roofing</h5>
                <div className="delta"><span className="arrow">↑</span><Counter to={62} suffix="%"/></div>
                <p>booked inspections in 60 days after replacing their old site and turning on AI follow-up.</p>
              </div>
              <div className="case">
                <span className="trade">Plumbing · Denver</span>
                <h5>Blueflow Plumbing</h5>
                <div className="delta"><span className="arrow">↑</span><span>£</span><Counter to={22}/><span style={{fontSize:18,opacity:.6,marginLeft:4}}>k/mo</span></div>
                <p>added MRR from after-hours emergency leads they used to lose to voicemail.</p>
              </div>
              <div className="case">
                <span className="trade">Landscaping · Austin</span>
                <h5>Oak &amp; Ivy Landscape</h5>
                <div className="delta"><span className="arrow">↑</span><Counter to={3.4} decimals={1}/><span style={{fontSize:18,opacity:.6,marginLeft:4}}>×</span></div>
                <p>quote-to-close rate after switching to instant ballpark quotes via SMS.</p>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function ROISection() {
  const [calls, setCalls] = React.useState(120);
  const [ticket, setTicket] = React.useState(850);
  const [closeRate, setCloseRate] = React.useState(22);

  const recovered = Math.round(calls * 0.28);
  const newCloseRate = Math.min(60, closeRate * 1.30);
  const newJobsPerMonth = Math.round((calls + recovered) * (newCloseRate/100));
  const oldJobsPerMonth = Math.round(calls * (closeRate/100));
  const extraJobs = Math.max(0, newJobsPerMonth - oldJobsPerMonth);
  const extraRevenuePerMonth = extraJobs * ticket;
  const extraRevenuePerYear = extraRevenuePerMonth * 12;

  function fmt(n) { return n.toLocaleString('en-US'); }

  return (
    <section id="roi" style={{background:'#F4F2EC'}}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="eyebrow">ROI calculator · live</span>
          <h2>See what fast follow-up is worth to your business.</h2>
          <p>Slide your numbers. The recovered revenue assumes typical Zap Pilot benchmarks across our trades partners.</p>
        </Reveal>
        <Reveal className="roi">
          <div className="roi-card">
            <div>
              <label>Monthly inbound leads</label>
              <div className="roi-input">
                <input type="number" value={calls}
                  onChange={e => setCalls(Math.max(0, Number(e.target.value)||0))}/>
                <span style={{color:'var(--muted)',fontSize:13}}>/mo</span>
              </div>
              <input type="range" className="roi-slider" min="20" max="600" step="10"
                value={calls} onChange={e => setCalls(Number(e.target.value))}/>
            </div>
            <div>
              <label>Average job value</label>
              <div className="roi-input">
                <span className="pre">£</span>
                <input type="number" value={ticket}
                  onChange={e => setTicket(Math.max(0, Number(e.target.value)||0))}/>
              </div>
              <input type="range" className="roi-slider" min="100" max="8000" step="50"
                value={ticket} onChange={e => setTicket(Number(e.target.value))}/>
            </div>
            <div>
              <label>Current close rate</label>
              <div className="roi-input">
                <input type="number" value={closeRate}
                  onChange={e => setCloseRate(Math.min(80, Math.max(0, Number(e.target.value)||0)))}/>
                <span style={{color:'var(--muted)',fontSize:13}}>%</span>
              </div>
              <input type="range" className="roi-slider" min="5" max="60" step="1"
                value={closeRate} onChange={e => setCloseRate(Number(e.target.value))}/>
            </div>
          </div>
          <div className="roi-result">
            <div>
              <div className="lbl">Projected added revenue</div>
              <div className="roi-big"><span className="dol">£</span>{fmt(extraRevenuePerYear)}<span style={{fontSize:'.35em',color:'rgba(255,255,255,.55)',marginLeft:6,fontWeight:500}}>/year</span></div>
              <p className="roi-sub">…on top of what you make today, by recovering missed leads and lifting close rate.</p>
            </div>
            <div className="roi-breakdown">
              <div>
                <div className="l">Extra jobs / mo</div>
                <div className="v">+{fmt(extraJobs)}</div>
              </div>
              <div>
                <div className="l">New close rate</div>
                <div className="v">{newCloseRate.toFixed(0)}%</div>
              </div>
              <div>
                <div className="l">Added MRR</div>
                <div className="v">£{fmt(extraRevenuePerMonth)}</div>
              </div>
              <div>
                <div className="l">Payback</div>
                <div className="v">{extraRevenuePerMonth > 1500 ? '< 30d' : '~ 60d'}</div>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function TestimonialsSection() {
  const t = [
    { quote:"We used to lose every after-hours lead to voicemail. Now they're booked before I even know they called.", name:"Marcus J.", role:"Owner · Apex Roofing", initials:"MJ" },
    { quote:"The site looks twice as expensive as my last one and converts five times better. Paid for itself in 6 weeks.", name:"Priya R.", role:"Owner · Blueflow Plumbing", initials:"PR" },
    { quote:"My techs aren't fielding scheduling texts anymore. Quotes go out instantly, jobs land on the calendar. It's quiet — in a good way.", name:"Drew K.", role:"GM · Northstar Electric", initials:"DK" },
  ];
  return (
    <section id="testimonials">
      <div className="container">
        <Reveal className="sec-head">
          <span className="eyebrow">Operators talking</span>
          <h2>Trades pros who flipped the switch.</h2>
        </Reveal>
        <Reveal className="testimonials" stagger>
          {t.map((q,i) => (
            <div key={i} className="quote">
              <span className="stars">{[...Array(5)].map((_,j) => <Ic.star key={j}/>)}</span>
              <blockquote>"{q.quote}"</blockquote>
              <div className="quote-by">
                <div className="av">{q.initials}</div>
                <div>
                  <div className="name">{q.name}</div>
                  <div className="role">{q.role}</div>
                </div>
              </div>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function PricingSection({ctaText}) {
  const tiers = [
    { name:"Starter", meta:"Everything you need to get your first leads coming in on autopilot.", price:"£197", per:"/mo",
      pts:["Custom conversion-tuned website","Hosting","SEO","AI missed call text back","Google review automation"], cta:"Get started" },
    { name:"Growth", meta:"The full system — website, AI agent, CRM and full automation stack.", price:"£297", per:"/mo", featured:true,
      pts:["Everything in Starter","AI text agent that books quotes on autopilot","Monthly performance reviews","Automatic appointment & quote booking","Custom CRM built for your business"], cta:"Most popular" },
    { name:"Scale", meta:"For multi-location teams with serious lead flow.", price:"Custom", per:"",
      pts:["Everything in Growth","Custom automations","Multi-location dashboards","Dedicated success manager","Quarterly strategy reviews","SLA + uptime guarantees"], cta:"Talk to us" },
  ];
  return (
    <section id="pricing">
      <div className="container">
        <Reveal className="sec-head">
          <span className="eyebrow">Pricing</span>
          <h2>Simple plans. No long contracts. Cancel anytime.</h2>
          <p>Most partners pay for the year on their first 30 jobs through the system.</p>
        </Reveal>
        <Reveal className="pricing" stagger>
          {tiers.map(t => (
            <div key={t.name} className={`tier ${t.featured ? 'featured' : ''}`}>
              {t.featured && <span className="ribbon">Most popular</span>}
              <h3>{t.name}</h3>
              <div className="tier-meta">{t.meta}</div>
              <div className="price">
                <span className="price-num">{t.price}</span>
                <span className="per">{t.per}</span>
              </div>
              <ul>{t.pts.map(p => <li key={p}>{p}</li>)}</ul>
              <a href="https://api.leadconnectorhq.com/widget/bookings/zappilot" target="_blank" rel="noopener" className={`btn ${t.featured ? 'btn-accent' : 'btn-ghost'}`}>
                {t.featured ? ctaText : t.cta}
              </a>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function FaqSection() {
  const items = [
    { q:"How long until we're live?", a:"Most partners are live in 10–14 days. We design and build in parallel: site, AI training, calendar/CRM wiring, and a thorough end-to-end test before any real customer touches it." },
    { q:"What if the AI says something wrong?", a:"It won't invent prices or make commitments — it's trained to escalate to a human the moment a conversation moves outside its trained scope. You set the guardrails; we tune them." },
    { q:"Will it work with my CRM and scheduler?", a:"Yes. We integrate natively with Jobber, Housecall Pro, ServiceTitan, Google Calendar, and most major dispatch tools. If you're on something custom, we'll wire it up." },
    { q:"What if I already have a website?", a:"We'll audit it free. If it converts well we leave it alone and bolt on the AI + automations. If it doesn't, we rebuild it — included in your plan." },
    { q:"What's the contract look like?", a:"Month-to-month. No setup fees on annual. Most partners stay 18+ months because the system pays for itself many times over." },
    { q:"Which trades do you specialize in?", a:"Roofing, plumbing, electrical, HVAC, landscaping, garage doors, pool service, and pest control. If your business books jobs and quotes work, we can help." },
  ];
  return (
    <section id="faq">
      <div className="container">
        <Reveal className="sec-head" style={{textAlign:'center',justifyItems:'center',margin:'0 auto 40px'}}>
          <span className="eyebrow">FAQ</span>
          <h2>Common questions.</h2>
        </Reveal>
        <Reveal className="faq" stagger>
          {items.map((it,i) => (
            <details key={i} className="faq-item" {...(i===0?{open:true}:{})}>
              <summary>{it.q}</summary>
              <div className="answer">{it.a}</div>
            </details>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function FinalCta({ctaText}) {
  return (
    <section id="final" className="final">
      <div className="container">
        <Reveal>
          <span className="eyebrow" style={{justifyContent:'center'}}>Ready when you are</span>
          <h2 style={{marginTop:18}}>Stop losing jobs<br/>to slow follow-up.</h2>
          <p>30-minute call. We'll audit your funnel, show you exactly where money is leaking, and you keep the plan whether or not we work together.</p>
          <div className="ctas">
            <a href="https://api.leadconnectorhq.com/widget/bookings/zappilot" target="_blank" rel="noopener" className="btn btn-accent">{ctaText}<Ic.arrow className="arr" style={{width:16,height:16}}/></a>
            <a href="#demo" className="btn btn-ghost">Try the demo first</a>
          </div>
          <div className="pill-row">
            <span>Free strategy audit</span>
            <span>No long contracts</span>
            <span>Live in 14 days</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="container ft-grid">
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          <span className="logo-mark"><Ic.bolt style={{color:'#FFD60A'}}/></span>
          <span style={{fontWeight:600,color:'var(--ink)'}}>Zap Pilot</span>
          <span style={{marginLeft:14,fontSize:13}}>© 2026 — built for trades operators.</span>
        </div>
        <div className="links">
          <a href="#">Privacy</a><a href="#">Terms</a><a href="#">Careers</a><a href="#">Contact</a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Counter, Reveal, Nav, Hero, ProblemSection, ServicesSection, DemoSection, HowSection,
  StatsSection, ROISection, TestimonialsSection, PricingSection, FaqSection, FinalCta, Footer
});
