/* global React */
const { useState: useStateS, useEffect: useEffectS } = React;

/* ──────────────────────────────────────────
   HERO + remaining marketing sections
   ────────────────────────────────────────── */

function Hero() {
  return (
    <header className="hero" id="top">
      <div className="hero-meta">
        <div>
          <span className="blink">●</span> &nbsp;Cayres&nbsp;Labs — AI&nbsp;Automation Studio
          &nbsp;/&nbsp; Est.&nbsp;2024 &nbsp;/&nbsp; San Diego, CA
        </div>
        <div className="right">
          a study in the gap between &nbsp;<span style={{ color: "var(--ink)" }}>website</span>
          &nbsp;and <span style={{ color: "var(--ink)" }}>revenue.</span>
        </div>
      </div>

      <h1 className="hero-display">
        You know your business is{" "}
        <span className="strike">leaking</span> <span className="it">leads.</span>
        <br />
        You just don't know <span className="it">where.</span>
      </h1>

      <div className="hero-bottom">
        <p className="hero-lede">
          We design + ship AI automation systems for businesses that know
          something is broken — but can't point to it on a whiteboard.
          <br />
          <br />
          Start by telling us what you do. The page below will tell you what to
          automate.
        </p>

        <div className="hero-stat">
          <div className="num">
            60<span style={{ fontSize: "0.5em", color: "var(--ink-mute)" }}>sec</span>
          </div>
          <div className="label">Avg response time for the systems we ship — to every form, call, and lead.</div>
        </div>

        <div className="hero-stat">
          <div className="num">
            2<span style={{ fontSize: "0.5em", color: "var(--ink-mute)" }}>wk</span>
          </div>
          <div className="label">From kickoff to "your phone stops ringing for the wrong reasons."</div>
        </div>
      </div>
    </header>
  );
}

/* ───── DISCOVERY SECTION WRAPPER ───── */

function DiscoverySection() {
  return (
    <section className="section dark" id="figure-out">
      <Reveal>
        <SectionHead
          num="01 — Discovery Engine"
          title={
            <>
              The hardest part isn't <span className="it">building</span> it.
              <br />
              It's <span className="it">knowing</span> what to build.
            </>
          }
          aside={
            <>
              Live · powered by Cayres AI
              <br />
              Free · no signup
            </>
          }
        />
      </Reveal>
      <Reveal delay={120}>
        <Discovery />
      </Reveal>
    </section>
  );
}

/* ───── LEAK MAP SECTION ───── */

function LeaksSection() {
  return (
    <section className="section" id="leaks">
      <Reveal>
        <SectionHead
          num="02 — Where revenue goes to die"
          title={
            <>
              Five places your business <span className="it">leaks</span> — measured.
            </>
          }
          aside={
            <>
              Hover any leak<br />
              to see the cost
            </>
          }
        />
      </Reveal>
      <Reveal delay={100}>
        <LeakMap />
      </Reveal>
    </section>
  );
}

/* ───── INDUSTRIES ───── */

const INDUSTRY_LIST = [
  { name: "Plumbing", lead: "Dispatching" },
  { name: "HVAC", lead: "Quote follow-up" },
  { name: "Dental", lead: "Recall + reactivation" },
  { name: "Med Spas", lead: "Booking + intake" },
  { name: "Law Firms", lead: "Intake qualification" },
  { name: "Restaurants", lead: "Reservations + reviews" },
  { name: "Electricians", lead: "After-hours capture" },
  { name: "Garage Door", lead: "Emergency routing" },
  { name: "Cleaning", lead: "Recurring scheduling" },
  { name: "Chiropractic", lead: "No-show reduction" },
  { name: "Pest Control", lead: "Renewals" },
  { name: "Pool Service", lead: "Seasonal campaigns" },
  { name: "Landscaping", lead: "Estimate follow-up" },
  { name: "Insurance", lead: "Policy renewals" },
  { name: "Accounting", lead: "Onboarding flows" },
  { name: "Salons", lead: "Rebooking" },
];

function IndustriesSection() {
  // Build a marquee string
  const marqueeItems = [
    "Plumbing",
    "HVAC",
    <em key="d" className="it">Dental</em>,
    "Med Spas",
    "Law Firms",
    <em key="r" className="it">Restaurants</em>,
    "Electricians",
    "Cleaning",
    <em key="c" className="it">Chiropractic</em>,
    "Pest Control",
    "Pool Service",
    <em key="l" className="it">Landscaping</em>,
    "Insurance",
    "Accounting",
    <em key="s" className="it">Salons</em>,
    "Tutoring",
  ];

  const focusDiscovery = (industry) => {
    const ta = document.querySelector(".disco-textarea");
    if (!ta) return;
    const map = {
      Plumbing: "I run a plumbing business in San Diego — leads come from Google and Yelp, but we miss calls during jobs and follow-up is whoever picks up.",
      HVAC: "We're an HVAC company with 12 techs. Leads come from Google ads, our quote follow-up is inconsistent.",
      Dental: "I own a 4-chair dental practice. We have a front desk that handles calls but misses a lot of after-hours inquiries.",
      "Med Spas": "I run a med spa — booking is through the phone and Instagram DMs, and we lose a lot of inquiries that never convert.",
      "Law Firms": "Boutique law firm, 6 attorneys, intake forms come in and sometimes sit for a day before we respond.",
      Restaurants: "I run a restaurant — reservations come from a few sources and we never ask for reviews systematically.",
      Electricians: "We're an electrical contractor, leads come in 24/7 but we only answer during business hours.",
      "Garage Door": "Garage door repair company — most leads are emergencies and the first to call back wins the job.",
      Cleaning: "Residential cleaning service, we do recurring + one-time and follow-up on quotes is patchy.",
      Chiropractic: "Chiropractic practice, no-shows are killing us and we never reactivate old patients.",
      "Pest Control": "Pest control company, recurring contracts but renewals and seasonal upsells are manual.",
      "Pool Service": "Pool service route, leads spike in summer and we can't keep up with the inquiries.",
      Landscaping: "Landscaping business, lots of estimate requests but follow-through is inconsistent.",
      Insurance: "Independent insurance agency, policy renewal reminders are a mess and we lose retention.",
      Accounting: "Boutique accounting firm, onboarding new clients takes forever and intake is all manual.",
      Salons: "Salon with 8 chairs, rebooking happens at checkout but a third of clients leave without a next visit booked.",
    };
    const txt = map[industry] || `I run a ${industry.toLowerCase()} business. What should I automate?`;
    ta.value = txt;
    ta.dispatchEvent(new Event("input", { bubbles: true }));
    // Trigger React onChange
    const nativeSetter = Object.getOwnPropertyDescriptor(
      window.HTMLTextAreaElement.prototype,
      "value"
    ).set;
    nativeSetter.call(ta, txt);
    ta.dispatchEvent(new Event("input", { bubbles: true }));
    document.getElementById("figure-out")?.scrollIntoView?.({ behavior: "smooth", block: "start" });
    setTimeout(() => ta.focus(), 600);
  };

  return (
    <section className="section" id="industries">
      <Reveal>
        <SectionHead
          num="03 — Built for"
          title={
            <>
              We've built for sixteen kinds of business.
              <br />
              <span className="it">Yours probably leaks the same way.</span>
            </>
          }
          aside={
            <>
              Tap an industry to<br />
              auto-fill the discovery engine
            </>
          }
        />
      </Reveal>

      <Reveal delay={100}>
        <div className="marquee-wrap" aria-hidden="true">
          <div className="marquee-track">
            {[...marqueeItems, ...marqueeItems, ...marqueeItems].map((it, i) => (
              <span key={i}>{it} <span style={{ opacity: 0.25 }}>·</span></span>
            ))}
          </div>
        </div>
      </Reveal>

      <Reveal delay={140}>
        <div className="industries-grid">
          {INDUSTRY_LIST.map((ind, i) => (
            <button
              key={i}
              className="ind-cell"
              onClick={() => focusDiscovery(ind.name)}
              style={{
                borderRight: (i + 1) % 4 === 0 ? "0" : undefined,
              }}
            >
              <div className="name">{ind.name}</div>
              <div className="lead">→ {ind.lead}</div>
            </button>
          ))}
        </div>
      </Reveal>
    </section>
  );
}

/* ───── PROCESS ───── */

const PROCESS = [
  {
    n: "01",
    t: "Find the leaks",
    b: "We sit with you for 90 minutes, walk through your funnel, and map every place a lead can fall through. You leave with a one-page diagram of your business.",
    m: "Week 0 · Discovery",
  },
  {
    n: "02",
    t: "Rebuild the front door",
    b: "If the website needs work, we redesign and ship it. Built for conversion first, beauty second — though we don't ship ugly.",
    m: "Week 1 · Site",
  },
  {
    n: "03",
    t: "Wire the systems",
    b: "Missed-call text-back, instant form response, multi-touch follow-up, review automation, intake. We build, you watch the lights turn on.",
    m: "Week 2 · Automation",
  },
  {
    n: "04",
    t: "Hand over the keys",
    b: "You own the website, the automations, the data. We stay on retainer or you fly solo — your call. No hostage contracts.",
    m: "Week 3 · Live",
  },
];

function ProcessSection() {
  return (
    <section className="section" id="process">
      <Reveal>
        <SectionHead
          num="04 — Process"
          title={
            <>
              Three weeks. <span className="it">Most of it</span> happens<br />
              while you sleep.
            </>
          }
          aside={
            <>
              From kickoff to live<br />
              ~21 days typical
            </>
          }
        />
      </Reveal>

      <div className="process">
        {PROCESS.map((p, i) => (
          <Reveal key={i} delay={i * 80} className="proc-step reveal">
            <div className="proc-num">{p.n}</div>
            <div className="proc-title">{p.t}</div>
            <div className="proc-body">{p.b}</div>
            <div className="proc-meta">{p.m}</div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* ───── WHY ───── */

const WHY = [
  {
    n: "01",
    h: <>One studio. <span className="it">One throat to choke.</span></>,
    b: "Most agencies stop at the website. The next agency takes your CRM. The third one runs your ads. We do the whole stack — and we're accountable for the whole result.",
  },
  {
    n: "02",
    h: <>Built around how your <span className="it">customers</span> actually buy.</>,
    b: "Not built around a template. We start with your funnel, not a Figma file. Every system is reverse-engineered from the moments your prospects actually choose you — or don't.",
  },
  {
    n: "03",
    h: <>You <span className="it">own</span> everything.</>,
    b: "The website lives on your domain. The automations run on tools you have logins for. The data is yours. If you fire us tomorrow, you take everything with you.",
  },
  {
    n: "04",
    h: <>We measure <span className="it">booked jobs.</span> Nothing else.</>,
    b: "Not impressions, not 'engagement', not Instagram followers. The only metric we send you is the count of leads captured and jobs booked. If those don't move, neither do we.",
  },
];

function WhySection() {
  return (
    <section className="section" id="why">
      <Reveal>
        <SectionHead
          num="05 — Why us"
          title={
            <>
              Four reasons we're worth<br />
              a <span className="it">strategy call.</span>
            </>
          }
        />
      </Reveal>

      <div className="why-list">
        {WHY.map((w, i) => (
          <Reveal key={i} delay={i * 60} className="why-row reveal">
            <div className="n">{w.n}</div>
            <div className="h">{w.h}</div>
            <div className="b">{w.b}</div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* ───── CONTACT ───── */

function ContactSection() {
  const [data, setData] = useStateS({ name: "", email: "", business: "", note: "" });
  const [sent, setSent] = useStateS(false);

  const submit = (e) => {
    e.preventDefault();
    if (!data.name || !data.email || !data.business) return;
    // In a real deploy, post to a form endpoint. Here, just persist locally.
    try {
      localStorage.setItem("cayres_contact_draft", JSON.stringify(data));
    } catch {}
    setSent(true);
  };

  return (
    <section className="section" id="contact">
      <div className="contact">
        <Reveal className="contact-left reveal">
          <h2 className="display">
            Let's figure out<br />
            what you're <span className="it">leaving</span><br />
            <span className="it">on the table.</span>
          </h2>

          <p style={{ maxWidth: "36ch", color: "var(--ink-2)", fontSize: "16px", lineHeight: 1.55 }}>
            Tell us what your business does, what's been frustrating, and what
            you'd love to stop doing manually. We'll come back within a day with
            either a free audit, a proposal, or "this isn't a fit" — whichever
            is honest.
          </p>

          <div className="meta">
            <div>
              <div className="l">Email</div>
              <a href="mailto:contact@cayreslabs.com">contact@cayreslabs.com</a>
            </div>
            <div>
              <div className="l">Phone</div>
              <a href="tel:+14244267477">(424) 426-7477</a>
            </div>
            <div>
              <div className="l">Office</div>
              <span>San Diego, California</span>
            </div>
            <div>
              <div className="l">Response time</div>
              <span>Under 24 hours, weekdays</span>
            </div>
          </div>
        </Reveal>

        <Reveal delay={120} className="reveal">
          <form className="contact-form" onSubmit={submit}>
            {sent ? (
              <div className="success">
                Got it — we'll be in touch within a day.
                <span className="small">
                  In the meantime, you can email <a href="mailto:contact@cayreslabs.com" style={{ color: "var(--signal)" }}>contact@cayreslabs.com</a> directly or reply to the confirmation we just sent.
                </span>
              </div>
            ) : (
              <>
                <div className="field">
                  <div className="label">01 / Your name</div>
                  <input
                    type="text"
                    placeholder="—"
                    value={data.name}
                    onChange={(e) => setData({ ...data, name: e.target.value })}
                    required
                  />
                </div>
                <div className="field">
                  <div className="label">02 / Email</div>
                  <input
                    type="email"
                    placeholder="you@business.com"
                    value={data.email}
                    onChange={(e) => setData({ ...data, email: e.target.value })}
                    required
                  />
                </div>
                <div className="field">
                  <div className="label">03 / What does your business do?</div>
                  <input
                    type="text"
                    placeholder="e.g. residential plumbing, San Diego, 2 trucks"
                    value={data.business}
                    onChange={(e) => setData({ ...data, business: e.target.value })}
                    required
                  />
                </div>
                <div className="field">
                  <div className="label">04 / What hurts the most right now?</div>
                  <textarea
                    placeholder="Tell us anything — missed calls, slow follow-up, no reviews, etc."
                    rows={3}
                    value={data.note}
                    onChange={(e) => setData({ ...data, note: e.target.value })}
                  />
                </div>

                <button type="submit" className="submit">
                  Send to Cayres Labs <span aria-hidden="true">→</span>
                </button>
              </>
            )}
          </form>
        </Reveal>
      </div>
    </section>
  );
}

/* ───── FOOTER ───── */

function Footer() {
  return (
    <footer className="footer">
      <div className="brand">
        Cayres<span className="it">Labs.</span>
      </div>
      <div className="footer-col">
        <h4>Studio</h4>
        <a href="#figure-out">Discovery engine</a>
        <a href="#leaks">Leak map</a>
        <a href="#process">Process</a>
        <a href="#why">Why us</a>
      </div>
      <div className="footer-col">
        <h4>Contact</h4>
        <a href="mailto:contact@cayreslabs.com">contact@cayreslabs.com</a>
        <a href="tel:+14244267477">(424) 426-7477</a>
        <a href="#contact">Start a project →</a>
      </div>
      <div className="footer-col">
        <h4>Elsewhere</h4>
        <a href="https://instagram.com/cayreslabs" target="_blank" rel="noreferrer">Instagram ↗</a>
        <a href="https://linkedin.com/company/cayreslabs" target="_blank" rel="noreferrer">LinkedIn ↗</a>
        <a href="https://facebook.com/cayreslabs" target="_blank" rel="noreferrer">Facebook ↗</a>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Cayres Labs LLC. San Diego, CA.</span>
        <span>Designed and built by Cayres Labs.</span>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Hero,
  DiscoverySection,
  LeaksSection,
  IndustriesSection,
  ProcessSection,
  WhySection,
  ContactSection,
  Footer,
});
