/* Broadcast console — an illustrative campaign send.
 *
 * Three panes: the audience funnel (list → consented), the pacing bar filling
 * against the WABA messaging tier, and a delivery log ticking over. Loops.
 * Numbers here are illustrative, not a client's reported results.
 */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

const BC_TOTAL = 29100;
const BC_CONSENTED = 24318;
const BC_TIER = 10000;
/* This used to re-render the whole console — style block and all — 60 times a
 * second. 15 is plenty: the counters still tick smoothly and the pacing bar
 * interpolates between updates on the compositor. */
const BC_TICK_MS = 1000 / 15;

function BroadcastStage() {
  const rootRef = useRefB(null);
  const { active, still } = useStage(rootRef);
  const [t, setT] = useStateB(() => (still ? 1 : 0)); // 0 → 1 progress through one send cycle

  useEffectB(() => {
    if (!active) return;
    let raf, start = null, last = 0;
    const DURATION = 5200, PAUSE = 1400;
    const run = (ts) => {
      if (start === null) start = ts;
      const elapsed = ts - start;
      const p = Math.min(1, elapsed / DURATION);
      if (ts - last >= BC_TICK_MS || p === 1) {
        last = ts;
        setT(1 - Math.pow(1 - p, 2.2));
      }
      if (elapsed < DURATION + PAUSE) raf = requestAnimationFrame(run);
      else { start = null; last = 0; setT(0); raf = requestAnimationFrame(run); }
    };
    raf = requestAnimationFrame(run);
    return () => cancelAnimationFrame(raf);
  }, [active]);

  const sent = Math.round(BC_TIER * t);
  const delivered = Math.round(sent * 0.973);
  const replied = Math.round(sent * 0.041);

  const log = [
    { at: 0.14, label: "Template approved", note: "wedding_arrivals_v2" },
    { at: 0.30, label: "Batch 1 · 2,500 queued", note: "paced to tier" },
    { at: 0.52, label: "3 opt-outs honored", note: "STOP · removed" },
    { at: 0.71, label: "Batch 3 · 2,500 queued", note: "retry: 11 failed" },
    { at: 0.89, label: "Replies routing to inbox", note: "bot on standby" },
  ].filter(r => t >= r.at).slice(-4).reverse();

  return (
    <div className="bc-stage" ref={rootRef}>
      <div className="bc-head">
        <div>
          <div className="bc-eyebrow">Campaign · Wedding season arrivals</div>
          <div className="bc-title">Broadcast to consented list</div>
        </div>
        <div className="bc-live"><span className="bc-dot" /> {t < 1 ? "Sending" : "Complete"}</div>
      </div>

      <div className="bc-grid">
        {/* Audience funnel */}
        <div className="bc-pane">
          <div className="bc-pane-label">Audience</div>
          <div className="bc-funnel">
            <div className="bc-funnel-row">
              <span className="bc-funnel-bar" style={{ width: "100%" }} />
              <b>{BC_TOTAL.toLocaleString()}</b>
              <span>on the list</span>
            </div>
            <div className="bc-funnel-row is-on">
              <span className="bc-funnel-bar" style={{ width: `${(BC_CONSENTED / BC_TOTAL) * 100}%` }} />
              <b>{BC_CONSENTED.toLocaleString()}</b>
              <span>consented</span>
            </div>
            <div className="bc-funnel-row is-off">
              <span className="bc-funnel-bar" style={{ width: `${((BC_TOTAL - BC_CONSENTED) / BC_TOTAL) * 100}%` }} />
              <b>{(BC_TOTAL - BC_CONSENTED).toLocaleString()}</b>
              <span>never messaged</span>
            </div>
          </div>
        </div>

        {/* Pacing */}
        <div className="bc-pane">
          <div className="bc-pane-label">Pacing · tier {BC_TIER.toLocaleString()}/day</div>
          <div className="bc-bar"><span className="bc-bar-fill" style={{ transform: `scaleX(${t})` }} /></div>
          <div className="bc-nums">
            <div><b>{sent.toLocaleString()}</b><span>sent</span></div>
            <div><b>{delivered.toLocaleString()}</b><span>delivered</span></div>
            <div><b>{replied.toLocaleString()}</b><span>replied</span></div>
          </div>
        </div>

        {/* Delivery log */}
        <div className="bc-pane">
          <div className="bc-pane-label">Send log</div>
          <div className="bc-log">
            {log.length === 0 && <div className="bc-log-row bc-log-idle">waiting for template approval…</div>}
            {log.map(r => (
              <div key={r.label} className="bc-log-row">
                <span className="bc-log-tick">✓✓</span>
                <span className="bc-log-label">{r.label}</span>
                <span className="bc-log-note">{r.note}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        .bc-stage { width: 100%; height: 100%; padding: 18px; display: flex; flex-direction: column; gap: 14px; font-family: var(--f-sans); }
        .bc-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; flex-wrap: wrap; }
        .bc-head > div { min-width: 0; }
        .bc-eyebrow { font: 500 10.5px/1 var(--f-mono); letter-spacing: .1em; text-transform: uppercase; color: var(--muted); }
        .bc-title { font-size: 15px; font-weight: 500; margin-top: 5px; }
        .bc-live { display: inline-flex; align-items: center; gap: 6px; font: 500 11px/1 var(--f-mono); color: var(--muted); text-transform: uppercase; letter-spacing: .1em; white-space: nowrap; }
        .bc-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); animation: pulse-dot 1.6s ease-in-out infinite; }

        .bc-grid { flex: 1; display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr) minmax(0, 1.15fr); gap: 12px; }
        .bc-pane { background: var(--paper); border: 1px solid var(--line); border-radius: 10px; padding: 12px 13px 14px; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
        html.dark .bc-pane { background: var(--paper-3); }
        .bc-pane-label { font: 500 10px/1 var(--f-mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }

        .bc-funnel { display: flex; flex-direction: column; gap: 8px; }
        .bc-funnel-row { position: relative; display: flex; align-items: baseline; gap: 7px; padding: 6px 8px; border-radius: 6px; overflow: hidden; }
        .bc-funnel-bar { position: absolute; inset: 0 auto 0 0; background: var(--ink); opacity: .07; border-radius: 6px; }
        .bc-funnel-row.is-on .bc-funnel-bar { background: var(--accent); opacity: .22; }
        .bc-funnel-row.is-off .bc-funnel-bar { background: var(--ink); opacity: .05; }
        .bc-funnel-row b { position: relative; font: 500 15px/1 var(--f-sans); color: var(--ink); letter-spacing: -0.01em; }
        .bc-funnel-row span:last-child { position: relative; font-size: 11.5px; color: var(--muted); }
        .bc-funnel-row.is-off b, .bc-funnel-row.is-off span:last-child { color: var(--muted); }

        .bc-bar { height: 8px; border-radius: 999px; background: color-mix(in oklab, var(--ink) 10%, transparent); overflow: hidden; }
        /* Scaled, not width-animated, so the fill rides the compositor and can
         * interpolate between the throttled React updates. */
        .bc-bar-fill {
          display: block; width: 100%; height: 100%;
          background: var(--accent); border-radius: 999px;
          transform-origin: left center; transform: scaleX(0);
          transition: transform .09s linear;
        }
        .bc-nums { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-top: auto; }
        .bc-nums b { display: block; font-family: var(--f-serif); font-style: italic; font-size: 22px; line-height: 1; letter-spacing: -0.02em; color: var(--ink); }
        .bc-nums span { display: block; margin-top: 5px; font: 500 10px/1.2 var(--f-mono); letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }

        /* Reserve the four-row height up front. Letting the log grow as entries
         * arrived pushed the whole card — and everything under it — down. */
        .bc-log { display: flex; flex-direction: column; gap: 6px; min-height: 78px; }
        .bc-log-row { display: flex; align-items: baseline; gap: 7px; font-size: 11.5px; color: var(--ink); animation: bc-in .35s ease both; min-width: 0; }
        .bc-log-tick { color: var(--accent); font-size: 10px; }
        .bc-log-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .bc-log-note { margin-left: auto; font: 400 10.5px/1 var(--f-mono); color: var(--muted); white-space: nowrap; }
        .bc-log-idle { color: var(--muted); font-family: var(--f-mono); font-size: 11px; }
        @keyframes bc-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }

        @media (max-width: 900px) {
          .bc-grid { grid-template-columns: minmax(0, 1fr); }
          .bc-stage { gap: 12px; }
        }
        @media (max-width: 560px) {
          .bc-stage { padding: 14px; }
          .bc-title { font-size: 14px; }
          .bc-nums b { font-size: 19px; }
        }
      `}</style>
    </div>
  );
}

window.BroadcastStage = BroadcastStage;
