// ============================================================================
// public/screens/analytics.jsx — Analytics Dashboard (Phase 7A)
// ============================================================================

function AnalyticsScreen() {
  const [overview, setOverview] = React.useState(null);
  const [callData, setCallData] = React.useState([]);
  const [agents, setAgents]     = React.useState([]);
  const [intents, setIntents]   = React.useState([]);
  const [quality, setQuality]   = React.useState([]);
  const [range, setRange]       = React.useState("30d");

  const load = React.useCallback(async () => {
    const [ov, cd, ag, it, ql] = await Promise.all([
      VoaisAPI.get("/api/analytics/overview"),
      VoaisAPI.get("/api/analytics/calls?range=" + range),
      VoaisAPI.get("/api/analytics/agents"),
      VoaisAPI.get("/api/analytics/intents"),
      VoaisAPI.get("/api/analytics/quality"),
    ]);
    if (ov.ok) setOverview(ov.data.overview);
    if (cd.ok) setCallData(cd.data.data);
    if (ag.ok) setAgents(ag.data.agents);
    if (it.ok) setIntents(it.data.intents);
    if (ql.ok) setQuality(ql.data.quality);
  }, [range]);
  React.useEffect(() => { load(); }, [load]);

  if (!overview) return <DashboardSkeleton/>;

  const intentColors = { interested: "var(--ok)", not_interested: "var(--err)", unclear: "var(--warn)", callback: "var(--accent)", unknown: "var(--ink-3)" };
  const qualColors = { hot: "#E24B4A", warm: "#EF9F27", cold: "#378ADD", unscored: "var(--ink-3)" };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      {/* KPI row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
        <AKpi label="Calls today" value={overview.today.calls}/>
        <AKpi label="Connect rate" value={overview.today.connect_rate + "%"} color="var(--ok)"/>
        <AKpi label="Hot leads today" value={overview.today.hot} color="var(--err)"/>
        <AKpi label="Minutes today" value={overview.today.minutes}/>
        <AKpi label="7d avg score" value={overview.week.avg_score}/>
        <AKpi label="30d calls" value={overview.month.calls}/>
        <AKpi label="All-time minutes" value={overview.all.minutes.toLocaleString("en-IN")}/>
      </div>

      {/* Range selector + Call volume chart */}
      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
          <div style={{ fontSize: 14, fontWeight: 600, flex: 1 }}>Call volume</div>
          <Segmented value={range} options={[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"12m",label:"12m"}]} onChange={setRange}/>
        </div>
        {callData.length > 0 ? (
          <BarChart data={callData.map(d => ({ label: String(d.period).slice(-5), value: +d.total }))} height={200}/>
        ) : <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No data for this period.</div>}
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--gap-grid)" }}>
        {/* Intent breakdown */}
        <Card>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Intent breakdown (30d)</div>
          {intents.length > 0 ? (
            <Donut size={160} thickness={24} data={intents.map(i => ({ value: +i.count, color: intentColors[i.interest] || "var(--ink-3)" }))}
              center={<div><div style={{ fontSize: 22, fontWeight: 700 }}>{intents.reduce((a,b)=>a+(+b.count),0)}</div><div style={{ fontSize: 11, color: "var(--ink-3)" }}>calls</div></div>}/>
          ) : null}
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 14 }}>
            {intents.map(i => (
              <div key={i.interest} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13 }}>
                <div style={{ width: 10, height: 10, borderRadius: 3, background: intentColors[i.interest] || "var(--ink-3)" }}/>
                <span style={{ flex: 1 }}>{i.interest}</span>
                <span className="tabular" style={{ fontWeight: 600 }}>{i.count}</span>
              </div>
            ))}
          </div>
        </Card>

        {/* Lead quality */}
        <Card>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Lead quality (30d)</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {quality.map(q => {
              const total = quality.reduce((a,b)=>a+(+b.count),0) || 1;
              const pct = Math.round((+q.count / total) * 100);
              return (
                <div key={q.quality}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, marginBottom: 4 }}>
                    <span style={{ flex: 1 }}>{q.quality}</span>
                    <span className="tabular" style={{ fontWeight: 600 }}>{q.count}</span>
                    <span style={{ fontSize: 11, color: "var(--ink-3)" }}>{pct}%</span>
                  </div>
                  <div style={{ height: 8, background: "var(--surface-2)", borderRadius: 4, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: pct + "%", background: qualColors[q.quality] || "var(--ink-3)", borderRadius: 4, transition: "width 0.5s" }}/>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      {/* Agent leaderboard */}
      <Card>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Agent performance (30d)</div>
        <table className="data-table" style={{ width: "100%", fontSize: 13 }}>
          <thead><tr><th style={{ paddingLeft: 16 }}>Agent</th><th>Calls</th><th>Answered</th><th>Hot leads</th><th>Avg score</th><th>Minutes</th></tr></thead>
          <tbody>
            {agents.map(a => (
              <tr key={a.id}>
                <td style={{ paddingLeft: 16 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    {a.avatar_gradient && <div style={{ width: 24, height: 24, borderRadius: 6, background: a.avatar_gradient }}/>}
                    <div><div style={{ fontWeight: 500 }}>{a.name}</div><div style={{ fontSize: 11, color: "var(--ink-3)" }}>{a.code}</div></div>
                  </div>
                </td>
                <td className="tabular">{+a.total_calls}</td>
                <td className="tabular">{+a.answered}</td>
                <td className="tabular" style={{ color: +a.hot_leads > 0 ? "var(--err)" : undefined }}>{+a.hot_leads}</td>
                <td className="tabular">{a.avg_score}</td>
                <td className="tabular">{Math.round(+a.total_seconds/60)}m</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function AKpi({ label, value, color }) {
  return (<div style={{ padding: "12px 14px", background: "var(--surface-2)", borderRadius: 10 }}>
    <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{label}</div>
    <div style={{ fontSize: 20, fontWeight: 600, color: color || "var(--ink-1)", marginTop: 2 }} className="tabular">{value}</div>
  </div>);
}

window.AnalyticsScreen = AnalyticsScreen;
