// Achieve — interactive landing app
const { useState, useEffect, useRef, useMemo } = React;

// ===== Icons =====
const Icon = {
  arrow: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M5 12h14M13 5l7 7-7 7"/></svg>),
  check: (p) => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" {...p}><polyline points="20 6 9 17 4 12"/></svg>),
  send: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M5 12L20 5l-3 15-5-7-7-1z"/></svg>),
  plus: (p) => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M12 5v14M5 12h14"/></svg>),
  phone: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>),
  mail: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 7L12 14 2 7"/></svg>),
  ig: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.6" fill="currentColor"/></svg>),
  spark: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M12 2v6M12 16v6M2 12h6M16 12h6M5 5l4 4M15 15l4 4M19 5l-4 4M9 15l-4 4"/></svg>),
  bot: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="3" y="7" width="18" height="13" rx="3"/><path d="M12 7V3M9 12h.01M15 12h.01M9 17h6"/></svg>),
  flow: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="5" cy="6" r="2"/><circle cx="19" cy="6" r="2"/><circle cx="12" cy="18" r="2"/><path d="M7 6h10M6 8l5 8M18 8l-5 8"/></svg>),
  inbox: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>),
  globe: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 0 20M12 2a15.3 15.3 0 0 0 0 20"/></svg>),
  star: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>),
  search: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>),
  rocket: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>),
};

// ===== Nav =====
function Nav() {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#top" className="logo">
          <span className="logo-mark">A</span>
          <span>achieve<em>.</em></span>
        </a>
        <div className="nav-links">
          <a href="#services">Services</a>
          <a href="#how">How it works</a>
          <a href="#demo">Demo</a>
          <a href="#pricing">Pricing</a>
          <a href="#faq">FAQ</a>
        </div>
        <a className="nav-cta" href="#contact">Start automating <Icon.arrow /></a>
      </div>
    </nav>
  );
}

// ===== Hero =====
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-grid"></div>
      <div className="hero-glow"></div>
      <div className="wrap">
        <div className="hero-inner">
          <span className="eyebrow"><span className="dot"></span>Automation studio for businesses</span>
          <h1>Stop losing leads to <em>slow replies</em> and silent inboxes.</h1>
          <p className="hero-sub">
            Achieve builds the automations and websites businesses need to capture every lead, follow up the moment it matters, and turn missed calls into booked work, without hiring another person.
          </p>
          <div className="hero-ctas">
            <a className="btn btn-primary" href="#contact">Start automating <Icon.arrow /></a>
            <a className="btn btn-ghost" href="#demo">See it in action</a>
          </div>
          <dl className="hero-meta">
            <div>
              <dt>Response time</dt>
              <dd><em>under 60s</em></dd>
            </div>
            <div>
              <dt>Channels covered</dt>
              <dd>SMS · Email · Web · IG</dd>
            </div>
            <div>
              <dt>Setup time</dt>
              <dd>2–3 weeks</dd>
            </div>
            <div>
              <dt>Built for</dt>
              <dd>1–25 person teams</dd>
            </div>
          </dl>
        </div>
      </div>
    </section>
  );
}

// ===== Services =====
const SERVICES = [
  {
    id: "missed-call",
    icon: <Icon.phone />,
    label: "Missed-call textback",
    tag: "Most common",
    title: "Never let a missed call become a lost customer.",
    blurb: "When a call goes unanswered, Achieve fires off a friendly text within seconds, qualifies the lead, and books them right into your calendar, or hands them to a human if it's hot.",
    features: [
      ["Under 60s response", "Texts go out the moment a call is missed."],
      ["Two-way SMS", "Replies thread back into your inbox or CRM."],
      ["Smart routing", "After-hours, weekends, and holidays handled."],
      ["Bilingual ready", "EN/FR templates available out of the box."],
    ],
  },
  {
    id: "chatbot",
    icon: <Icon.bot />,
    label: "Website chatbot",
    tag: "Conversion lift",
    title: "A 24/7 concierge on every page of your site.",
    blurb: "Trained on your services, hours, and pricing. Answers questions, qualifies visitors, and quietly drops the warm ones into your CRM with the context you need to close.",
    features: [
      ["Trained on your business", "Pulls from your real docs, FAQ, and pricing."],
      ["Lead capture", "Names, numbers, intent. Saved automatically."],
      ["Calendar booking", "Hot leads can self-book a slot live in chat."],
      ["Handoff to human", "Escalate any thread to your inbox in one tap."],
    ],
  },
  {
    id: "outreach",
    icon: <Icon.flow />,
    label: "Outreach automation",
    tag: "Pipeline builder",
    title: "Cold pipeline that runs while you work the warm one.",
    blurb: "Targeted lists, multi-step sequences, and reply-detection that pauses threads the moment a real human writes back. We set the system, you take the meetings.",
    features: [
      ["Personalized at scale", "First-line and offer-line tailored per prospect."],
      ["Multi-channel", "Email, LinkedIn, and SMS in one cadence."],
      ["Deliverability first", "Warmup, SPF/DKIM, and inbox rotation handled."],
      ["Reply-aware", "Sequence stops the second they engage."],
    ],
  },
  {
    id: "email",
    icon: <Icon.inbox />,
    label: "Email campaigns",
    tag: "Recurring revenue",
    title: "Bring quiet customers back without lifting a finger.",
    blurb: "Win-back flows, post-purchase nurtures, and seasonal campaigns wired to your CRM or POS. Set once, earn monthly.",
    features: [
      ["Win-back flows", "Re-engage anyone who's gone cold in 60+ days."],
      ["Branded templates", "Designed in your voice and palette."],
      ["A/B everything", "Subject lines, offers, and timing tested live."],
      ["Reporting that's readable", "Plain-English monthly summary, no jargon."],
    ],
  },
  {
    id: "reviews",
    icon: <Icon.star />,
    label: "Review automation",
    tag: "Reputation",
    title: "More five-stars, automatic responses, zero scrambling.",
    blurb: "After every job, customers get a friendly review request. New reviews, good or bad, get a thoughtful reply drafted by AI, ready in your inbox to approve or send.",
    features: [
      ["Auto request", "Triggered after a job closes or invoice is paid."],
      ["Drafted replies", "AI writes, you approve in one click."],
      ["Negative review safety", "Bad reviews route to you privately first."],
      ["Multi-platform", "Google, Facebook, Yelp, and more."],
    ],
  },
  {
    id: "follow-up",
    icon: <Icon.search />,
    label: "Lead follow-up & management",
    tag: "Pipeline hygiene",
    title: "A CRM that actually nudges you when it matters.",
    blurb: "Centralized lead inbox with auto-tagging, reminders, and follow-up cadences so nothing rots in a spreadsheet. Works with what you already use.",
    features: [
      ["Unified inbox", "Calls, texts, emails, and form fills in one view."],
      ["Auto-tagging", "Hot, warm, cold. Scored on real behavior."],
      ["Smart reminders", "Pings you the moment a follow-up is due."],
      ["Plays nice", "Integrates with HubSpot, GHL, Sheets, Airtable."],
    ],
  },
  {
    id: "site",
    icon: <Icon.globe />,
    label: "Conversion-built websites",
    tag: "Foundation",
    title: "Fast, trustworthy sites built to actually convert.",
    blurb: "We design and ship sites that load instantly, rank locally, and funnel visitors into your automations. Not generic template work.",
    features: [
      ["Fast by default", "Lighthouse 95+ on mobile, every time."],
      ["Local SEO ready", "Schema, GBP, and on-page handled."],
      ["Built around your funnel", "Every page nudges toward your CTA."],
      ["You own everything", "Full code, full assets, no lock-in."],
    ],
  },
  {
    id: "reports",
    icon: <Icon.spark />,
    label: "Reports & dashboards",
    tag: "Visibility",
    title: "See what's working in 30 seconds, not 30 minutes.",
    blurb: "A clean monthly dashboard showing leads in, replies out, conversion, and revenue impact. Written in your language, not analytics-speak.",
    features: [
      ["Plain-English KPIs", "What changed, what's next, why it matters."],
      ["Live dashboard link", "Share with partners or your team anytime."],
      ["Source attribution", "Know which channel actually books the work."],
      ["Monthly review call", "Optional 30-min strategy call each month."],
    ],
  },
];

function Services() {
  const [active, setActive] = useState(SERVICES[0].id);
  const svc = SERVICES.find(s => s.id === active);
  return (
    <section className="sec" id="services" data-screen-label="Services">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow"><span className="dot"></span>What we build</span>
            <h2>Built for the way <em>businesses</em> actually grow.</h2>
          </div>
          <p>Pick the automation that's bleeding the most leads today and we'll have it running in days. Most clients start with one and add the rest as ROI shows up.</p>
        </div>
        <div className="svc-layout">
          <div className="svc-list">
            {SERVICES.map((s, i) => (
              <button
                key={s.id}
                className={"svc-item" + (active === s.id ? " active" : "")}
                onClick={() => setActive(s.id)}
              >
                <span className="num">0{i+1}</span>
                <span>{s.label}</span>
                <Icon.arrow className="arrow" />
              </button>
            ))}
          </div>
          <div className="svc-detail" key={svc.id}>
            <span className="svc-detail-tag">{svc.icon}{svc.tag}</span>
            <h3>{svc.title}</h3>
            <p>{svc.blurb}</p>
            <div className="svc-features">
              {svc.features.map(([t, d]) => (
                <div className="svc-feature" key={t}>
                  <span className="svc-feature-icon"><Icon.check /></span>
                  <span className="svc-feature-text"><b>{t}.</b> {d}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== How it works =====
function HowItWorks() {
  const steps = [
    { n: "01", icon: <Icon.search />, t: "Audit", d: "We map your current funnel: every lead source, dead spot, and slow follow-up. You get a written diagnosis and a quote, free." },
    { n: "02", icon: <Icon.flow />, t: "Design", d: "We design the automations around your real workflow, not a template. You approve copy, branching, and tone before anything goes live." },
    { n: "03", icon: <Icon.rocket />, t: "Launch", d: "We ship it, connect it to your existing tools, and stress-test with real traffic. Most builds are live in 2–3 weeks." },
    { n: "04", icon: <Icon.spark />, t: "Tune", d: "We watch the numbers, refine the prompts, and add new flows as your team grows. Reporting comes monthly, in plain English." },
  ];
  return (
    <section className="sec" id="how" data-screen-label="How it works" style={{paddingTop: 0}}>
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow"><span className="dot"></span>How it works</span>
            <h2>Four steps from <em>audit</em> to live system.</h2>
          </div>
          <p>No hand-wavy "AI strategy" decks. We diagnose, build, ship, and tune. You keep ownership of everything we make.</p>
        </div>
        <div className="steps">
          {steps.map(s => (
            <div className="step" key={s.n}>
              <div className="step-icon">{s.icon}</div>
              <div className="step-num">{s.n}</div>
              <h4>{s.t}</h4>
              <p>{s.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ===== Chatbot demo =====
const BOT_SYSTEM = `You are Ava, the friendly AI concierge for Achieve, an automation studio run by Zane Robertson that helps businesses stop losing leads.

What Achieve builds:
- Missed-call textback (auto-text missed callers in under 60s): Setup $500, $150/mo
- AI website chatbot (24/7 lead capture, books appointments): Setup $500, $200/mo
- Review request automation (auto-asks for reviews after jobs, AI-drafted replies): Setup $300, $100/mo
- Lead follow-up & CRM (unified inbox, smart reminders, auto-tagging): Setup $400, $150/mo
- Email campaigns (win-back, nurture, A/B tested): Setup $400, $125/mo
- Cold outreach automation (multi-channel, reply-aware, deliverability-tuned)
- Conversion-built websites (fast, local-SEO ready): Setup $1,250
- Reports & dashboards (plain-English monthly summaries)

Packages (better value):
- Starter Pack ($1,000 setup + $250/mo): Website + Missed-call textback + Review automation
- Growth Pack ($2,000 setup + $450/mo): Everything in Starter + Lead follow-up + AI chat widget
- Full Stack ($3,500 setup + $700/mo): Everything in Growth + Email campaigns + CRM pipeline + Priority support + AI receptionist (answers calls, qualifies, books)

Process: Free 30-min audit, then Design (you approve everything), then Launch, then ongoing tuning. Client owns all code, prompts, and assets. No lock-in. Pricing is negotiable.

Contact: zane.rw.robertson@gmail.com · (416) 660-3723 · IG @zanerobertsonn

How to chat:
- Be warm, concise, conversational. 1–3 short sentences per reply. No bullet lists unless explicitly asked.
- Answer questions directly using the info above. If a question is genuinely outside your knowledge (very technical integration specifics, custom contracts, NDAs, anything Zane should answer personally), say so honestly and offer to connect them with Zane.
- Only suggest booking an audit when it actually makes sense: the user is showing buying intent, asking about pricing for their specific situation, ready to move forward, or has shared enough that scoping is the obvious next step. NEVER pitch the audit on every reply; it's annoying.
- If the user is just exploring or asking general questions, just answer the question. No CTA tail.
- Don't invent stats or claim track records. If asked about case studies, mention Zane has worked with a family-owned trade business (website + textback) and an independent influencer (cold email outreach for brand deals).
- Never use markdown formatting (no asterisks, no headers).`;

function Chatbot() {
  const initialQuick = ["What do you build?", "How much does it cost?", "Will it work for my business?"];
  const [messages, setMessages] = useState([{ from: "bot", text: "Hey 👋 I'm Ava, the automation concierge for Achieve. What can I help you figure out?" }]);
  const [quick, setQuick] = useState(initialQuick);
  const [typing, setTyping] = useState(false);
  const [input, setInput] = useState("");
  const bodyRef = useRef(null);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, typing]);

  const send = async (txt) => {
    if (!txt) return;
    const newHistory = [...messages, { from: "user", text: txt }];
    setMessages(newHistory);
    setQuick([]);
    setTyping(true);

    try {
      const apiMessages = newHistory.map(m => ({
        role: m.from === "user" ? "user" : "assistant",
        content: m.text,
      }));
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ system: BOT_SYSTEM, messages: apiMessages }),
      });
      const data = await res.json();
      setMessages(m => [...m, { from: "bot", text: (data.reply || "").trim() || "Hmm, can you say that another way?" }]);
    } catch (e) {
      setMessages(m => [...m, { from: "bot", text: "Sorry, I hit a snag. You can text Zane directly at (416) 660-3723." }]);
    } finally {
      setTyping(false);
    }
  };

  const onSubmit = (e) => { e.preventDefault(); if (input.trim()) { send(input.trim()); setInput(""); } };

  return (
    <section className="sec" id="demo" data-screen-label="Demo">
      <div className="wrap">
        <div className="demo-grid">
          <div className="demo-text">
            <span className="eyebrow"><span className="dot"></span>Live on your site</span>
            <h2>Try the <em>chatbot</em> we'd put on your website.</h2>
            <p>This is the actual concierge experience your visitors get. Trained on your business, polite, persistent, and quietly dropping qualified leads into your inbox while you work.</p>
            <div className="demo-bullets">
              <div className="demo-bullet"><Icon.check /><span>Replies in under 2 seconds, every time, all hours.</span></div>
              <div className="demo-bullet"><Icon.check /><span>Qualifies leads with the questions you'd ask yourself.</span></div>
              <div className="demo-bullet"><Icon.check /><span>Books appointments live or hands hot leads to a human.</span></div>
              <div className="demo-bullet"><Icon.check /><span>Voice and tone match your brand. Never robotic.</span></div>
            </div>
            <a className="btn btn-primary" href="#contact">Put one on my site <Icon.arrow /></a>
          </div>
          <div className="chatbot">
            <div className="chat-header">
              <div className="chat-avatar">A</div>
              <div>
                <div className="chat-name">Ava, Achieve concierge</div>
                <div className="chat-sub"><span className="live"></span>online · replies instantly</div>
              </div>
            </div>
            <div className="chat-body" ref={bodyRef}>
              {messages.map((m, i) => (
                <div key={i} className={"msg " + m.from}>{m.text}</div>
              ))}
              {typing && <div className="msg bot typing"><span></span><span></span><span></span></div>}
              {quick.length > 0 && !typing && (
                <div className="chat-quick">
                  {quick.map(q => <button key={q} onClick={() => send(q)}>{q}</button>)}
                </div>
              )}
            </div>
            <form className="chat-input" onSubmit={onSubmit}>
              <input value={input} onChange={e => setInput(e.target.value)} placeholder="Type a message..." />
              <button className="chat-send" type="submit"><Icon.send /></button>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== ROI Calculator =====
function ROI() {
  const [calls, setCalls] = useState(80);
  const [missedPct, setMissedPct] = useState(35);
  const [value, setValue] = useState(450);
  const [closeRate, setCloseRate] = useState(25);

  const missedCalls = Math.round(calls * missedPct / 100);
  const recoveryRate = 0.55;
  const recoveredLeads = Math.round(missedCalls * recoveryRate);
  const newCustomers = Math.round(recoveredLeads * closeRate / 100);
  const monthly = newCustomers * value;
  const yearly = monthly * 12;

  const fmt = (n) => "$" + n.toLocaleString("en-US");

  return (
    <section className="sec" id="roi" data-screen-label="ROI" style={{paddingTop: 0}}>
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow"><span className="dot"></span>ROI Calculator</span>
            <h2>How much money is <em>silence</em> costing you?</h2>
          </div>
          <p>Move the sliders to your real numbers. We use a 55% missed-call recovery rate (the industry average for textback automations) to estimate what Achieve would put back on your books.</p>
        </div>
        <div className="roi-card">
          <div className="roi-inputs">
            <div className="roi-input">
              <label>Inbound calls / month <b>{calls}</b></label>
              <input type="range" min="10" max="500" step="10" value={calls} onChange={e => setCalls(+e.target.value)} />
            </div>
            <div className="roi-input">
              <label>% of calls missed today <b>{missedPct}%</b></label>
              <input type="range" min="5" max="80" step="1" value={missedPct} onChange={e => setMissedPct(+e.target.value)} />
            </div>
            <div className="roi-input">
              <label>Avg. customer value <b>{fmt(value)}</b></label>
              <input type="range" min="50" max="5000" step="50" value={value} onChange={e => setValue(+e.target.value)} />
            </div>
            <div className="roi-input">
              <label>Your typical close rate <b>{closeRate}%</b></label>
              <input type="range" min="5" max="80" step="1" value={closeRate} onChange={e => setCloseRate(+e.target.value)} />
            </div>
          </div>
          <div className="roi-output">
            <div>
              <div className="roi-output-label">Estimated monthly recovery</div>
              <div className="roi-big">{fmt(monthly)}</div>
              <div className="roi-sub">That's <b style={{color: "var(--fg)"}}>{fmt(yearly)}</b> a year you're leaving on the table to slow replies.</div>
            </div>
            <div className="roi-breakdown">
              <div><div className="lbl">Missed calls / mo</div><div className="val">{missedCalls}</div></div>
              <div><div className="lbl">Recovered leads</div><div className="val">{recoveredLeads}</div></div>
              <div><div className="lbl">New customers</div><div className="val">{newCustomers}</div></div>
              <div><div className="lbl">Monthly upside</div><div className="val" style={{color: "var(--lime)"}}>{fmt(monthly)}</div></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== About Zane =====
function About() {
  return (
    <section className="sec" id="about" data-screen-label="About" style={{paddingTop: 0}}>
      <div className="wrap">
        <div className="about about-text-only">
          <div className="about-text">
            <span className="eyebrow"><span className="dot"></span>About</span>
            <h2>Built by <em>Zane Robertson</em>.</h2>
            <p>I started Achieve after watching businesses, including my dad's, lose customers they never even knew called. The problem was never effort. It was the gap between the lead landing and someone actually reaching out.</p>
            <p>Every automation, every page of copy, every chatbot prompt — I build it personally. When you work with Achieve, you have direct access to the person who built your system, not a support queue.</p>
            <p>If you're tired of leads going quiet because nobody got back to them fast enough, that's exactly what I fix.</p>
          </div>
          <div className="about-cards">
            <div className="about-card">
              <div className="about-card-icon"><Icon.phone /></div>
              <h4>Started with a real problem</h4>
              <p>My dad's trade business was losing jobs to competitors simply because calls went unanswered. I built the fix. It worked. That became Achieve.</p>
            </div>
            <div className="about-card">
              <div className="about-card-icon"><Icon.flow /></div>
              <h4>Built across industries</h4>
              <p>From home services to content creators to professional services — if a business relies on inbound leads, there's a system that stops the leaks.</p>
            </div>
            <div className="about-card">
              <div className="about-card-icon"><Icon.spark /></div>
              <h4>You own everything</h4>
              <p>Every login, every prompt, every line of code is yours. No dependency on Achieve forever. You walk away with a system that runs on its own.</p>
            </div>
            <div className="about-card">
              <div className="about-card-icon"><Icon.rocket /></div>
              <h4>Direct line, always</h4>
              <p>You get my number and email from day one. Questions get answered by the person who built your system, not passed around.</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== FAQ =====
const FAQS = [
  ["Do I need to already have software in place?", "No. Achieve plugs into whatever you have, or sets up the lightest stack that works. Most builds use tools you may already pay for (Twilio, GHL, HubSpot, Google Workspace) so monthly costs stay low."],
  ["Will the bot sound like a robot?", "No. Voice and tone are written to match your brand. We'll use your actual copy, your real FAQs, and the way you'd answer a customer in person. You approve every word before it goes live."],
  ["Do I own the work after we're done?", "Completely. You get every login, every prompt, every line of code. No lock-in, no vendor dependency on me forever. If you outgrow Achieve, you walk with the whole system."],
  ["What if I'm not technical at all?", "Perfect, that's most of the people I work with. I handle the plumbing. You get a clean dashboard, a monthly summary in plain English, and a phone number for when you have questions."],
  ["How is this different from hiring someone to handle calls and follow-ups?", "A person costs $3,000 to $5,000+ per month, needs training, takes time off, and can only handle one thing at a time. Achieve automations run 24/7, reply in under 60 seconds to every lead simultaneously, and cost a fraction of that. You stay in the loop without being the bottleneck."],
  ["Do you work with businesses outside the home services industry?", "Yes. While home services businesses are a great fit, Achieve has built systems for creators, professional services, and any business that relies on inbound leads. If leads are slipping through the cracks, there's likely a system that fixes it."],
];

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section className="sec" id="faq" data-screen-label="FAQ" style={{paddingTop: 0}}>
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow"><span className="dot"></span>FAQ</span>
            <h2>Questions, <em>answered straight</em>.</h2>
          </div>
          <p>Couldn't find what you were looking for? Text me directly. The number is in the footer.</p>
        </div>
        <div className="faq">
          {FAQS.map(([q, a], i) => (
            <div key={i} className={"faq-item" + (open === i ? " open" : "")}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{q}</span>
                <span className="faq-toggle"><Icon.plus /></span>
              </button>
              <div className="faq-a"><p>{a}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ===== Contact =====
const FORMSPREE_ID = "xlgzenqe";

const INTENT_OPTIONS = [
  { value: "audit", label: "Not sure yet", sub: "Help me figure out what I need" },
  { value: "service", label: "I have something in mind", sub: "I want to ask about a specific service or package" },
];

function Contact() {
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState(null);
  const [intent, setIntent] = useState("audit");
  const [form, setForm] = useState({ name: "", email: "", phone: "", business: "", interest: "", message: "" });
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const onSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(null);
    try {
      const payload = { ...form, intent: intent === "audit" ? "Needs an audit" : "Inquiring about a service/package" };
      const res = await fetch(`https://formspree.io/f/${FORMSPREE_ID}`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        setError("Something went wrong. Please email Zane directly at zane.rw.robertson@gmail.com");
      }
    } catch {
      setError("Something went wrong. Please email Zane directly at zane.rw.robertson@gmail.com");
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="sec" id="contact" data-screen-label="Contact" style={{paddingTop: 0, paddingBottom: 40}}>
      <div className="wrap">
        <div className="contact-wrap">
          <div className="contact-text">
            <span className="eyebrow"><span className="dot"></span>Start Automating</span>
            <h2>Let's figure out <em>what fits</em>.</h2>
            <p>Whether you know exactly what you want or have no idea where to start, reach out and we'll take it from there. No pressure, no pitch deck.</p>
            <div className="contact-direct">
              <a href="mailto:zane.rw.robertson@gmail.com">
                <span className="icon"><Icon.mail /></span>
                <span><div className="lbl">Email</div><div className="val">zane.rw.robertson@gmail.com</div></span>
              </a>
              <a href="tel:+14166603723">
                <span className="icon"><Icon.phone /></span>
                <span><div className="lbl">Phone</div><div className="val">(416) 660-3723</div></span>
              </a>
              <a href="https://instagram.com/zanerobertsonn" target="_blank" rel="noreferrer">
                <span className="icon"><Icon.ig /></span>
                <span><div className="lbl">Instagram</div><div className="val">@zanerobertsonn</div></span>
              </a>
            </div>
          </div>
          <form className="form" onSubmit={onSubmit}>
            <div className="intent-toggle">
              {INTENT_OPTIONS.map(opt => (
                <button
                  key={opt.value}
                  type="button"
                  className={"intent-btn" + (intent === opt.value ? " active" : "")}
                  onClick={() => setIntent(opt.value)}
                >
                  <span className="intent-radio"></span>
                  <span>
                    <span className="intent-label">{opt.label}</span>
                    <span className="intent-sub">{opt.sub}</span>
                  </span>
                </button>
              ))}
            </div>
            <div className="form-row two">
              <div>
                <label>Your name</label>
                <input required value={form.name} onChange={set("name")} placeholder="Jane Smith" />
              </div>
              <div>
                <label>Business</label>
                <input value={form.business} onChange={set("business")} placeholder="Smith Plumbing Co." />
              </div>
            </div>
            <div className="form-row two">
              <div>
                <label>Email</label>
                <input required type="email" value={form.email} onChange={set("email")} placeholder="you@business.com" />
              </div>
              <div>
                <label>Phone</label>
                <input value={form.phone} onChange={set("phone")} placeholder="(555) 555-5555" />
              </div>
            </div>
            {intent === "service" && (
              <div className="form-row">
                <label>What are you interested in?</label>
                <select value={form.interest} onChange={set("interest")}>
                  <option value="">Select a service or package...</option>
                  <optgroup label="Packages">
                    <option>Starter package</option>
                    <option>Growth package</option>
                    <option>Full Stack package</option>
                  </optgroup>
                  <optgroup label="Individual services">
                    {SERVICES.map(s => <option key={s.id}>{s.label}</option>)}
                  </optgroup>
                </select>
              </div>
            )}
            <div className="form-row">
              <label>{intent === "audit" ? "Tell me about your business" : "Anything else we should know?"}</label>
              <textarea
                value={form.message}
                onChange={set("message")}
                placeholder={intent === "audit"
                  ? "What does your business do, how do leads come in, and where do things seem to fall apart?"
                  : "Any questions, context, or details that would help us get started."}
              ></textarea>
            </div>
            <div className={"form-success" + (submitted ? " show" : "")}>
              Got it. Zane will be in touch within 24 hours.
            </div>
            {error && <div className="form-success show" style={{color:"var(--warn)", borderColor:"var(--warn)", background:"rgba(255,122,58,0.08)"}}>{error}</div>}
            <div className="form-submit">
              <button className="btn btn-primary" type="submit" disabled={sending || submitted}>
                {sending ? "Sending..." : submitted ? "Sent!" : <span style={{display:"inline-flex",alignItems:"center",gap:10}}>Send it over <Icon.arrow /></span>}
              </button>
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

// ===== Pricing =====
const PACKAGES = [
  {
    id: "starter",
    name: "Starter",
    title: "Plug the biggest leaks, fast.",
    monthly: 250, setup: 1000,
    includes: [
      ["Conversion-built website", "Fast, SEO-ready, built around your funnel."],
      ["Missed-call textback", "Auto-text every missed call within 60s."],
      ["Review request automation", "More 5-stars on autopilot."],
    ],
    cta: "Start with Starter",
  },
  {
    id: "growth",
    name: "Growth",
    title: "Capture and convert on every channel.",
    monthly: 450, setup: 2000,
    featured: true,
    badge: "Most popular",
    includes: [
      ["Everything in Starter", "Website + textback + reviews."],
      ["Lead follow-up & CRM", "Unified inbox with smart reminders."],
      ["AI chat widget", "24/7 concierge trained on your business."],
    ],
    cta: "Pick Growth",
  },
  {
    id: "full",
    name: "Full Stack",
    title: "Run your whole front office on autopilot.",
    monthly: 700, setup: 3500,
    includes: [
      ["Everything in Growth", "All five core automations."],
      ["Email campaigns", "Win-back, nurture, and seasonal flows."],
      ["CRM pipeline", "Every lead tracked end-to-end."],
      ["AI receptionist", "Answers calls, qualifies, books."],
      ["Priority support", "Direct line, same-day response."],
    ],
    cta: "Go Full Stack",
  },
];

const ALACARTE = [
  { id: "site", name: "Conversion website", icon: <Icon.globe />, desc: "Fast, mobile-first, local-SEO ready.", monthly: 0, setup: 1250 },
  { id: "mct", name: "Missed-call textback", icon: <Icon.phone />, desc: "Auto-text missed callers in under 60s.", monthly: 150, setup: 500 },
  { id: "chat", name: "AI chat widget", icon: <Icon.bot />, desc: "24/7 lead capture on every page.", monthly: 200, setup: 500 },
  { id: "follow", name: "Lead follow-up & CRM", icon: <Icon.search />, desc: "Unified inbox, smart reminders.", monthly: 150, setup: 400 },
  { id: "review", name: "Review automation", icon: <Icon.star />, desc: "Auto-request + AI-drafted replies.", monthly: 100, setup: 300 },
  { id: "email", name: "Email campaigns", icon: <Icon.inbox />, desc: "Win-back and nurture flows.", monthly: 125, setup: 400 },
];

function Pricing() {
  const [selected, setSelected] = useState({});
  const [annual, setAnnual] = useState(false);
  const toggleRef = useRef(null);
  const monthlyBtnRef = useRef(null);
  const annualBtnRef = useRef(null);
  const [pillStyle, setPillStyle] = useState({ left: 4, width: 0 });

  useEffect(() => {
    const target = annual ? annualBtnRef.current : monthlyBtnRef.current;
    if (target && toggleRef.current) {
      const tRect = toggleRef.current.getBoundingClientRect();
      const bRect = target.getBoundingClientRect();
      setPillStyle({ left: bRect.left - tRect.left, width: bRect.width });
    }
  }, [annual]);

  const toggle = (id) => setSelected(s => ({ ...s, [id]: !s[id] }));
  const picks = ALACARTE.filter(a => selected[a.id]);
  const monthly = picks.reduce((s, a) => s + a.monthly, 0);
  const setup = picks.reduce((s, a) => s + a.setup, 0);
  const fmt = (n) => "$" + n.toLocaleString();

  const pkgSavings = useMemo(() => {
    const ids = new Set(picks.map(p => p.id));
    if (["site","mct","chat","follow","review","email"].every(x => ids.has(x))) {
      return { name: "Full Stack", saveSetup: setup - 3500, saveMo: monthly - 700 };
    }
    if (["site","mct","review","follow","chat"].every(x => ids.has(x))) {
      return { name: "Growth", saveSetup: setup - 2000, saveMo: monthly - 450 };
    }
    if (["site","mct","review"].every(x => ids.has(x))) {
      return { name: "Starter", saveSetup: setup - 1000, saveMo: monthly - 250 };
    }
    return null;
  }, [picks, setup, monthly]);

  const displayMonthly = (m) => annual ? Math.round(m * 0.85) : m;

  return (
    <section className="pricing-section" id="pricing" data-screen-label="Pricing">
      <div className="wrap">
        <div className="pricing-hero">
          <span className="eyebrow"><span className="dot"></span>Pricing</span>
          <h2>Pick the plan that <em>fits your funnel</em>.</h2>
          <p>Pay for what you need, when you need it. Every package is negotiable. If your scope is smaller, the number is smaller. We'd rather find the right fit than lose the project.</p>
          <div className="billing-toggle" ref={toggleRef}>
            <span className="pill" style={{ left: pillStyle.left, width: pillStyle.width }}></span>
            <button ref={monthlyBtnRef} className={!annual ? "active" : ""} onClick={() => setAnnual(false)}>Pay monthly</button>
            <button ref={annualBtnRef} className={annual ? "active" : ""} onClick={() => setAnnual(true)}>Pay annually <span className="billing-save">SAVE 15%</span></button>
          </div>
        </div>

        <div className="packages">
          {PACKAGES.map((p, i) => {
            const m = displayMonthly(p.monthly);
            return (
              <div key={p.id} className={"pkg" + (p.featured ? " featured" : "")}>
                {p.badge && <span className="pkg-badge">{p.badge}</span>}
                <div className="pkg-eyebrow">
                  <span className="pkg-mark">{i === 0 ? <Icon.spark /> : i === 1 ? <Icon.rocket /> : <Icon.star />}</span>
                  <span className="pkg-name">{p.name}</span>
                </div>
                <div className="pkg-tagline">{p.title}</div>
                <div className="pkg-price-block">
                  <div className="pkg-price-from">One-time setup fee</div>
                  <div className="pkg-price">
                    <span className="currency">$</span>
                    <span className="num">{p.setup.toLocaleString()}</span>
                  </div>
                  <div className="pkg-then-row">
                    <span className="pkg-then-label">then</span>
                    <span className="pkg-then-price">{fmt(m)}<span className="pkg-then-mo">/ mo</span></span>
                  </div>
                  <div className="pkg-billed">
                    {annual ? <>monthly billed at <b>{fmt(m * 12)}/yr</b> · <span className="strike">{fmt(p.monthly * 12)}/yr</span></> : <>or <b>{fmt(Math.round(p.monthly * 0.85))}/mo</b> billed annually</>}
                  </div>
                </div>
                <a className="pkg-cta" href="#contact">{p.cta}</a>
                <div className="pkg-includes">What's included</div>
                <ul className="pkg-features">
                  {p.includes.map(([t, d]) => (
                    <li key={t}>
                      <span className="pkg-check"><Icon.check /></span>
                      <span><b>{t}.</b> {d}</span>
                    </li>
                  ))}
                </ul>
                <div className="pkg-details"><a href="#contact">More details</a></div>
              </div>
            );
          })}
        </div>

        <div className="builder-head">
          <h3>Or build your own, <em>a la carte</em>.</h3>
          <p>Pick exactly what you need and see the total update live. If your selection matches a package, you'll see the bundle savings appear automatically.</p>
        </div>

        <div className="builder">
          <div className="builder-list">
            {ALACARTE.map(a => (
              <button
                key={a.id}
                className={"builder-item" + (selected[a.id] ? " selected" : "")}
                onClick={() => toggle(a.id)}
                type="button"
              >
                <span className="builder-checkbox"><Icon.check /></span>
                <span className="builder-item-info">
                  <span className="builder-item-name">{a.icon}{a.name}</span>
                  <span className="builder-item-desc">{a.desc}</span>
                </span>
                <span className="builder-item-price">
                  {a.monthly > 0 ? <>${a.monthly}<span className="mo">/ mo ongoing</span></> : <><span className="mo">No monthly fee</span></>}
                </span>
                <span className="builder-item-setup">Setup fee<b>${a.setup.toLocaleString()}</b></span>
              </button>
            ))}
          </div>

          <aside className="builder-summary">
            <div className="builder-summary-head">
              <span>Your bundle</span>
              <span className="builder-count">{picks.length}</span>
            </div>

            {picks.length === 0 ? (
              <div className="builder-empty">Select services to build your quote.</div>
            ) : (
              <div className="builder-selected">
                {picks.map(p => (
                  <div key={p.id} className="builder-selected-row">
                    <span className="builder-selected-name">{p.name}</span>
                    <span className="builder-selected-price">
                      {p.monthly > 0 ? `${fmt(p.monthly)}/mo` : fmt(p.setup)}
                    </span>
                  </div>
                ))}
              </div>
            )}

            <div className="builder-totals">
              <div className="builder-total-row">
                <span className="lbl">Setup (one-time)</span>
                <span className="val">{fmt(setup)}</span>
              </div>
              <div className="builder-plus-row">+ then monthly</div>
              <div className="builder-total-row big">
                <span className="lbl">Monthly ongoing</span>
                <span className="val">{fmt(monthly)}<span style={{fontSize:14, color:"var(--fg-3)", fontFamily:"var(--mono)", letterSpacing:"0.06em", marginLeft:6}}>/mo</span></span>
              </div>
              {pkgSavings && (pkgSavings.saveSetup > 0 || pkgSavings.saveMo > 0) && (
                <div className="builder-savings">
                  <span>Bundle as <b>{pkgSavings.name}</b> and save</span>
                  <span className="save-amt">{fmt(pkgSavings.saveSetup)} + {fmt(pkgSavings.saveMo)}/mo</span>
                </div>
              )}
              <a
                className={"builder-cta" + (picks.length === 0 ? " disabled" : "")}
                href="#contact"
              >
                {picks.length === 0 ? "Pick a service to start" : <>Get this quote <Icon.arrow /></>}
              </a>
            </div>
          </aside>
        </div>

        <div className="price-foot">
          <div className="price-foot-text">
            <h4>Pricing is a <em>conversation</em>, not a contract.</h4>
            <p>Every business has different scope, existing tools, and budget. Tell me what you're working with and we'll land on a number that works for both of us.</p>
          </div>
          <a className="btn btn-primary" href="#contact">Discuss pricing <Icon.arrow /></a>
        </div>
      </div>
    </section>
  );
}

// ===== Footer =====
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand footer-col">
            <a href="#top" className="logo"><span className="logo-mark">A</span><span>achieve<em>.</em></span></a>
            <p>Automation studio for businesses that are tired of losing leads to silence.</p>
          </div>
          <div className="footer-col">
            <h5>Build</h5>
            <ul>
              <li><a href="#services">Services</a></li>
              <li><a href="#how">How it works</a></li>
              <li><a href="#demo">Live demo</a></li>
              <li><a href="#roi">ROI calculator</a></li>
              <li><a href="#pricing">Pricing</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <ul>
              <li><a href="#about">About Zane</a></li>
              <li><a href="#faq">FAQ</a></li>
              <li><a href="#contact">Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Direct</h5>
            <ul>
              <li><a href="mailto:zane.rw.robertson@gmail.com">zane.rw.robertson@gmail.com</a></li>
              <li><a href="tel:+14166603723">(416) 660-3723</a></li>
              <li><a href="https://instagram.com/zanerobertsonn" target="_blank" rel="noreferrer">@zanerobertsonn</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2026 Achieve · Built by Zane Robertson</span>
          <span>Toronto · ON · Canada</span>
        </div>
      </div>
    </footer>
  );
}

function App() {
  return (
    <>
      <Nav />
      <Hero />
      <Services />
      <HowItWorks />
      <Chatbot />
      <ROI />
      <Pricing />
      <About />
      <FAQ />
      <Contact />
      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
