// ============================================================================
// public/screens/dashboard.jsx — Real dashboard wired to /api/dashboard/summary
// ----------------------------------------------------------------------------
// Fetches all widgets in one round-trip via /summary. Shows a skeleton state
// while loading, then renders KPIs / call-volume / intent donut / hot leads /
// active campaigns / today's schedule. Each widget knows how to render an
// empty state when its data is missing — important for fresh tenants where
// none of these will have rows yet.
// ============================================================================

function DashboardScreen({ go, session }) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let alive = true;
    setLoading(true); setError(null);
    VoaisAPI.get("/api/dashboard/summary").then((r) => {
      if (!alive) return;
      if (r.ok && r.data?.ok) {
        setData(r.data);
      } else {
        setError(r.data?.msg || "Couldn't load dashboard data.");
      }
      setLoading(false);
    });
    return () => { alive = false; };
  }, []);

  if (loading) return <DashboardSkeleton/>;
  if (error)   return <DashboardError msg={error}/>;
  if (!data)   return null;

  const { kpis, callVolume, intent, hotLeads, campaigns, schedule } = data;
  const isFresh = (kpis.callsToday.value === 0 && callVolume.total === 0);

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

      {/* Empty-state banner for brand-new tenants */}
      {isFresh && (
        <Card className="empty-banner">
          <div style={{ display: "flex", alignItems: "center", gap: 14, padding: 4 }}>
            <div style={{ flexShrink: 0, color: "var(--accent)" }}><I.spark size={20}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Welcome to VoAIs Call!</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 3 }}>
                Your dashboard is empty because you haven't run any campaigns yet. Set up your first AI agent and contact list to get started.
              </div>
            </div>
            <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => go("agents")}>Create agent</Btn>
            <Btn kind="ghost"   size="sm" icon={<I.contacts size={13}/>} onClick={() => go("contacts")}>Import contacts</Btn>
          </div>
        </Card>
      )}

      {/* ── KPI strip ── */}
      <div className="kpi-grid">
        <KpiCard label="Calls today"    kpi={kpis.callsToday}      sparkColor="#3B7BFF" valueFormat={(v) => Number(v).toLocaleString("en-IN")} period="vs yesterday"/>
        <KpiCard label="Connected rate" kpi={kpis.connectedRate}   sparkColor="#00D49F" valueFormat={(v) => `${v}%`} period="vs yesterday"/>
        <KpiCard label="Hot leads"      kpi={kpis.hotLeads}        sparkColor="#FF6B3D" valueFormat={(v) => Number(v).toLocaleString("en-IN")} period="vs yesterday"/>
        <KpiCard label="Minutes used"   kpi={kpis.minutesUsed}     sparkColor="#A78BFA" valueFormat={(v) => Number(v).toLocaleString("en-IN")} period={`of ${(kpis.minutesUsed.ofTotal || 0).toLocaleString("en-IN")} included`}/>
      </div>

      {/* ── Call volume + Today's schedule ── */}
      <div className="mobile-stack" style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: "var(--gap-grid)" }}>

        {/* Call volume — last 12 months */}
        <Card>
          <CardHead
            title="Call Volume"
            subtitle="Total calls placed across all campaigns"
            right={
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                <Segmented value="Yearly" options={["Weekly", "Monthly", "Yearly", "Range"]} onChange={() => {}}/>
                <button className="topbar-icon-btn" title="Filter"><I.filter size={14}/></button>
              </div>
            }
          />
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 14 }}>
            <div style={{ fontSize: 30, fontWeight: 600, letterSpacing: "-0.02em" }} className="tabular">
              {Number(callVolume.total).toLocaleString("en-IN")}
            </div>
            {callVolume.delta && callVolume.delta !== "—" && (
              <Badge tone={callVolume.trend === "up" ? "green" : callVolume.trend === "down" ? "red" : "gray"}>
                {callVolume.trend === "up" ? "▲" : callVolume.trend === "down" ? "▼" : "●"} {callVolume.delta}
              </Badge>
            )}
            <span className="muted t-sm">vs {Number(callVolume.priorTotal).toLocaleString("en-IN")} last period</span>
          </div>
          {callVolume.total === 0
            ? <Empty title="No calls yet" sub="Once your first campaign runs, you'll see call volume trends here."/>
            : <BarChart data={callVolume.series} accentIndex={callVolume.series.length - 1} format={(v) => v >= 1000 ? Math.round(v / 1000) + "k" : v}/>
          }
        </Card>

        {/* Today's schedule */}
        <Card>
          <CardHead
            title="Today's Schedule"
            right={
              <div style={{ display: "flex", gap: 6 }}>
                <button className="topbar-icon-btn" style={{ width: 28, height: 28 }}><I.chevL size={12}/></button>
                <span style={{ fontSize: 13, fontWeight: 600, padding: "0 4px", display: "grid", alignItems: "center" }}>
                  {new Date().toLocaleDateString("en-IN", { month: "short", day: "numeric", year: "numeric" })}
                </span>
                <button className="topbar-icon-btn" style={{ width: 28, height: 28 }}><I.chevR size={12}/></button>
              </div>
            }
          />
          <MiniCalendar/>
          <div className="hr"/>
          {schedule.length === 0 ? (
            <Empty title="No campaigns scheduled" sub="Schedule a campaign to see it here."/>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {schedule.map((s, i) => {
                const sched = parseJson(s.schedule_json) || {};
                const colors = ["var(--viz-green)", "var(--accent)", "var(--viz-purple)", "var(--viz-orange)"];
                return (
                  <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "8px 10px", borderRadius: 10, background: "var(--surface-2)" }}>
                    <div style={{ width: 3, height: 30, background: colors[i % colors.length], borderRadius: 2 }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{sched.start || "—"} · {s.remaining} contacts pending</div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </Card>
      </div>

      {/* ── AI summary + Intent donut + Hot leads ── */}
      <div className="mobile-stack" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1.2fr", gap: "var(--gap-grid)" }}>

        {/* AI Insights — static for now, Phase 7 makes it real */}
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
            <div style={{ color: "var(--accent)" }}><I.spark size={16}/></div>
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>AI Summary</div>
          </div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.6, margin: "10px 0 14px" }}>
            {campaigns.length > 0 ? (
              <>Your top performer this week is <b style={{ color: "var(--ink)" }}>{campaigns[0].name}</b> with a {Math.round((campaigns[0].connected / Math.max(1, campaigns[0].dialed)) * 100)}% connect rate. The AI summary will get richer once you have more campaigns running.</>
            ) : (
              <>Once you have a few campaigns running, this card will surface actionable insights — best calling times, top objections, and which agents are converting.</>
            )}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 12 }}>
            <div style={{ background: "var(--surface-2)", padding: "10px 12px", borderRadius: 12 }}>
              <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Best calling time</div>
              <div style={{ fontSize: 15, fontWeight: 600, marginTop: 4 }}>{intent.total > 0 ? "11AM–1PM" : "—"}</div>
              <div style={{ fontSize: 11, color: intent.total > 0 ? "var(--ok)" : "var(--ink-3)", marginTop: 2 }}>{intent.total > 0 ? "+24% pickup" : "Need more data"}</div>
            </div>
            <div style={{ background: "var(--surface-2)", padding: "10px 12px", borderRadius: 12 }}>
              <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Top objection</div>
              <div style={{ fontSize: 15, fontWeight: 600, marginTop: 4 }}>{intent.total > 0 ? "Too busy" : "—"}</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{intent.total > 0 ? "32% of failed" : "Need more data"}</div>
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface)", border: "1px solid var(--line)", padding: "8px 10px", borderRadius: 999 }}>
            <I.spark size={13}/>
            <input style={{ flex: 1, background: "transparent", border: 0, outline: 0, fontSize: 12.5, color: "var(--ink)" }} placeholder="Ask anything about your campaigns…"/>
            <button className="topbar-icon-btn" style={{ width: 24, height: 24, border: 0, background: "var(--accent)", color: "white" }}><I.arrow_right size={12}/></button>
          </div>
        </Card>

        {/* Intent donut */}
        <Card>
          <CardHead title="Intent Breakdown" right={
            <Segmented value="30d" options={[{ value: "7d", label: "7d" }, { value: "30d", label: "30d" }, { value: "90d", label: "90d" }]} onChange={() => {}}/>
          }/>
          {intent.total === 0 ? (
            <Empty title="No call data yet" sub="Intent insights appear as your agents complete calls."/>
          ) : (
            <>
              <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 18, alignItems: "center" }}>
                <Donut
                  data={intent.segments}
                  size={150}
                  thickness={20}
                  center={
                    <div>
                      <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }} className="tabular">
                        {Number(intent.total).toLocaleString("en-IN")}
                      </div>
                      <div style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 2 }}>Total calls</div>
                    </div>
                  }
                />
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {intent.segments.map((x, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: x.color }}/>
                      <span style={{ flex: 1, color: "var(--ink-2)" }}>{x.label}</span>
                      <span className="tabular bold">{x.value}%</span>
                    </div>
                  ))}
                </div>
              </div>
              <div style={{ marginTop: 14, padding: 10, background: "var(--surface-2)", borderRadius: 10, fontSize: 11.5, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 8 }}>
                <I.alert size={14}/>
                <span>Hot leads share is{" "}
                  <span style={{ color: "var(--ok)", fontWeight: 600 }}>
                    {intent.segments[0].value}%
                  </span> of all calls.
                </span>
              </div>
            </>
          )}
        </Card>

        {/* Hot leads list */}
        <Card padded={false}>
          <div style={{ padding: "var(--pad-card) var(--pad-card) 0", display: "flex", alignItems: "center", gap: 8 }}>
            <I.fire size={15} stroke="var(--viz-orange)"/>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>Hot Leads</h3>
            <span className="badge yellow" style={{ marginLeft: 4 }}>{hotLeads.length} new</span>
            <div style={{ flex: 1 }}/>
            <button className="topbar-icon-btn" style={{ width: 28, height: 28 }} onClick={() => go("history")} title="View all"><I.arrow_up_right size={14}/></button>
          </div>
          <div style={{ padding: "10px 8px 12px", maxHeight: 340, overflowY: "auto" }}>
            {hotLeads.length === 0 ? (
              <div style={{ padding: "24px 12px" }}>
                <Empty title="No hot leads yet" sub="High-score leads from your campaigns will surface here."/>
              </div>
            ) : (
              hotLeads.map((l) => (
                <div key={l.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 12px", borderRadius: 10 }} className="hot-lead">
                  <Avatar name={l.contact_name || "?"} size={32}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{l.contact_name || "Unknown"}</div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {l.interest || "—"} · {l.campaign_name || "—"}
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ok)" }}>{l.lead_score}</div>
                    <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{timeAgo(l.started_at)}</div>
                  </div>
                </div>
              ))
            )}
          </div>
          <div style={{ borderTop: "1px solid var(--line)", padding: "10px var(--pad-card)" }}>
            <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "space-between" }} onClick={() => go("history")}>
              View all leads <I.arrow_up_right size={13}/>
            </button>
          </div>
        </Card>
      </div>

      {/* ── Active campaigns table ── */}
      <Card padded={false}>
        <div style={{ padding: "16px 20px", display: "flex", alignItems: "center", gap: 10 }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>Active campaigns</h3>
          {campaigns.length > 0 && <Badge tone="green" dot>{campaigns.length} running</Badge>}
          <div style={{ flex: 1 }}/>
          <Btn kind="ghost"   size="sm" icon={<I.filter size={13}/>}>Filter</Btn>
          <Btn kind="primary" size="sm" icon={<I.plus    size={13}/>} onClick={() => go("campaigns")}>New campaign</Btn>
        </div>
        {campaigns.length === 0 ? (
          <div style={{ padding: "24px 20px" }}>
            <Empty title="No active campaigns" sub="Create your first campaign to start running calls."/>
          </div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>Campaign</th>
                <th>Agent</th>
                <th>Progress</th>
                <th>Connected</th>
                <th>Hot leads</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {campaigns.map((c) => {
                const pct = c.contacts > 0 ? Math.round((c.dialed / c.contacts) * 100) : 0;
                return (
                  <tr key={c.id} style={{ cursor: "pointer" }} onClick={() => go("campaigns")}>
                    <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>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <Avatar name={c.agent_name || "?"} size={24}/>
                        <span>{c.agent_name || "—"}</span>
                      </div>
                    </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.contacts).toLocaleString("en-IN")}
                        </span>
                      </div>
                    </td>
                    <td className="tabular bold">{c.connect_rate ? `${Math.round(c.connect_rate)}%` : "—"}</td>
                    <td><span className="badge green">{c.hot}</span></td>
                    <td><Badge tone="green" dot>{c.status}</Badge></td>
                    <td style={{ width: 30 }}><button className="topbar-icon-btn" style={{ width: 28, height: 28, border: 0 }}><I.more size={14}/></button></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </Card>

    </div>
  );
}

// ── KPI card ───────────────────────────────────────────────────────────
function KpiCard({ label, kpi, sparkColor, valueFormat, period }) {
  if (!kpi) return null;
  const trendSymbol = kpi.trend === "up" ? "▲" : kpi.trend === "down" ? "▼" : "●";
  return (
    <div className="card kpi-card">
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div className="kpi-label">{label}</div>
        {kpi.spark && <Sparkline data={kpi.spark} color={sparkColor} width={60} height={20}/>}
      </div>
      <div className="kpi-value tabular">{valueFormat ? valueFormat(kpi.value) : kpi.value}</div>
      <div className="kpi-foot">
        <span className={`kpi-trend ${kpi.trend === "down" ? "down" : ""}`}>
          {trendSymbol} {kpi.delta}
        </span>
        <span>{period}</span>
      </div>
    </div>
  );
}

// ── Mini calendar — UI-only for now ────────────────────────────────────
function MiniCalendar() {
  const now = new Date();
  const today = now.getDate();
  const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4, fontSize: 11.5 }}>
      {["M", "T", "W", "T", "F", "S", "S"].map((d, i) => (
        <div key={i} style={{ textAlign: "center", color: "var(--ink-3)", padding: "4px 0", fontWeight: 600 }}>{d}</div>
      ))}
      {Array.from({ length: daysInMonth }).map((_, i) => {
        const day = i + 1;
        const isToday = day === today;
        const isPast  = day < today;
        return (
          <div
            key={i}
            className="tabular"
            style={{
              textAlign: "center", padding: "7px 0", fontSize: 12.5, borderRadius: 8,
              background: isToday ? "var(--accent)" : "transparent",
              color: isToday ? "white" : isPast ? "var(--ink-3)" : "var(--ink)",
              fontWeight: isToday ? 600 : 500,
              cursor: "pointer",
            }}
          >
            {day}
          </div>
        );
      })}
    </div>
  );
}

// ── Skeleton (loading state) ───────────────────────────────────────────
function DashboardSkeleton() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div className="kpi-grid">
        {[0,1,2,3].map((i) => <div key={i} className="card kpi-card skel-block" style={{ minHeight: 110 }}/>)}
      </div>
      <div className="mobile-stack" style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: "var(--gap-grid)" }}>
        <div className="card skel-block" style={{ minHeight: 320 }}/>
        <div className="card skel-block" style={{ minHeight: 320 }}/>
      </div>
      <div className="card skel-block" style={{ minHeight: 240 }}/>
    </div>
  );
}

function DashboardError({ msg }) {
  return (
    <Card>
      <div style={{ padding: 20, textAlign: "center" }}>
        <div style={{ color: "var(--err)", marginBottom: 8 }}><I.alert size={24}/></div>
        <div style={{ fontWeight: 600, marginBottom: 6 }}>Couldn't load dashboard</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{msg}</div>
        <Btn kind="primary" size="sm" onClick={() => location.reload()} style={{ marginTop: 16 }}>Retry</Btn>
      </div>
    </Card>
  );
}

// ── Utilities ──────────────────────────────────────────────────────────
function timeAgo(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  const s = Math.max(1, Math.floor((Date.now() - d.getTime()) / 1000));
  if (s < 60)       return s + "s ago";
  if (s < 3600)     return Math.floor(s / 60) + " min ago";
  if (s < 86400)    return Math.floor(s / 3600) + " hr ago";
  return Math.floor(s / 86400) + " d ago";
}

function parseJson(v) {
  if (v === null || v === undefined) return null;
  if (typeof v === "object") return v;
  try { return JSON.parse(v); } catch (_) { return null; }
}

window.DashboardScreen = DashboardScreen;
