/* OpSpot — The crew, the inbound pipeline, the command center queue. */
const { useState, useEffect, useRef } = React;

/* ---------- The crew ---------- */
function Crew() {
  return (
    <section className="section-pad" id="crew" style={{ paddingTop: 110 }}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="kicker"><b>03</b> · The crew</span>
          <h2 className="display" style={{ marginTop: 14 }}>Eight AI employees. One job each.</h2>
          <p>You don’t get a tool to figure out on your own. You get a crew that slots into the phone, inbox, and calendar you already use — each one owns a narrow job, hands off cleanly, and signs its work.</p>
        </Reveal>
        <div className="crew-grid">
          {CREW.map((m, i) => {
            const wide = i < 2;
            return (
              <Reveal key={m.id} delay={(i % 3) + 1} className={`crew-card ${wide ? 'wide' : ''}`}
                      style={{ '--c': m.c, '--c1': m.c1, '--c2': m.c2 }}>
                <div className="crew-top">
                  <div className="crew-badge">{m.name === 'Deal Desk' ? 'DD' : m.name[0]}</div>
                  <div className="crew-id">
                    <span className="nm">{m.name}</span>
                    <span className="rl">{m.role}</span>
                  </div>
                </div>
                <p>{m.job}</p>
                <div className="crew-verbs">
                  {m.verbs.map(v => <span className="v" key={v}>{v}</span>)}
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------- Inbound pipeline ---------- */
/* ---------- Inbound relay — one ticket, processed live ---------- */
const RELAY = [
  { id: 'courier', verb: 'Capturing', status: 'on the line', line: 'Caught your web form in 40s — pulled the name, address, and job type.', stamp: 'captured' },
  { id: 'recon', verb: 'Sizing', status: 'auditing', line: 'Matched the account — leak inspection ≈ $480, and it’s a repeat customer.', stamp: 'valued' },
  { id: 'comms', verb: 'Writing', status: 'drafting', line: 'Wrote the reply with two time slots, in plain language that sounds like you.', stamp: 'drafted' },
  { id: 'redpen', verb: 'Checking', status: 'reviewing', line: 'No overpromising, the price is accurate, privacy is clear — safe to send.', stamp: 'cleared' },
  { id: 'marshal', verb: 'Booking', status: 'scheduling', line: 'Booked Tue 9:30 with Marco. Confirmation sent, reminder scheduled.', stamp: 'booked' },
  { id: 'receipt', verb: 'Signed', status: 'done', line: 'Receipt filed — 5 actions logged. You can open it anytime.', stamp: 'signed', terminal: true },
];

function InboundFlow() {
  const [step, setStep] = useState(0);
  const [ticket, setTicket] = useState(4471);

  useEffect(() => {
    const id = setInterval(() => {
      setStep(s => {
        if (s >= RELAY.length - 1) { setTicket(t => t + 1); return 0; }
        return s + 1;
      });
    }, 1750);
    return () => clearInterval(id);
  }, []);

  const crewOf = (id) => CREW.find(c => c.id === id) || CREW[0];
  const progress = (step / (RELAY.length - 1)) * 100;
  const cur = RELAY[step];

  return (
    <section className="section-pad" id="flow" style={{ paddingTop: 0 }}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="kicker"><b>04</b> · How inbound flows</span>
          <h2 className="display" style={{ marginTop: 14 }}>From “someone called” to “booked, with a receipt.”</h2>
          <p>Every inbound runs the same clean relay. Each member does one job, stamps the ticket, and hands off — and nothing important ships until Redpen clears it. Here’s one moving through, live.</p>
        </Reveal>

        <Reveal delay={1} className="relay">
          <div className="relay-rail">
            <div className="relay-rail-h">The relay</div>
            <div className="relay-line"><span className="relay-line-fill" style={{ height: progress + '%' }} /></div>
            {RELAY.map((r, i) => {
              const m = crewOf(r.id);
              const state = i < step ? 'done' : i === step ? 'active' : 'pending';
              const c = r.terminal ? 'var(--money)' : m.c;
              const c1 = r.terminal ? 'oklch(0.6 0.15 158)' : m.c1;
              const c2 = r.terminal ? 'var(--money)' : m.c2;
              return (
                <div className={`relay-step ${state}`} key={r.id} style={{ '--c': c, '--c1': c1, '--c2': c2 }}>
                  <span className="relay-badge">
                    {state === 'done' ? <Ico d={ICONS.check} size={15} /> : <Ico d={r.terminal ? ICONS.receipt : crewIcon(r.id)} size={16} />}
                  </span>
                  <span className="relay-name">{r.terminal ? 'Receipt' : m.name}</span>
                  <span className="relay-verb">{state === 'pending' ? 'queued' : state === 'active' ? r.status : r.stamp}</span>
                </div>
              );
            })}
          </div>

          <div className="relay-stage">
            <div className="ticket">
              <div className="ticket-head">
                <div className="ticket-id">
                  <span className="tk">INBOUND</span>
                  <b>#{ticket}</b>
                  <span className="tk-sub">leak inspection · web form · 2:48am</span>
                </div>
                <div className={`ticket-status ${cur.terminal ? 'done' : ''}`}>
                  <span className="d" /> {cur.terminal ? 'complete' : cur.verb + '…'}
                </div>
              </div>
              <div className="ticket-body">
                {RELAY.slice(0, step + 1).map((r, i) => {
                  const m = crewOf(r.id);
                  const isCur = i === step;
                  const c = r.terminal ? 'var(--money)' : m.c;
                  const c1 = r.terminal ? 'oklch(0.6 0.15 158)' : m.c1;
                  const c2 = r.terminal ? 'var(--money)' : m.c2;
                  return (
                    <div className={`ticket-line ${isCur ? 'cur' : ''} ${r.terminal ? 'sign' : ''}`} key={r.id + '-' + ticket} style={{ '--c': c, '--c1': c1, '--c2': c2 }}>
                      <span className="tl-badge">{r.terminal ? 'OS' : m.name[0]}</span>
                      <div className="tl-text">
                        <span className="tl-who">{r.terminal ? 'OpSpot' : m.name} <em>· {r.stamp}</em></span>
                        <span className="tl-desc">{r.line}</span>
                      </div>
                      <span className="tl-mark">
                        {isCur && !r.terminal ? <span className="tl-dots"><span /><span /><span /></span> : <Ico d={ICONS.check} size={14} />}
                      </span>
                    </div>
                  );
                })}
              </div>
              <div className="ticket-foot">
                <span>{cur.terminal ? `✓ signed · op-relay-${ticket} · 5 actions logged` : `live · step ${step + 1} of ${RELAY.length}`}</span>
                <span className="tf-mono">opspot.relay</span>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- Command Center queue ---------- */
const JOBS = [
  { t: 'After-hours call · leak inspection', who: 'Courier', id: 'courier' },
  { t: 'Stale estimate flagged · Bayside Café', who: 'Recon', id: 'recon' },
  { t: 'Quote follow-up · 9 contacts', who: 'Comms', id: 'comms' },
  { t: '$8.4k proposal · held for sign-off', who: 'Redpen', id: 'redpen' },
  { t: 'Rebooked 2 no-shows', who: 'Marshal', id: 'marshal' },
  { t: 'Web form caught · routed to Recon', who: 'Courier', id: 'courier' },
  { t: 'Invoice nudge · $2.1k aging', who: 'Comms', id: 'comms' },
  { t: '3 completed jobs unbilled · invoiced', who: 'Marshal', id: 'marshal' },
  { t: 'Review ask sent · 5★ job', who: 'Comms', id: 'comms' },
];

function CommandCenter() {
  const [intake, setIntake] = useState([0, 1, 2]);
  const [working, setWorking] = useState([3, 4]);
  const [done, setDone] = useState([5, 6, 7]);
  const counter = useRef(8);
  useEffect(() => {
    const tick = setInterval(() => {
      setWorking(w => {
        if (w.length) { const [first, ...rest] = w; setTimeout(() => setDone(d => [first, ...d].slice(0, 4)), 0); return rest; }
        return w;
      });
      setIntake(it => {
        if (it.length) { const [first, ...rest] = it; setTimeout(() => setWorking(w => [...w, first]), 0); return rest; }
        return it;
      });
      setIntake(it => [counter.current++, ...it].slice(0, 4));
    }, 3000);
    return () => clearInterval(tick);
  }, []);

  const renderJob = (id) => {
    const j = JOBS[id % JOBS.length];
    const m = CREW.find(c => c.id === j.id) || CREW[0];
    return (
      <div key={id} className="job ent">
        <div className="jh"><span>JOB-{String(1240 + id).padStart(4, '0')}</span><span>{(id % 13) + 1}m</span></div>
        <div>{j.t}</div>
        <div className="who"><span className="ag" style={{ '--c1': m.c1, '--c2': m.c2 }} /> {j.who}</div>
      </div>
    );
  };

  return (
    <section className="section-pad" id="center" style={{ paddingTop: 0 }}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="kicker"><b>05</b> · Command Center</span>
          <h2 className="display" style={{ marginTop: 14 }}>One queue for the whole operation.</h2>
          <p>Work lands from anywhere and moves from intake to done — in the open. You see every job, approve what matters, and ignore the rest. Nothing happens off the books.</p>
        </Reveal>
        <Reveal delay={1} className="cmd-mock">
          <div className="cmd-head">
            <div className="dots"><span /><span /><span /></div>
            <span className="stage-title">command-center · live</span>
            <div className="cmd-tabs"><span className="on">Queue</span><span>Approvals</span><span>Receipts</span><span>Crew</span></div>
          </div>
          <div className="cmd-body">
            <div className="lane">
              <div className="lane-h"><span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--courier)', boxShadow: '0 0 8px var(--courier)' }} /> Intake <span className="ct">{intake.length} new</span></div>
              {intake.map(renderJob)}
            </div>
            <div className="lane">
              <div className="lane-h"><span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--recon)', boxShadow: '0 0 8px var(--recon)' }} /> Working <span className="ct">{working.length} active</span></div>
              {working.map(renderJob)}
            </div>
            <div className="lane">
              <div className="lane-h"><span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--money)', boxShadow: '0 0 8px var(--money)' }} /> Done · today <span className="ct">{done.length + 142} ✓</span></div>
              {done.map(renderJob)}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- Connected hub (compact, revamped system map) ---------- */
function Hub() {
  const tools = [
    { l: 'Phone', c: 'var(--courier)' },
    { l: 'Inbox', c: 'var(--recon)' },
    { l: 'Calendar', c: 'var(--marshal)' },
    { l: 'CRM', c: 'var(--orbit)' },
    { l: 'Payments', c: 'var(--teller)' },
    { l: 'Website', c: 'var(--comms)' },
    { l: 'Reviews', c: 'var(--dealdesk)' },
    { l: 'Texts', c: 'oklch(0.6 0.2 22)' },
  ];
  const cx = 340, cy = 190, rx = 272, ry = 135, N = tools.length;
  const nodes = tools.map((t, i) => {
    const a = (Math.PI * 2 * i) / N - Math.PI / 2;
    return { ...t, a, x: cx + rx * Math.cos(a), y: cy + ry * Math.sin(a) };
  });
  return (
    <section className="section-pad" id="connected" style={{ paddingTop: 0 }}>
      <div className="container">
        <Reveal className="sec-head">
          <span className="kicker"><b>06</b> · Connected</span>
          <h2 className="display" style={{ marginTop: 14 }}>Plugs into the tools you already run.</h2>
          <p>OpSpot sits in the middle of your phone, inbox, calendar, CRM, and the rest — so the crew works with what you’ve got. No rip-and-replace, and no new logins for your team.</p>
        </Reveal>
        <Reveal delay={1} className="hub">
          <svg className="hub-svg" viewBox="0 0 680 380" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
            <defs>
              <radialGradient id="hubCore" cx="0.5" cy="0.5" r="0.5">
                <stop offset="0" stopColor="oklch(0.62 0.22 290 / .28)" />
                <stop offset="0.6" stopColor="oklch(0.62 0.2 270 / .1)" />
                <stop offset="1" stopColor="transparent" />
              </radialGradient>
            </defs>
            <circle cx={cx} cy={cy} r="128" fill="url(#hubCore)" />
            {nodes.map((p, i) => (
              <g key={'l' + i}>
                <line x1={cx} y1={cy} x2={p.x} y2={p.y} stroke="rgba(15,17,22,.09)" strokeWidth="1" />
                <line x1={cx} y1={cy} x2={p.x} y2={p.y} stroke={p.c} strokeWidth="1.4" strokeOpacity="0.5" strokeDasharray="3 8" style={{ animation: 'dash 5s linear infinite', animationDelay: `${i * 0.4}s` }} />
              </g>
            ))}
            <circle cx={cx} cy={cy} r="44" fill="#fff" stroke="var(--courier)" strokeOpacity="0.5" strokeWidth="1.5" />
            <circle cx={cx} cy={cy} r="6" fill="var(--courier)">
              <animate attributeName="r" values="6;9;6" dur="2.6s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="1;.5;1" dur="2.6s" repeatCount="indefinite" />
            </circle>
            <text x={cx} y={cy - 1} textAnchor="middle" fontFamily="Space Grotesk, sans-serif" fontSize="16" fontWeight="600" fill="#0e1116">OpSpot</text>
            <text x={cx} y={cy + 16} textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" letterSpacing="2.5" fill="#8a90a0">CORE</text>
            {nodes.map((p, i) => {
              const above = p.y < cy - 10;
              const ly = above ? p.y - 30 : p.y + 34;
              return (
                <g key={'n' + i}>
                  <circle cx={p.x} cy={p.y} r="21" fill="#fff" stroke={p.c} strokeOpacity="0.55" strokeWidth="1.5" />
                  <circle cx={p.x} cy={p.y} r="6" fill={p.c}>
                    <animate attributeName="opacity" values="1;.35;1" dur={`${2 + i * 0.25}s`} repeatCount="indefinite" />
                  </circle>
                  <text x={p.x} y={ly} textAnchor="middle" dominantBaseline={above ? 'auto' : 'hanging'} fontFamily="Space Grotesk, sans-serif" fontSize="14" fontWeight="500" fill="#3d434f">{p.l}</text>
                </g>
              );
            })}
          </svg>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Crew, InboundFlow, CommandCenter, Hub });
