// ============================================================================
// public/screens/campaigns.jsx — Campaigns list + detail + create wizard
// ----------------------------------------------------------------------------
// Three views toggle in one component:
//   • list    → CampaignsList
//   • detail  → CampaignDetail
//   • wizard  → CampaignWizard (4 steps)
// Status changes (start/pause/cancel) go through dedicated POST endpoints.
// ============================================================================

function CampaignsScreen({ go, session }) {
  const [view, setView]         = React.useState("list");  // list | detail | wizard
  const [selectedId, setSelectedId] = React.useState(null);

  const openDetail = (id) => { setSelectedId(id); setView("detail"); };
  const back       = () => setView("list");

  if (view === "wizard") return <CampaignWizard onDone={(id) => { setSelectedId(id); setView("detail"); }} onCancel={back}/>;
  if (view === "detail" && selectedId) return <CampaignDetail id={selectedId} onBack={back} go={go}/>;
  return <CampaignsList onOpenDetail={openDetail} onNew={() => setView("wizard")} go={go}/>;
}

// ── List view ──────────────────────────────────────────────────────────
function CampaignsList({ onOpenDetail, onNew, go }) {
  const [campaigns, setCampaigns] = React.useState(null);
  const [stats, setStats]         = React.useState(null);
  const [filter, setFilter]       = React.useState("all");
  const [q, setQ]                 = React.useState("");
  const [err, setErr]             = React.useState(null);

  const reload = React.useCallback(() => {
    setErr(null);
    const params = new URLSearchParams();
    if (filter !== "all") params.append("status", filter);
    if (q.trim())         params.append("q", q.trim());
    Promise.all([
      VoaisAPI.get("/api/campaigns?" + params.toString()),
      VoaisAPI.get("/api/campaigns/stats"),
    ]).then(([list, st]) => {
      if (list.ok && list.data?.ok) setCampaigns(list.data.campaigns);
      else                          setErr(list.data?.msg || "Failed to load campaigns.");
      if (st.ok && st.data?.ok)     setStats(st.data.stats);
    });
  }, [filter, q]);

  React.useEffect(() => {
    const id = setTimeout(reload, q ? 250 : 0);
    return () => clearTimeout(id);
  }, [reload, q]);

  const handleStatusChange = async (id, action) => {
    const r = await VoaisAPI.post(`/api/campaigns/${id}/${action}`);
    if (!r.ok) { alert(r.data?.msg || "Action failed."); return; }
    reload();
  };

  if (campaigns === null && !err) return <DashboardSkeleton/>;

  const counts = stats || { active: 0, scheduled: 0, finished: 0, callsPending: 0, avgConnectRate: null, hotConversion: null };

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

      {/* Top KPIs */}
      <div className="kpi-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
        <Card className="kpi-card">
          <div className="kpi-label">Active campaigns</div>
          <div className="kpi-value tabular" style={{ marginTop: 8 }}>{Number(counts.active).toLocaleString("en-IN")}</div>
          <div className="kpi-foot"><span style={{ color: "var(--viz-green)" }}>●</span> {counts.scheduled} scheduled</div>
        </Card>
        <Card className="kpi-card">
          <div className="kpi-label">Calls pending</div>
          <div className="kpi-value tabular" style={{ marginTop: 8 }}>{Number(counts.callsPending).toLocaleString("en-IN")}</div>
          <div className="kpi-foot"><span style={{ color: "var(--accent)" }}>●</span> across active campaigns</div>
        </Card>
        <Card className="kpi-card">
          <div className="kpi-label">Avg connect rate</div>
          <div className="kpi-value tabular" style={{ marginTop: 8 }}>{counts.avgConnectRate != null ? `${counts.avgConnectRate}%` : "—"}</div>
          <div className="kpi-foot"><span style={{ color: "var(--viz-purple)" }}>●</span> across all campaigns</div>
        </Card>
        <Card className="kpi-card">
          <div className="kpi-label">Hot lead conversion</div>
          <div className="kpi-value tabular" style={{ marginTop: 8 }}>{counts.hotConversion != null ? `${counts.hotConversion}%` : "—"}</div>
          <div className="kpi-foot"><span style={{ color: "var(--viz-orange)" }}>●</span> of dialed calls</div>
        </Card>
      </div>

      {/* Action bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
        <Tabs
          value={filter}
          options={[
            { value: "all",        label: "All" },
            { value: "running",    label: "Running" },
            { value: "scheduled",  label: "Scheduled" },
            { value: "paused",     label: "Paused" },
            { value: "completed",  label: "Completed" },
            { value: "draft",      label: "Draft" },
          ]}
          onChange={setFilter}
        />
        <div className="search-box" style={{ maxWidth: 280 }}>
          <I.search size={14}/>
          <input placeholder="Search by name or code…" value={q} onChange={(e) => setQ(e.target.value)}/>
        </div>
        <div style={{ flex: 1 }}/>
        <Btn kind="primary" icon={<I.plus size={14}/>} onClick={onNew}>New campaign</Btn>
      </div>

      {err && <div className="auth-banner err"><I.alert size={14}/><span>{err}</span></div>}

      {/* Table or empty state */}
      {campaigns?.length === 0 ? (
        <Card>
          <div style={{ padding: "40px 24px", textAlign: "center", maxWidth: 520, margin: "0 auto" }}>
            <div style={{ width: 64, height: 64, borderRadius: 16, margin: "0 auto 20px", display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)" }}>
              <I.campaigns size={28}/>
            </div>
            <h2 style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em", margin: "14px 0 10px" }}>
              {q || filter !== "all" ? "No campaigns match" : "No campaigns yet"}
            </h2>
            <p style={{ color: "var(--ink-3)", fontSize: 13.5, lineHeight: 1.6, margin: "0 0 20px" }}>
              {q || filter !== "all"
                ? "Try a different filter or search term."
                : "A campaign points an AI agent at a contact list and runs calls on a schedule. Set one up to launch your first batch."}
            </p>
            {!q && filter === "all" && <Btn kind="primary" icon={<I.plus size={14}/>} onClick={onNew}>Create your first campaign</Btn>}
          </div>
        </Card>
      ) : (
        <Card padded={false}>
          <table className="table">
            <thead>
              <tr>
                <th>Campaign</th>
                <th>Agent</th>
                <th>Progress</th>
                <th>Connect rate</th>
                <th>Hot leads</th>
                <th>Status</th>
                <th style={{ width: 120 }}></th>
              </tr>
            </thead>
            <tbody>
              {campaigns?.map((c) => {
                const pct = c.total > 0 ? Math.round((c.dialed / c.total) * 100) : 0;
                return (
                  <tr key={c.id} style={{ cursor: "pointer" }} onClick={() => onOpenDetail(c.id)}>
                    <td>
                      <div style={{ fontWeight: 600 }}>{c.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{c.industry || "—"} · {c.code}</div>
                    </td>
                    <td>
                      {c.agent_name ? (
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          <Avatar name={c.agent_name} size={24}/>
                          <span style={{ fontSize: 13 }}>{c.agent_name}</span>
                        </div>
                      ) : <span style={{ color: "var(--ink-3)" }}>—</span>}
                    </td>
                    <td style={{ minWidth: 180 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ flex: 1, height: 6, background: "var(--surface-3)", borderRadius: 4, overflow: "hidden" }}>
                          <div style={{ width: `${pct}%`, height: "100%", background: "var(--accent)", borderRadius: 4 }}/>
                        </div>
                        <span className="tabular t-xs muted" style={{ minWidth: 80 }}>
                          {Number(c.dialed).toLocaleString("en-IN")} / {Number(c.total).toLocaleString("en-IN")}
                        </span>
                      </div>
                    </td>
                    <td className="tabular bold">{c.connect_rate != null ? `${Math.round(c.connect_rate)}%` : "—"}</td>
                    <td><span className="badge green">{Number(c.hot_leads || 0)}</span></td>
                    <td>
                      <Badge tone={statusTone(c.status)} dot>{c.status}</Badge>
                    </td>
                    <td onClick={(e) => e.stopPropagation()}>
                      <CampaignRowActions campaign={c} onAction={handleStatusChange}/>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      )}
    </div>
  );
}

function statusTone(s) {
  if (s === "running" || s === "active")   return "green";
  if (s === "paused")                       return "yellow";
  if (s === "completed")                    return "blue";
  if (s === "scheduled")                    return "blue";
  if (s === "cancelled" || s === "failed")  return "red";
  return "gray";
}

function CampaignRowActions({ campaign, onAction }) {
  const c = campaign;
  if (c.status === "draft" || c.status === "scheduled" || c.status === "paused") {
    return <Btn kind="ghost" size="sm" icon={<I.play size={12}/>} onClick={() => onAction(c.id, "start")}>Start</Btn>;
  }
  if (c.status === "running") {
    return <Btn kind="ghost" size="sm" icon={<I.pause size={12}/>} onClick={() => onAction(c.id, "pause")}>Pause</Btn>;
  }
  return null;
}

// ── Detail view ─────────────────────────────────────────────────────────
function CampaignDetail({ id, onBack, go }) {
  const [data, setData] = React.useState(null);
  const [err, setErr]   = React.useState(null);

  const reload = React.useCallback(() => {
    VoaisAPI.get(`/api/campaigns/${id}`).then((r) => {
      if (r.ok && r.data?.ok) setData(r.data);
      else                    setErr(r.data?.msg || "Couldn't load campaign.");
    });
  }, [id]);
  React.useEffect(reload, [reload]);

  const handleAction = async (action) => {
    const r = await VoaisAPI.post(`/api/campaigns/${id}/${action}`);
    if (!r.ok) { alert(r.data?.msg || "Action failed."); return; }
    reload();
  };
  const handleDelete = async () => {
    if (!confirm("Delete this campaign? This cannot be undone.")) return;
    const r = await VoaisAPI.del(`/api/campaigns/${id}`);
    if (!r.ok) { alert(r.data?.msg || "Delete failed."); return; }
    onBack();
  };

  if (!data && !err) return <DashboardSkeleton/>;
  if (err) return <DashboardError msg={err}/>;

  const c = data.campaign;
  const pct = c.total > 0 ? Math.round((c.dialed / c.total) * 100) : 0;
  const schedule = parseScheduleJson(c.schedule_json);

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

      {/* Header bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <Btn kind="ghost" size="sm" icon={<I.chevL size={13}/>} onClick={onBack}>Back</Btn>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{c.code} · {c.industry || "—"}</div>
          <h1 style={{ margin: "2px 0 0", fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{c.name}</h1>
        </div>
        <Badge tone={statusTone(c.status)} dot>{c.status}</Badge>
        {(c.status === "draft" || c.status === "scheduled" || c.status === "paused") &&
          <Btn kind="primary" size="sm" icon={<I.play size={12}/>} onClick={() => handleAction("start")}>Start</Btn>}
        {c.status === "running" &&
          <Btn kind="ghost"   size="sm" icon={<I.pause size={12}/>} onClick={() => handleAction("pause")}>Pause</Btn>}
        {c.status !== "cancelled" && c.status !== "completed" &&
          <Btn kind="ghost"   size="sm" onClick={() => handleAction("cancel")}>Cancel</Btn>}
        <Btn kind="ghost" size="sm" onClick={handleDelete} style={{ color: "var(--err)" }} icon={<I.trash size={13}/>}/>
      </div>

      {/* Progress strip */}
      <Card>
        <div style={{ display: "flex", alignItems: "baseline", gap: 16, marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Progress</div>
            <div style={{ fontSize: 26, fontWeight: 600 }} className="tabular">
              {Number(c.dialed).toLocaleString("en-IN")} <span style={{ color: "var(--ink-3)", fontSize: 14, fontWeight: 500 }}>/ {Number(c.total).toLocaleString("en-IN")}</span>
            </div>
          </div>
          <div style={{ flex: 1 }}/>
          <div style={{ display: "flex", gap: 24 }}>
            <Stat2 label="Connected"   value={Number(c.connected || 0).toLocaleString("en-IN")} color="var(--viz-green)"/>
            <Stat2 label="Hot leads"   value={Number(c.hot_leads  || 0).toLocaleString("en-IN")} color="var(--viz-orange)"/>
            <Stat2 label="Minutes"     value={Number(c.minutes_used || 0).toLocaleString("en-IN")} color="var(--accent)"/>
            <Stat2 label="Connect rate" value={c.connect_rate != null ? `${Math.round(c.connect_rate)}%` : "—"} color="var(--viz-purple)"/>
          </div>
        </div>
        <div style={{ height: 8, background: "var(--surface-3)", borderRadius: 4, overflow: "hidden" }}>
          <div style={{ width: `${pct}%`, height: "100%", background: "var(--accent)", borderRadius: 4 }}/>
        </div>
      </Card>

      {/* Configuration + schedule */}
      <div className="mobile-stack" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--gap-grid)" }}>
        <Card>
          <CardHead title="Configuration"/>
          <table className="table" style={{ marginTop: 4 }}>
            <tbody>
              <ConfigRow k="Agent" v={c.agent_name ? <><Avatar name={c.agent_name} size={20}/> <span style={{ marginLeft: 6 }}>{c.agent_name}</span></> : "—"}/>
              <ConfigRow k="Phonebook" v={c.phonebook_name || "—"}/>
              <ConfigRow k="Direction" v={c.direction}/>
              <ConfigRow k="Mode" v={c.mode}/>
              <ConfigRow k="Concurrent calls" v={c.concurrent_calls}/>
              <ConfigRow k="Max attempts" v={c.max_attempts}/>
              <ConfigRow k="Retry delay" v={`${c.retry_delay_min} min`}/>
              <ConfigRow k="Created" v={new Date(c.created_at).toLocaleString("en-IN", { dateStyle: "medium", timeStyle: "short" })}/>
              {c.started_at && <ConfigRow k="Started" v={new Date(c.started_at).toLocaleString("en-IN", { dateStyle: "medium", timeStyle: "short" })}/>}
            </tbody>
          </table>
        </Card>

        <Card>
          <CardHead title="Schedule"/>
          {schedule ? (
            <div style={{ marginTop: 10 }}>
              <table className="table">
                <tbody>
                  <ConfigRow k="Calling days" v={(schedule.days || []).join(", ").toUpperCase() || "—"}/>
                  <ConfigRow k="Calling hours" v={`${schedule.start || "—"} – ${schedule.end || "—"}`}/>
                  <ConfigRow k="Timezone" v={schedule.tz || "Asia/Kolkata"}/>
                  {c.start_date && <ConfigRow k="Window starts" v={new Date(c.start_date).toLocaleDateString("en-IN")}/>}
                  {c.end_date   && <ConfigRow k="Window ends"   v={new Date(c.end_date  ).toLocaleDateString("en-IN")}/>}
                </tbody>
              </table>
            </div>
          ) : (
            <div style={{ marginTop: 16 }}>
              <Empty title="No schedule set" subtitle="This campaign will dial whenever it's running."/>
            </div>
          )}
        </Card>
      </div>

      {/* Recent calls */}
      <Card padded={false}>
        <div style={{ padding: "14px 20px", display: "flex", alignItems: "center", gap: 10 }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>Recent calls</h3>
          <Badge tone="gray">{data.recentCalls.length}</Badge>
          <div style={{ flex: 1 }}/>
          {data.recentCalls.length > 0 && <Btn kind="ghost" size="sm" onClick={() => go("history")}>View all <I.arrow_up_right size={13}/></Btn>}
        </div>
        {data.recentCalls.length === 0 ? (
          <div style={{ padding: "30px 20px" }}>
            <Empty title="No calls yet" subtitle="Once this campaign starts running, the most recent calls will appear here."/>
          </div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>Time</th>
                <th>Contact</th>
                <th>Phone</th>
                <th>Outcome</th>
                <th>Score</th>
                <th>Duration</th>
              </tr>
            </thead>
            <tbody>
              {data.recentCalls.map((rc) => (
                <tr key={rc.id}>
                  <td style={{ fontSize: 12, color: "var(--ink-3)" }}>{new Date(rc.started_at).toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit" })}</td>
                  <td style={{ fontWeight: 600 }}>{rc.contact_name || "—"}</td>
                  <td style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{rc.contact_phone || "—"}</td>
                  <td>{rc.outcome ? <Badge tone={outcomeTone(rc.outcome)} dot>{rc.outcome.replace(/_/g, " ")}</Badge> : "—"}</td>
                  <td className="tabular">{rc.lead_score ?? "—"}</td>
                  <td className="tabular">{rc.duration_s ? formatDuration(rc.duration_s) : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  );
}

function Stat2({ label, value, color }) {
  return (
    <div>
      <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}><span style={{ color }}>●</span> {label}</div>
      <div style={{ fontSize: 20, fontWeight: 600, marginTop: 2 }} className="tabular">{value}</div>
    </div>
  );
}
function ConfigRow({ k, v }) {
  return (
    <tr>
      <td style={{ color: "var(--ink-3)", width: 140, fontSize: 12.5 }}>{k}</td>
      <td style={{ fontSize: 13 }}>{v}</td>
    </tr>
  );
}
function outcomeTone(o) {
  if (o === "talked" || o === "answered")       return "green";
  if (o === "voicemail")                         return "yellow";
  if (o === "no_answer" || o === "busy")         return "gray";
  if (o === "failed" || o === "instant_hangup")  return "red";
  return "gray";
}
function formatDuration(s) {
  s = Number(s) || 0;
  const m = Math.floor(s / 60), sec = s % 60;
  return `${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`;
}
function parseScheduleJson(v) {
  if (!v) return null;
  if (typeof v === "object") return v;
  try { return JSON.parse(v); } catch (_) { return null; }
}

// ── Wizard ──────────────────────────────────────────────────────────────
function CampaignWizard({ onDone, onCancel }) {
  const STEPS = ["Basics", "Agent", "Contacts", "Schedule"];
  const [step, setStep]   = React.useState(0);
  const [form, setForm]   = React.useState({
    name: "", industry: "",
    agent_id: "", phonebook_id: "",
    concurrent_calls: 1, max_attempts: 2, retry_delay_min: 60, delay_ms: 2000,
    schedule_json: { days: ["mon","tue","wed","thu","fri"], start: "10:00", end: "19:00", tz: "Asia/Kolkata" },
  });
  const [agents, setAgents]         = React.useState([]);
  const [phonebooks, setPhonebooks] = React.useState([]);
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr]               = React.useState(null);

  React.useEffect(() => {
    VoaisAPI.get("/api/agents").then((r) => {
      if (r.ok && r.data?.ok) {
        const active = r.data.agents.filter((a) => a.status === "active");
        setAgents(active);
      }
    });
    VoaisAPI.get("/api/contacts/phonebooks").then((r) => {
      if (r.ok && r.data?.ok) setPhonebooks(r.data.phonebooks);
    });
  }, []);

  const next = () => {
    setErr(null);
    if (step === 0 && !form.name.trim()) return setErr("Give your campaign a name.");
    if (step === 1 && !form.agent_id)    return setErr("Pick an agent (or activate one in the Agents page).");
    if (step === 2 && !form.phonebook_id) return setErr("Pick a phonebook (or upload contacts first).");
    if (step < STEPS.length - 1) setStep(step + 1);
    else                          submit();
  };
  const back = () => { setErr(null); if (step > 0) setStep(step - 1); };

  const submit = async () => {
    setSubmitting(true);
    setErr(null);
    const r = await VoaisAPI.post("/api/campaigns", {
      name: form.name.trim(),
      industry: form.industry || null,
      agent_id: Number(form.agent_id),
      phonebook_id: Number(form.phonebook_id),
      concurrent_calls: Number(form.concurrent_calls),
      max_attempts: Number(form.max_attempts),
      retry_delay_min: Number(form.retry_delay_min),
      delay_ms: Number(form.delay_ms),
      schedule_json: form.schedule_json,
    });
    setSubmitting(false);
    if (r.ok) onDone(r.data.campaignId);
    else      setErr(r.data?.msg || "Failed to create campaign.");
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)", maxWidth: 720, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Btn kind="ghost" size="sm" icon={<I.chevL size={13}/>} onClick={onCancel}>Cancel</Btn>
        <div style={{ flex: 1 }}/>
        <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>Step {step + 1} of {STEPS.length}</span>
      </div>

      {/* Step indicator */}
      <div style={{ display: "flex", gap: 8 }}>
        {STEPS.map((s, i) => (
          <div key={s} style={{ flex: 1 }}>
            <div style={{
              height: 4, borderRadius: 2,
              background: i <= step ? "var(--accent)" : "var(--surface-3)",
              transition: "background 0.2s",
            }}/>
            <div style={{ fontSize: 11.5, color: i === step ? "var(--ink)" : "var(--ink-3)", marginTop: 6, fontWeight: i === step ? 600 : 500 }}>
              {s}
            </div>
          </div>
        ))}
      </div>

      <Card>
        {err && <div className="auth-banner err" style={{ marginBottom: 14 }}><I.alert size={14}/><span>{err}</span></div>}

        {/* Step 0 — Basics */}
        {step === 0 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Campaign basics</h2>
            <p style={{ margin: 0, color: "var(--ink-3)", fontSize: 13 }}>Just a name and (optionally) an industry tag so it's easy to find later.</p>
            <Field label="Name *">
              <input className="input" autoFocus placeholder="e.g. Mercedes GLE — Test Drive Lucknow" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}/>
            </Field>
            <Field label="Industry">
              <select className="select" value={form.industry} onChange={(e) => setForm({ ...form, industry: e.target.value })}>
                <option value="">—</option>
                <option value="Automotive">Automotive</option>
                <option value="EdTech">EdTech</option>
                <option value="Real Estate">Real Estate</option>
                <option value="BFSI">BFSI</option>
                <option value="Healthcare">Healthcare</option>
                <option value="Government">Government</option>
                <option value="MSME">MSME</option>
                <option value="Retail">Retail</option>
                <option value="Other">Other</option>
              </select>
            </Field>
          </div>
        )}

        {/* Step 1 — Agent */}
        {step === 1 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Pick an AI agent</h2>
            <p style={{ margin: 0, color: "var(--ink-3)", fontSize: 13 }}>Choose the persona that will handle calls. Only active agents are shown.</p>
            {agents.length === 0 ? (
              <Empty title="No active agents" subtitle="Create or activate an agent on the Agents page first."/>
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 12 }}>
                {agents.map((a) => (
                  <div
                    key={a.id}
                    onClick={() => setForm({ ...form, agent_id: a.id })}
                    style={{
                      padding: 14, borderRadius: 12, cursor: "pointer",
                      border: `2px solid ${form.agent_id === a.id ? "var(--accent)" : "var(--line)"}`,
                      background: form.agent_id === a.id ? "var(--accent-soft)" : "var(--surface)",
                      transition: "all 0.12s",
                    }}
                  >
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 10, background: a.avatar_gradient || "var(--accent)", display: "grid", placeItems: "center", color: "white", fontWeight: 700 }}>
                        {(a.name || "?").charAt(0).toUpperCase()}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 14 }}>{a.name}</div>
                        <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{a.language} · {a.llm_provider}</div>
                      </div>
                    </div>
                    {a.role && <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 8, lineHeight: 1.5 }}>{a.role}</div>}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Step 2 — Contacts */}
        {step === 2 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Pick contacts</h2>
            <p style={{ margin: 0, color: "var(--ink-3)", fontSize: 13 }}>Choose the phonebook this campaign will dial through.</p>
            {phonebooks.length === 0 ? (
              <Empty title="No phonebooks" subtitle="Go to Contacts and upload a CSV first."/>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {phonebooks.map((pb) => (
                  <div
                    key={pb.id}
                    onClick={() => setForm({ ...form, phonebook_id: pb.id })}
                    style={{
                      padding: "12px 16px", borderRadius: 10, cursor: "pointer",
                      border: `2px solid ${form.phonebook_id === pb.id ? "var(--accent)" : "var(--line)"}`,
                      background: form.phonebook_id === pb.id ? "var(--accent-soft)" : "var(--surface)",
                      display: "flex", alignItems: "center", gap: 12,
                    }}
                  >
                    <I.template size={18} stroke={form.phonebook_id === pb.id ? "var(--accent)" : "var(--ink-3)"}/>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{pb.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{Number(pb.count).toLocaleString("en-IN")} contacts</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Step 3 — Schedule */}
        {step === 3 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Schedule & retries</h2>
            <p style={{ margin: 0, color: "var(--ink-3)", fontSize: 13 }}>Pick the days and hours your agent should dial. TRAI guidelines: 09:00–21:00 local time.</p>

            <Field label="Calling days">
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {[
                  ["mon","Mon"], ["tue","Tue"], ["wed","Wed"], ["thu","Thu"],
                  ["fri","Fri"], ["sat","Sat"], ["sun","Sun"],
                ].map(([id, label]) => {
                  const on = (form.schedule_json.days || []).includes(id);
                  return (
                    <button
                      key={id} type="button"
                      className={`btn ${on ? "btn-primary" : "btn-ghost"}`}
                      style={{ minWidth: 64 }}
                      onClick={() => {
                        const days = on
                          ? form.schedule_json.days.filter((d) => d !== id)
                          : [...form.schedule_json.days, id];
                        setForm({ ...form, schedule_json: { ...form.schedule_json, days } });
                      }}
                    >
                      {label}
                    </button>
                  );
                })}
              </div>
            </Field>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Start time">
                <input className="input" type="time" value={form.schedule_json.start} onChange={(e) => setForm({ ...form, schedule_json: { ...form.schedule_json, start: e.target.value } })}/>
              </Field>
              <Field label="End time">
                <input className="input" type="time" value={form.schedule_json.end} onChange={(e) => setForm({ ...form, schedule_json: { ...form.schedule_json, end: e.target.value } })}/>
              </Field>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
              <Field label="Concurrent calls" hint="How many lines at once.">
                <input className="input" type="number" min={1} max={50} value={form.concurrent_calls} onChange={(e) => setForm({ ...form, concurrent_calls: e.target.value })}/>
              </Field>
              <Field label="Max attempts" hint="Per contact.">
                <input className="input" type="number" min={1} max={10} value={form.max_attempts} onChange={(e) => setForm({ ...form, max_attempts: e.target.value })}/>
              </Field>
              <Field label="Retry delay (min)">
                <input className="input" type="number" min={1} max={1440} value={form.retry_delay_min} onChange={(e) => setForm({ ...form, retry_delay_min: e.target.value })}/>
              </Field>
            </div>
          </div>
        )}

        <div style={{ display: "flex", gap: 8, justifyContent: "space-between", marginTop: 18 }}>
          <Btn kind="ghost" disabled={step === 0} onClick={back}>Back</Btn>
          <Btn kind="primary" onClick={next} disabled={submitting}>
            {step === STEPS.length - 1
              ? (submitting ? "Creating…" : "Create campaign")
              : "Continue"}
          </Btn>
        </div>
      </Card>
    </div>
  );
}

window.CampaignsScreen = CampaignsScreen;
