// ============================================================================
// public/screens/monitor.jsx — Live Call Monitor (Phase 5)
// ----------------------------------------------------------------------------
// Connects to GET /api/calls/live (SSE) for real-time active calls.
// Shows cards with waveform, status, duration timer, agent info.
// ============================================================================

function MonitorScreen() {
  const [activeCalls, setActive] = React.useState([]);
  const [connected, setConnected] = React.useState(false);
  const [error, setError]        = React.useState(null);
  const [stats, setStats]        = React.useState(null);
  const esRef = React.useRef(null);
  const timerRef = React.useRef(null);

  // SSE connection
  React.useEffect(() => {
    const base = (window.VOAIS_API_BASE || "");
    const sess = VoaisAPI.getSession();
    if (!sess?.token) return;

    // SSE doesn't support custom headers easily, so we'll poll instead
    // (browser EventSource can't set Authorization header)
    let alive = true;

    const poll = async () => {
      if (!alive) return;
      try {
        const r = await VoaisAPI.get("/api/calls?status=in_progress&limit=50&page=1");
        if (r.ok && r.data?.ok) {
          // Also get initiated + ringing
          const r2 = await VoaisAPI.get("/api/calls?status=initiated&limit=50&page=1");
          const r3 = await VoaisAPI.get("/api/calls?status=ringing&limit=50&page=1");
          const r4 = await VoaisAPI.get("/api/calls?status=answered&limit=50&page=1");
          const all = [
            ...(r.data.calls || []),
            ...(r2.ok ? r2.data.calls || [] : []),
            ...(r3.ok ? r3.data.calls || [] : []),
            ...(r4.ok ? r4.data.calls || [] : []),
          ];
          // Deduplicate by id
          const seen = new Set();
          const unique = all.filter(c => { if (seen.has(c.id)) return false; seen.add(c.id); return true; });
          setActive(unique);
          setConnected(true);
        }
      } catch (e) {
        console.warn("[monitor] poll error:", e.message);
      }
    };

    poll();
    const interval = setInterval(poll, 3000);

    // Also load stats
    VoaisAPI.get("/api/calls/stats").then(r => {
      if (r.ok && r.data?.ok) setStats(r.data.stats);
    });

    return () => {
      alive = false;
      clearInterval(interval);
    };
  }, []);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>

      {/* Header KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 10 }}>
        <div style={{ padding: "14px 16px", background: activeCalls.length > 0 ? "var(--accent-soft)" : "var(--surface-2)", borderRadius: 12, textAlign: "center" }}>
          <div style={{ fontSize: 32, fontWeight: 700, color: activeCalls.length > 0 ? "var(--accent)" : "var(--ink-3)" }} className="tabular">
            {activeCalls.length}
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>Active calls</div>
        </div>
        {stats && (
          <>
            <div style={{ padding: "14px 16px", background: "var(--surface-2)", borderRadius: 12, textAlign: "center" }}>
              <div style={{ fontSize: 24, fontWeight: 600 }} className="tabular">{stats.today.total}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>Calls today</div>
            </div>
            <div style={{ padding: "14px 16px", background: "var(--surface-2)", borderRadius: 12, textAlign: "center" }}>
              <div style={{ fontSize: 24, fontWeight: 600, color: "var(--ok)" }} className="tabular">{stats.today.answered}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>Answered</div>
            </div>
            <div style={{ padding: "14px 16px", background: "var(--surface-2)", borderRadius: 12, textAlign: "center" }}>
              <div style={{ fontSize: 24, fontWeight: 600 }} className="tabular">{stats.today.minutes}m</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>Minutes</div>
            </div>
          </>
        )}
      </div>

      {/* Connection status */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-3)" }}>
        <div style={{ width: 8, height: 8, borderRadius: "50%", background: connected ? "var(--ok)" : "var(--err)" }}/>
        {connected ? "Live — refreshing every 3s" : "Connecting..."}
      </div>

      {/* Active calls grid */}
      {activeCalls.length === 0 && (
        <Card>
          <div style={{ padding: "48px 24px", textAlign: "center" }}>
            <I.phone size={40} style={{ color: "var(--ink-3)", opacity: 0.3, marginBottom: 16 }}/>
            <h3 style={{ fontSize: 18, fontWeight: 600, margin: "0 0 8px" }}>No active calls</h3>
            <p style={{ color: "var(--ink-3)", fontSize: 13, margin: 0 }}>
              When campaigns start dialing, active calls will appear here in real-time.
            </p>
          </div>
        </Card>
      )}

      {activeCalls.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: "var(--gap-grid)" }}>
          {activeCalls.map(c => (
            <LiveCallCard key={c.id} call={c}/>
          ))}
        </div>
      )}
    </div>
  );
}


// ── Live Call Card ──────────────────────────────────────────────────────
function LiveCallCard({ call }) {
  // Live duration timer
  const [elapsed, setElapsed] = React.useState(0);

  React.useEffect(() => {
    if (!call.started_at) return;
    const start = new Date(call.started_at).getTime();
    const tick = () => setElapsed(Math.floor((Date.now() - start) / 1000));
    tick();
    const interval = setInterval(tick, 1000);
    return () => clearInterval(interval);
  }, [call.started_at]);

  const statusColor = call.status === "in_progress" || call.status === "answered"
    ? "var(--ok)" : call.status === "ringing"
    ? "var(--warn)" : "var(--ink-3)";

  const statusLabel = call.status === "in_progress" ? "Talking"
    : call.status === "answered" ? "Connected"
    : call.status === "ringing" ? "Ringing"
    : call.status;

  return (
    <Card padded={false}>
      {/* Accent top */}
      <div style={{ height: 4, background: statusColor, borderTopLeftRadius: "var(--r-lg)", borderTopRightRadius: "var(--r-lg)" }}/>

      <div style={{ padding: 16 }}>
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
          {call.agent_gradient && (
            <div style={{ width: 36, height: 36, borderRadius: 10, background: call.agent_gradient,
              display: "grid", placeItems: "center", fontWeight: 700, fontSize: 15, color: "#fff" }}>
              {(call.agent_name || "?").charAt(0)}
            </div>
          )}
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{call.agent_name || "AI Agent"}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{call.number || "—"}</div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
              <div style={{ width: 8, height: 8, borderRadius: "50%", background: statusColor, animation: "pulse 2s infinite" }}/>
              <span style={{ fontSize: 12, fontWeight: 500, color: statusColor }}>{statusLabel}</span>
            </div>
          </div>
        </div>

        {/* Waveform */}
        {(call.status === "in_progress" || call.status === "answered") && (
          <div style={{ margin: "8px 0" }}>
            <Waveform count={32} height={32} color={statusColor} running/>
          </div>
        )}

        {/* Footer */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 10 }}>
          <div style={{ fontSize: 20, fontWeight: 600, fontVariantNumeric: "tabular-nums", color: "var(--ink-1)" }}>
            {formatMonitorDuration(elapsed)}
          </div>
          <div style={{ flex: 1 }}/>
          {call.campaign_name && <Badge tone="gray">{call.campaign_name}</Badge>}
          <Badge tone="blue">{call.direction}</Badge>
          <Badge tone="gray">{call.mode}</Badge>
        </div>
      </div>
    </Card>
  );
}

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

window.MonitorScreen = MonitorScreen;
