// hero-live.jsx — Live AI ops console for the hero right column.
// Shows: live waiting times across 4 clinics, an animated patient
// onboarding flow (Sarah M., looping), agent reasoning text, and a
// compact phone-line card. All numbers drift each tick to feel alive.

const { useState: useS_HL, useEffect: useE_HL, useRef: useR_HL } = React;

// ─────────────────────────────────────────────────────────────────────────────
// LiveOpsConsole — top card
// ─────────────────────────────────────────────────────────────────────────────

const CLINIC_BASELINES = [
  { code: "Tuxedo",    base: 42, range: 14 },
  { code: "St. Vital", base: 74, range: 18 },
  { code: "Brandon",   base: 18, range: 8  },
  { code: "Steinbach", base: 35, range: 12 },
];

function formatWait(sec) {
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return `${m}:${String(s).padStart(2, "0")}`;
}

function LiveOpsConsole({ onWhy }) {
  const [tick, setTick] = useS_HL(0);
  useE_HL(() => {
    const id = setInterval(() => setTick((t) => t + 1), 2400);
    return () => clearInterval(id);
  }, []);

  // Drift wait times deterministically off tick so SSR/CSR match.
  const waits = CLINIC_BASELINES.map((c, i) => {
    const drift = Math.sin((tick + i * 1.7) * 0.6) * c.range;
    return Math.max(8, Math.round(c.base + drift));
  });
  const maxWait = Math.max(120, ...waits);

  // Agents + counters drift
  const agentsActive = 11 + ((tick * 3) % 7);
  const queued = 4 + (tick % 6);
  const bookedToday = 38 + Math.floor(tick / 4) % 18;

  // Booking flow: 5 steps, ~3 ticks each, loops.
  const FLOW = [
    { label: "Intake captured",          detail: "SMS · NEW_PATIENT · PII redacted",       dur: "2.1s" },
    { label: "Severity assessed",        detail: "Pain-First Routing · 7/10",              dur: "0.4s" },
    { label: "Slot matched",             detail: "Tuxedo · Dr. Chen · 10:30 tomorrow",     dur: "0.7s" },
    { label: "Confirmation dispatched",  detail: "SMS · delivered · receipt logged",       dur: "1.1s" },
    { label: "Intake form queued",       detail: "PIPEDA consent v1.4 · sent",             dur: "0.3s" },
  ];
  const flowStep = Math.min(FLOW.length, Math.floor((tick % 18) / 3));
  const reasoning = [
    "Reading inbound: chipped front tooth, throbbing this morning, new to us.",
    "Severity 7/10 — structural damage + acute pain. Urgent eligible.",
    "Three urgent slots within 24h. Closest match: Tuxedo / Dr. Chen / 10:30.",
    "Reply drafted in EN at grade-7 reading level. Sending.",
    "Confirmation in. Queueing intake form + privacy notice for tomorrow morning.",
  ][Math.min(reasoning_len() - 1, flowStep)];

  return (
    <div className="liveops">
      {/* Header */}
      <div className="liveops-head">
        <div className="liveops-status">
          <span className="liveops-dot" />
          <span className="eyebrow" style={{ fontSize: 10 }}>ARIA · live ops</span>
        </div>
        <div className="liveops-meta">
          <span><b>{agentsActive}</b> agents</span>
          <span className="liveops-sep">·</span>
          <span><b>{queued}</b> queued</span>
          <span className="liveops-sep">·</span>
          <span><b>{bookedToday}</b> booked today</span>
        </div>
      </div>

      {/* Live waiting times */}
      <div className="liveops-section">
        <div className="liveops-section-head">
          <span className="eyebrow" style={{ fontSize: 10 }}>Live · first-reply latency</span>
          <span className="liveops-tag">median · last 5 min</span>
        </div>
        <div className="liveops-clinics">
          {CLINIC_BASELINES.map((c, i) => {
            const pct = Math.min(100, (waits[i] / maxWait) * 100);
            const hot = waits[i] > 75;
            return (
              <div key={c.code} className="liveops-row">
                <div className="liveops-row-name">{c.code}</div>
                <div className="liveops-bar">
                  <div className="liveops-bar-fill" style={{ width: `${pct}%`, background: hot ? "var(--warn)" : "var(--brand)" }} />
                </div>
                <div className="liveops-row-time" style={{ color: hot ? "var(--warn)" : "var(--ink)" }}>{formatWait(waits[i])}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Divider */}
      <div className="liveops-divider" />

      {/* Onboarding flow */}
      <div className="liveops-section">
        <div className="liveops-section-head">
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div className="liveops-avatar">SM</div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>Onboarding · Sarah M.</div>
              <div style={{ fontSize: 11, color: "var(--ink-mute)" }}>New patient · SMS · Tuxedo</div>
            </div>
          </div>
          <span className="liveops-tag liveops-tag-live">live</span>
        </div>

        <div className="liveops-steps">
          {FLOW.map((s, i) => {
            const state = i < flowStep ? "done" : i === flowStep ? "active" : "idle";
            return (
              <div key={i} className="liveops-step" data-state={state}>
                <span className="liveops-step-marker">
                  {state === "done" && <CheckIcon />}
                  {state === "active" && <span className="liveops-spin" />}
                  {state === "idle" && <span className="liveops-idle-dot" />}
                </span>
                <span className="liveops-step-label">{s.label}</span>
                <span className="liveops-step-detail">{s.detail}</span>
                <span className="liveops-step-dur">{state === "done" ? s.dur : state === "active" ? "…" : ""}</span>
              </div>
            );
          })}
        </div>

        {/* Reasoning bubble */}
        <div className="liveops-reasoning">
          <div className="liveops-reasoning-head">
            <span>ARIA · reasoning</span>
            <span className="liveops-typing"><i /><i /><i /></span>
          </div>
          <div key={flowStep} className="liveops-reasoning-text">
            {reasoning}
          </div>
        </div>

        <button onClick={onWhy} className="btn btn-primary liveops-why">
          Why this routing? <span style={{ opacity: .7, fontFamily: "var(--font-display)", fontStyle: "italic" }}>see the receipts</span>
        </button>
      </div>
    </div>
  );
}

function reasoning_len() { return 5; }

function CheckIcon() {
  return (
    <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
      <path d="M2.5 6.5l2.5 2.5L9.5 3.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Hero right column composition (top console + 2 small cards)
// ─────────────────────────────────────────────────────────────────────────────

function HeroLiveColumn({ onWhy }) {
  return (
    <div className="hero-right">
      <LiveOpsConsole onWhy={onWhy} />

      <div className="hero-right-row">
        {/* Phone demo line card */}
        <a href="tel:+12498000333" className="hero-mini hero-mini-dark">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="liveops-dot" />
            <span style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "rgba(244,238,230,.65)" }}>
              EN demo line
            </span>
          </div>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, lineHeight: 1.05 }}>+1 249<br />800 0333</div>
            <div style={{ fontSize: 11, color: "rgba(244,238,230,.55)", marginTop: 8 }}>
              Appointments · recalls · after-hours triage
            </div>
          </div>
        </a>

        {/* New-patient onboarding mini card */}
        <a href="#contact" className="hero-mini hero-mini-light">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--brand)" }} />
            <span style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
              New patient · 90s
            </span>
          </div>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, lineHeight: 1.05, color: "var(--ink)" }}>
              Onboard yourself,<br /><span style={{ fontStyle: "italic", color: "var(--brand)" }}>any channel.</span>
            </div>
            <div style={{ fontSize: 11.5, color: "var(--ink-mute)", marginTop: 8, lineHeight: 1.4 }}>
              4 steps · PIPEDA consent · no calls required
            </div>
          </div>
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { LiveOpsConsole, HeroLiveColumn });
