/* OpSpot — Hero (ROI), Leak Ledger (dark console), ROI Math receipt. */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- small inline icons ---------- */
function Ico({ d, fill = false, size = 24 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill={fill ? 'currentColor' : 'none'}
         stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      {d}
    </svg>
  );
}
const ICONS = {
  phone: <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-6 19.79 19.79 0 0 1-3.07-8.67A2 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" />,
  search: <><circle cx="11" cy="11" r="7" /><path d="m21 21-4.35-4.35" /></>,
  pen: <path d="M12 19l7-7 3 3-7 7-3-3zM18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5zM2 2l7.586 7.586M11 11a2 2 0 1 0 4 0 2 2 0 0 0-4 0z" />,
  calendar: <><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></>,
  receipt: <path d="M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1zM8 8h8M8 12h8M8 16h5" />,
  check: <path d="M20 6 9 17l-5-5" />,
  send: <path d="m22 2-7 20-4-9-9-4 20-7z" />,
  chat: <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />,
  x: <path d="M18 6 6 18M6 6l12 12" />,
  bolt: <path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z" />,
  shield: <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />,
  dollar: <path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />,
  pin: <React.Fragment><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></React.Fragment>,
};
function crewIcon(id) {
  const map = { courier: ICONS.chat, recon: ICONS.search, comms: ICONS.send, redpen: ICONS.pen, marshal: ICONS.calendar, dealdesk: ICONS.dollar, teller: ICONS.dollar, orbit: ICONS.bolt };
  return map[id] || ICONS.bolt;
}

/* ---------- live ops console (mid-page) ---------- */
const TRANSCRIPT = [
  "Hi, thanks for calling Ridge Plumbing — this is the front desk.",
  "I can get you booked for a leak inspection. What’s the address?",
  "Got it — Tuesday at 9:30 with Marco. Sending your confirmation now.",
];
function ConsoleStage() {
  const [feed, setFeed] = useState(FEED.slice(0, 5));
  const [recovered, setRecovered] = useState(8420);
  const [callIdx, setCallIdx] = useState(0);
  const [typed, setTyped] = useState('');
  const idx = useRef(4);

  useEffect(() => {
    const id = setInterval(() => {
      idx.current = (idx.current + 1) % FEED.length;
      const next = FEED[idx.current];
      setFeed(prev => [next, ...prev.slice(0, 4)]);
      if (next.recovered) setRecovered(r => r + next.recovered);
    }, 3200);
    return () => clearInterval(id);
  }, []);

  useEffect(() => {
    const line = TRANSCRIPT[callIdx];
    let i = 0; setTyped('');
    const id = setInterval(() => {
      i++; setTyped(line.slice(0, i));
      if (i >= line.length) { clearInterval(id); setTimeout(() => setCallIdx(c => (c + 1) % TRANSCRIPT.length), 2600); }
    }, 30);
    return () => clearInterval(id);
  }, [callIdx]);

  return (
    <div className="stage">
      <div className="stage-head">
        <div className="dots"><span /><span /><span /></div>
        <span className="stage-title">opspot.ops — live ledger</span>
        <span className="stage-pill"><span className="dot" /> crew on shift</span>
      </div>
      <div className="stage-body">
        <aside className="stage-sidebar">
          <div className="side-h">The crew</div>
          {CREW.slice(0, 6).map(m => (
            <div key={m.id} className={`side-item ${m.id === 'courier' ? 'active' : ''}`} style={{ '--c1': m.c1, '--c2': m.c2 }}>
              <span className="ag" /> {m.name}
            </div>
          ))}
          <div className="side-h">This month</div>
          <div className="side-item" style={{ '--c1': 'var(--money)', '--c2': 'var(--money)' }}>
            <span className="ag" /> Receipts <span className="count">1,284</span>
          </div>
        </aside>
        <main className="stage-main">
          <div className="stage-roi">
            <div className="kpi">
              <div className="label">Labor saved · mo</div>
              <div className="val">92h <span className="delta">$3,220</span></div>
              <div className="spark"><Spark seed={2} color="var(--courier)" /></div>
            </div>
            <div className="kpi">
              <div className="label">Leakage recovered</div>
              <div className="val" style={{ color: 'var(--money)' }}><CountMoney value={recovered} /></div>
              <div className="spark"><Spark seed={5} color="var(--money)" /></div>
            </div>
            <div className="kpi">
              <div className="label">Inbound answered</div>
              <div className="val">100% <span className="delta">+0 missed</span></div>
              <div className="spark"><Spark seed={8} color="var(--comms)" /></div>
            </div>
          </div>
          <div className="feed">
            <div className="feed-head">
              <span>Live activity · with receipts</span>
              <span className="tabs"><span className="on">All</span><span>Recovered</span><span>Held</span></span>
            </div>
            {feed.map((r, i) => (
              <div className="row" key={r.msg + i} style={{ '--ac': r.c, gridTemplateColumns: '14px 80px 1fr 64px 70px' }}>
                <div className="agent-dot" />
                <div className="ts mono">{r.who}</div>
                <div className="msg">{r.msg}</div>
                <div className={`tag ${r.cls}`}>{r.tag}</div>
                <div className="rec">{r.recovered ? `+$${r.recovered.toLocaleString()}` : '✓ log'}</div>
              </div>
            ))}
          </div>
        </main>
        <aside className="stage-right">
          <div className="now-card">
            <div className="h">● Live call · 02:14</div>
            <div className="live-call">
              <div className="avatar">C</div>
              <div className="wave">
                {Array.from({ length: 18 }).map((_, i) => <span key={i} style={{ animationDelay: `${i * 60}ms` }} />)}
              </div>
            </div>
            <div className="transcript">
              <span className="who">Courier</span>
              {typed}
              <span className="cursor" />
            </div>
          </div>
          <div className="approval">
            <div className="h">⏸ Awaiting your approval</div>
            <div className="body">
              Redpen held an <b>$8,400 proposal</b> to Ridge HVAC — the price claim needs your sign-off.
            </div>
            <div className="acts">
              <button className="mini-btn ok">Approve &amp; send</button>
              <button className="mini-btn no">Edit</button>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ---------- Hero visual — live teaser (fire, above the fold) ---------- */
function HeroVisual() {
  const [feed, setFeed] = useState(FEED.slice(0, 4));
  const [rec, setRec] = useState(11240);
  const i = useRef(3);
  useEffect(() => {
    const id = setInterval(() => {
      i.current = (i.current + 1) % FEED.length;
      const nx = FEED[i.current];
      setFeed(p => [nx, ...p.slice(0, 3)]);
      if (nx.recovered) setRec(r => r + nx.recovered);
    }, 2600);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="hero-visual">
      <div className="hv-glow" />
      <div className="hv-card">
        <div className="hv-head">
          <span className="hv-live"><span className="d" /> live · this month</span>
          <span className="hv-rec"><CountMoney value={rec} /></span>
        </div>
        <div className="hv-sub">recovered for you — every dollar with a receipt</div>
        <div className="hv-feed">
          {feed.map((r, idx) => (
            <div className="hv-row" key={r.msg + idx} style={{ '--ac': r.c }}>
              <span className="hv-dot" />
              <span className="hv-who">{r.who}</span>
              <span className="hv-msg">{r.msg}</span>
              <span className="hv-tag">{r.recovered ? `+$${r.recovered.toLocaleString()}` : '✓'}</span>
            </div>
          ))}
        </div>
        <div className="hv-call">
          <span className="hv-av">C</span>
          <div className="hv-wave">{Array.from({ length: 20 }).map((_, k) => <span key={k} style={{ animationDelay: `${k * 55}ms` }} />)}</div>
          <span className="hv-calllabel">Courier · on a call</span>
        </div>
      </div>
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-grid" />
      <div className="hero-beams" />
      <div className="hero-inner hero-split">
        <Reveal className="hero-copy">
          <div className="hero-local">
            <span className="hl-pin"><Ico d={ICONS.pin} size={18} /></span>
            <span className="hl-text"><b>Wilmington-built.</b> On the job 24/7.</span>
          </div>
          <h1 className="display">
            <span className="grad">AI employees that</span>{' '}
            <span className="accent">pay for themselves.</span>
          </h1>
          <p className="hero-sub">
            A crew of AI employees that answers your inbound, plugs the leaks, and pays for itself —
            measured in <b>labor saved</b> and <b>leakage recovered.</b>
          </p>
          <div className="hero-actions">
            <a href="#contact" className="btn btn-primary btn-xl" onClick={(e) => { e.preventDefault(); scrollToId('contact'); }}>Get my free audit →</a>
            <a href="#leak" className="btn btn-ghost" onClick={(e) => { e.preventDefault(); scrollToId('leak'); }}>See where the money leaks</a>
          </div>
          <div className="roi-ticker">
            <div className="roi-chip">
              <span className="rc-label">Labor saved / mo</span>
              <span className="rc-val">92 hrs</span>
              <span className="rc-sub">inbox, chasing, admin</span>
            </div>
            <div className="roi-chip">
              <span className="rc-label">Leakage recovered</span>
              <span className="rc-val green">$14.8k</span>
              <span className="rc-sub">across 8 leaks</span>
            </div>
            <div className="roi-chip">
              <span className="rc-label">Inbound answered</span>
              <span className="rc-val">100%</span>
              <span className="rc-sub">calls · forms · chat</span>
            </div>
          </div>
          <p className="note-illus" style={{ marginTop: 16 }}>Illustrative example for a mid-size local business.</p>
        </Reveal>
        <Reveal delay={1}>
          <HeroVisual />
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- Live ops console (mid-page section) ---------- */
function LiveOps() {
  return (
    <section className="section-pad" id="live" style={{ paddingTop: 110 }}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="kicker"><b>05</b> · Command Center</span>
          <h2 className="display" style={{ marginTop: 14 }}>Your whole operation, running in the open.</h2>
          <p>One screen for everything the crew handles — live calls, activity, receipts, and the few things waiting on you. You watch it work, approve what matters, and ignore the rest.</p>
        </Reveal>
        <Reveal delay={1}>
          <ConsoleStage />
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- Leak Ledger (dark operations console) ---------- */
function LeakLedger() {
  const totalLoss = LEAKS.reduce((s, l) => s + l.monthly, 0);
  const totalRec = LEAKS.reduce((s, l) => s + Math.round(l.monthly * l.recover), 0);
  const crewById = Object.fromEntries(CREW.map(m => [m.name, m]));
  return (
    <section className="section-pad console" id="leak" style={{ paddingTop: 96, paddingBottom: 96 }}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="kicker"><b>01</b> · The leak</span>
          <h2 className="display" style={{ marginTop: 14 }}>
            Your business isn’t slow.<br />
            <span className="display-muted">It’s leaking.</span>
          </h2>
          <p>Every missed call, slow follow-up, and unbilled job is money walking out the door — quietly, every month. Here’s where the average business leaks, and how we plug each line without changing how you work.</p>
        </Reveal>

        <Reveal delay={1} className="ledger">
          <div className="ledger-head">
            <div className="dots"><span /><span /><span /></div>
            <span className="lh-title">leak-ledger.ops · monthly · illustrative</span>
            <span className="lh-live"><span className="dot" /> tracked live</span>
          </div>
          <div className="lr-cols">
            <span>Where it leaks</span>
            <span className="ra">Lost / mo</span>
            <span>Plugged by</span>
            <span className="ra">Recovered</span>
          </div>
          {LEAKS.map((l) => {
            const m = crewById[l.fixedBy] || CREW[0];
            const rec = Math.round(l.monthly * l.recover);
            return (
              <div className="lrow" key={l.k}>
                <div className="leak-name">
                  <b>{l.label}</b>
                  <small>{l.detail}</small>
                </div>
                <div className="leak-loss">−${l.monthly.toLocaleString()}</div>
                <div className="leak-fix"><span className="ag" style={{ '--c1': m.c1, '--c2': m.c2 }} /> {l.fixedBy}</div>
                <div className="leak-rec">+${rec.toLocaleString()}</div>
                <div className="leak-bar"><i style={{ width: `${Math.round(l.recover * 100)}%` }} /></div>
              </div>
            );
          })}
          <div className="ledger-foot">
            <span className="lf-label">Total / month</span>
            <span className="lf-loss">−${totalLoss.toLocaleString()}</span>
            <span className="lf-mid">≈ {Math.round(totalRec / totalLoss * 100)}% recoverable with the crew on it</span>
            <span className="lf-rec">+${totalRec.toLocaleString()}</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- ROI Math receipt ---------- */
function RoiMath() {
  const ref = useRef(null);
  const [run, setRun] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((e) => { if (e[0].isIntersecting) { setRun(true); io.disconnect(); } }, { threshold: 0.2 });
    io.observe(el); return () => io.disconnect();
  }, []);
  const labor = ROI.laborHours * ROI.laborRate;
  const net = labor + ROI.leakageRecovered - ROI.fee;
  const multiple = ((labor + ROI.leakageRecovered) / ROI.fee).toFixed(1);
  return (
    <section className="section-pad" id="roi" style={{ paddingTop: 110 }}>
      <div className="container">
        <Reveal className="sec-head" style={{ maxWidth: 820 }}>
          <span className="kicker"><b>02</b> · The math</span>
          <h2 className="display" style={{ marginTop: 14 }}>One number decides everything: net ROI.</h2>
          <p>We don’t sell hours or seats. We sell a return. Every month you get a plain receipt: what we saved you in labor, what we recovered in leakage, minus what we cost. If it isn’t green, we fix it.</p>
        </Reveal>
        <div className="roi-wrap">
          <Reveal delay={1} className="roi-receipt">
            <span ref={ref} aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} />
            <div className="rr-head"><span>roi-statement.opspot</span><span>example · /mo</span></div>
            <div className="rr-body">
              <div className="rr-line">
                <div className="rr-l"><b>Labor saved</b><small>{ROI.laborHours} hrs × ${ROI.laborRate}/hr — inbox, chasing, admin</small></div>
                <div className="rr-amt pos">{run ? <CountMoney value={labor} run={run} /> : '$0'}</div>
              </div>
              <div className="rr-line">
                <div className="rr-l"><b>Leakage recovered</b><small>missed calls, slow follow-up, unbilled work…</small></div>
                <div className="rr-amt pos">{run ? <CountMoney value={ROI.leakageRecovered} run={run} /> : '$0'}</div>
              </div>
              <div className="rr-line">
                <div className="rr-l"><b>OpSpot fee</b><small>Growth Ops Employee — example tier</small></div>
                <div className="rr-amt neg">−${ROI.fee.toLocaleString()}</div>
              </div>
            </div>
            <div className="rr-total">
              <div className="rt-l"><b>Net operational ROI</b><small>{multiple}× return on fee · this month</small></div>
              <div className="rt-amt">{run ? <CountMoney value={net} run={run} /> : '$0'}</div>
            </div>
            <div className="rr-foot"><span>signed · op-roi-2B7E</span><span>illustrative example</span></div>
          </Reveal>
          <div className="roi-side">
            <Reveal delay={2}>
              <h3>If it doesn’t pay for itself, you shouldn’t keep it.</h3>
              <p>That’s the deal. Everything we put into your business has to make this one number bigger than what we charge — and you can open the receipt behind every dollar.</p>
              <div className="roi-bullets">
                <div className="rb"><span className="rb-ic">{<Ico d={ICONS.check} size={13} />}</span><div><b>Labor saved</b> is measured in real hours handled — not vibes.</div></div>
                <div className="rb"><span className="rb-ic">{<Ico d={ICONS.check} size={13} />}</span><div><b>Leakage recovered</b> is tied to specific leaks Recon found and the crew plugged.</div></div>
                <div className="rb"><span className="rb-ic">{<Ico d={ICONS.check} size={13} />}</span><div><b>Every dollar</b> traces back to a signed receipt you can open.</div></div>
              </div>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Ico, ICONS, crewIcon, ConsoleStage, HeroVisual, Hero, LiveOps, LeakLedger, RoiMath });
