/* ============================================================
   sections.jsx — Services (stacking cards), Featured case (HVAC)
   ============================================================ */

const { useEffect: useEffectSE, useRef: useRefSE, useState: useStateSE } = React;

/* ---------------------------------------------------------------
   Services — stacking sticky cards. Each card pins, the next
   slides up over it. Built so depth and scale read naturally.
   --------------------------------------------------------------- */

const SERVICES_DATA = [
  {
    label: "01 — Custom AI automations",
    h: <>AI automations that <em>do the work for you</em>.</>,
    p: "No matter how complex the task — agents that plan, decompose, and execute end-to-end. Built to your operation, with a custom interface to control them.",
    bullets: [
      "Plan → execute → deliver, with logs you can read",
      "Wired into the tools your team already uses",
      "A custom panel so you stay in the driver's seat",
    ],
    Scene: () => <AIScene />,
  },
  {
    label: "02 — Beautifully designed sites",
    h: <>Custom sites that <em>look like the brand</em> they sell.</>,
    p: "Landing pages, e-commerce, photo portfolios, full product sites. Each one custom — designed to its own voice, not poured into a template.",
    bullets: [
      "Designed from a blank page, not a theme",
      "Fast, responsive, accessible by default",
      "Editable content blocks for your team",
    ],
    Scene: () => <SitesScene />,
  },
  {
    label: "03 — Get discovered",
    h: <>Show up where buyers <em>are looking</em>.</>,
    p: "Search, AI overviews, Meta ads, social mentions. A discovery engine that gets your brand cited, recommended, and clicked.",
    bullets: [
      "SEO + AEO so models cite you, not competitors",
      "Meta ad systems with creative that actually converts",
      "Earned mentions and review momentum",
    ],
    Scene: () => <DiscoScene />,
  },
];

function Services() {
  const cardsRef = useRefSE([]);
  const [shrinkSet, setShrinkSet] = useStateSE(new Set());

  useEffectSE(() => {
    const onScroll = () => {
      const next = new Set();
      cardsRef.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        // when next card has scrolled meaningfully over us, mark shrink
        const nextEl = cardsRef.current[i + 1];
        if (nextEl) {
          const nr = nextEl.getBoundingClientRect();
          const stickyTop = r.top; // current pinned position
          // when next card top is within ~70% of viewport above current card
          if (nr.top < window.innerHeight * 0.55) {
            next.add(i);
          }
        }
      });
      setShrinkSet(next);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section className="services" id="services">
      <div className="shell">
        <div className="section-head">
          <div className="num">Services</div>
          <h2>Three things we do — <em>well</em>.</h2>
        </div>
      </div>

      <div className="shell">
        <div className="svc-stack">
          {SERVICES_DATA.map((s, i) => (
            <article
              key={i}
              ref={(el) => (cardsRef.current[i] = el)}
              className={`svc-card ${shrinkSet.has(i) ? "shrink" : ""}`}
              style={{ top: `calc(72px + ${i * 18}px)` }}
            >
              <div className="copy">
                <div className="top">
                  <span className="label">{s.label}</span>
                  <span>0{i + 1} / 03</span>
                </div>
                <div>
                  <h3 className="serif">{s.h}</h3>
                  <p style={{ marginTop: 18 }}>{s.p}</p>
                </div>
                <ul>
                  {s.bullets.map((b, j) => <li key={j}>{b}</li>)}
                </ul>
              </div>
              <div className="preview">
                <s.Scene />
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------
   Featured case — HVAC reporting software, accurate-feeling
   --------------------------------------------------------------- */

function HVACPreview() {
  // The accurate-feeling reporting dashboard.
  // Generic name (not Elevate). Uses real-looking numbers from the screenshot.
  return (
    <div className="hvac">
      <div className="side">
        <div className="brand-h">
          <div className="nm">CREWBOARD</div>
          <div className="sub">Operations · v2.4</div>
        </div>
        <div className="group">Today</div>
        <div className="item active"><span className="ic">▦</span>Dashboard</div>
        <div className="item"><span className="ic">↗</span>Revenue</div>
        <div className="item"><span className="ic">$</span>Sales</div>
        <div className="group">Crew</div>
        <div className="item"><span className="ic">⚒</span>Service techs</div>
        <div className="item"><span className="ic">⚒</span>Installers</div>
        <div className="group">Pipeline</div>
        <div className="item"><span className="ic">◎</span>Marketing</div>
        <div className="item"><span className="ic">◉</span>Prospecting</div>
        <div className="item"><span className="ic">$</span>A/R</div>
        <div className="item"><span className="ic">!</span>Revenue leaks</div>
        <div className="item"><span className="ic">★</span>Memberships</div>
        <div className="group">System</div>
        <div className="item"><span className="ic">⚙</span>Business logic</div>
        <div className="item"><span className="ic">✉</span>Conversations</div>
      </div>

      <div className="main">
        <div className="topbar">
          <span className="ttl">Dashboard</span>
          <span className="pill">YTD <b>$895,048</b></span>
          <span className="pill">Lifetime <b>$5,947,594</b></span>
          <span className="pill">This month ▾</span>
          <span className="right">
            <span>April 2024</span>
            <span className="acc">M</span>
          </span>
        </div>

        <div className="content">
          <div className="toprow">
            <div className="kpibox">
              <div className="lbl">Month revenue</div>
              <div className="val">$225,919</div>
              <div className="dlt"><span className="up">↑ 18.2%</span> vs Mar</div>
              <div className="spark">
                <svg viewBox="0 0 100 30" preserveAspectRatio="none">
                  <polyline points="0,22 12,18 24,20 36,12 48,16 60,8 72,14 84,4 100,10"
                    fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" />
                </svg>
              </div>
            </div>
            <div className="kpibox">
              <div className="lbl">Jobs completed</div>
              <div className="val">81</div>
              <div className="dlt"><span className="up">↑ 12</span> · 54 service · 27 install</div>
              <div className="spark">
                <svg viewBox="0 0 100 30" preserveAspectRatio="none">
                  {[3,5,4,6,7,8,7,9,10,8,11,12].map((h, i, a) => (
                    <rect key={i} x={i * (100/a.length) + 1} y={30 - h*2.4} width={100/a.length - 2} height={h*2.4} fill="var(--accent)" opacity="0.7" />
                  ))}
                </svg>
              </div>
            </div>
            <div className="kpibox">
              <div className="lbl">A/R outstanding</div>
              <div className="val">$50,937</div>
              <div className="dlt"><span className="down">↓ 8.4%</span> vs Mar</div>
              <div className="spark">
                <svg viewBox="0 0 100 30" preserveAspectRatio="none">
                  <polyline points="0,12 14,14 28,16 42,15 56,18 70,20 84,22 100,24"
                    fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" />
                </svg>
              </div>
            </div>
            <div className="kpibox">
              <div className="lbl">Closing ratio · Michael</div>
              <div className="val">25.0%</div>
              <div className="dlt">8 closed of 32 open</div>
              <div className="spark">
                <svg viewBox="0 0 100 30">
                  <rect x="0" y="14" width="25" height="6" rx="2" fill="var(--accent)" />
                  <rect x="0" y="14" width="100" height="6" rx="2" fill="var(--accent)" opacity="0.18" />
                </svg>
              </div>
            </div>
          </div>

          <div className="twocol">
            <div className="panel-h">
              <div className="head">
                <span className="ttl">Revenue · daily</span>
                <span className="tabs"><span>7d</span><span>30d</span><span className="on">MTD</span><span>YTD</span></span>
              </div>
              <div className="chart-h">
                <svg viewBox="0 0 600 220" preserveAspectRatio="none">
                  <defs>
                    <linearGradient id="cgrad" x1="0" x2="0" y1="0" y2="1">
                      <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.35" />
                      <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
                    </linearGradient>
                  </defs>
                  {/* gridlines */}
                  {[40, 90, 140, 190].map((y) => (
                    <line key={y} x1="0" x2="600" y1={y} y2={y} stroke="currentColor" opacity="0.06" />
                  ))}
                  {/* spiky line — rough match to the screenshot */}
                  <path
                    d="M 0,180 L 20,160 L 40,170 L 60,140 L 80,150 L 100,120 L 120,135 L 140,90 L 160,140 L 180,80 L 200,150 L 220,40 L 240,160 L 260,110 L 280,170 L 300,90 L 320,140 L 340,130 L 360,160 L 380,100 L 400,170 L 420,110 L 440,150 L 460,80 L 480,160 L 500,120 L 520,170 L 540,100 L 560,150 L 580,130 L 600,170 L 600,220 L 0,220 Z"
                    fill="url(#cgrad)"
                  />
                  <path
                    d="M 0,180 L 20,160 L 40,170 L 60,140 L 80,150 L 100,120 L 120,135 L 140,90 L 160,140 L 180,80 L 200,150 L 220,40 L 240,160 L 260,110 L 280,170 L 300,90 L 320,140 L 340,130 L 360,160 L 380,100 L 400,170 L 420,110 L 440,150 L 460,80 L 480,160 L 500,120 L 520,170 L 540,100 L 560,150 L 580,130 L 600,170"
                    fill="none" stroke="var(--accent)" strokeWidth="1.6" strokeLinejoin="round"
                  />
                  {/* peak marker */}
                  <circle cx="220" cy="40" r="4" fill="var(--accent)" />
                  <text x="232" y="38" fill="var(--ink)" fontSize="11" fontFamily="var(--mono)">$28,447 · Apr 11</text>
                </svg>
              </div>
            </div>

            <div className="panel-h">
              <div className="head">
                <span className="ttl">Revenue leaks</span>
                <span className="tabs"><span className="on">Open</span><span>Resolved</span></span>
              </div>
              <div className="leakslist">
                <div className="row">
                  <span className="nm">Estimate sent · no follow-up (5d)</span>
                  <span className="src">12 jobs</span>
                  <span className="v">$28,500</span>
                </div>
                <div className="row">
                  <span className="nm">Membership lapsed · auto-bill failed</span>
                  <span className="src">7 customers</span>
                  <span className="v">$1,260</span>
                </div>
                <div className="row">
                  <span className="nm">Diagnostic done · no sold work</span>
                  <span className="src">9 jobs</span>
                  <span className="v">$14,400</span>
                </div>
                <div className="row">
                  <span className="nm">Open invoice · 60+ days</span>
                  <span className="src">4 customers</span>
                  <span className="v">$3,600</span>
                </div>
                <div className="row">
                  <span className="nm">Tech upsell flagged · not offered</span>
                  <span className="src">22 visits</span>
                  <span className="v">$3,300</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FeaturedCase() {
  return (
    <section className="featured" id="work">
      <div className="shell">
        <div className="stage">
          <div className="case-meta">
            <span className="left">Crewboard · 2026 · ongoing</span>
            <span className="right">
              <b>Custom reporting software</b> · revenue leak detection · A/R recovery · marketing attribution
            </span>
          </div>

          <h3 className="serif">
            Built around how <em>they</em> think about the work — their crews,
            their territories, their commission rules. Not a template.
          </h3>

          <div className="frame">
            <HVACPreview />
          </div>

          <div className="impact">
            <div className="stat">
              <div className="v serif">7 days</div>
              <div className="l">To working software</div>
              <div className="d">First usable build delivered in week one. Iterated weekly thereafter.</div>
            </div>
            <div className="stat">
              <div className="v serif">Custom</div>
              <div className="l">Business-logic reporting</div>
              <div className="d">Their dispatch, their territories, their commission rules — surfaced exactly how they think about the work.</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Services, FeaturedCase });
