// screens-agents.jsx — AI team cards + agent detail drawer
const TRUST_LADDER = [
  { n: 1, label: "Observe", desc: "Watches and learns. No messages." },
  { n: 2, label: "Drafts only", desc: "Writes drafts for you to send." },
  { n: 3, label: "Send with approval", desc: "Sends after you approve each one." },
  { n: 4, label: "Auto-send (low risk)", desc: "Sends safe replies on its own." },
  { n: 5, label: "Director", desc: "Runs campaigns end-to-end." },
];

function TrustMeter({ level, compact }) {
  return (
    <div className="row" style={{ gap: 4 }}>
      {[1, 2, 3, 4, 5].map((n) => (
        <span key={n} style={{ width: compact ? 16 : 22, height: 6, borderRadius: 999, background: n <= level ? "var(--color-primary)" : "var(--border-1)" }} />
      ))}
    </div>
  );
}

function AgentCard({ a }) {
  const { openAgent, editAgent } = useApp();
  return (
    <Card hover style={{ cursor: "pointer" }} onClick={() => openAgent(a)}>
      <div className="between" style={{ marginBottom: 14 }}>
        <div className="row" style={{ gap: 12 }}>
          <Avatar name={a.name} color={a.color} size="lg" />
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{a.name}</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-3)" }}>{a.role}</div>
          </div>
        </div>
        <div className="row" style={{ gap: 4 }}>
          <button className="iconbtn" style={{ width: 34, height: 34 }} title="Edit agent" onClick={(e) => { e.stopPropagation(); editAgent(a); }}><Icon name="edit" size={17} /></button>
          <Badge tone="green" dot="#22C55E">Active</Badge>
        </div>
      </div>
      <p style={{ fontSize: 13, lineHeight: 1.5, color: "var(--fg-3)", marginBottom: 16, minHeight: 38 }}>{a.blurb}</p>
      <div className="grid" style={{ gridTemplateColumns: "repeat(3,1fr)", gap: 8, marginBottom: 16 }}>
        {[["Active leads", a.activeLeads], ["Win rate", a.winRate + "%"], ["Campaigns", a.campaigns]].map(([k, v]) => (
          <div key={k} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
            <div style={{ fontSize: 18, fontWeight: 800, letterSpacing: "-0.02em" }}>{v}</div>
            <div style={{ fontSize: 11, color: "var(--fg-4)" }}>{k}</div>
          </div>
        ))}
      </div>
      <div className="between">
        <div>
          <div style={{ fontSize: 11, color: "var(--fg-4)", marginBottom: 5, fontWeight: 600 }}>Trust level · {a.trustLabel}</div>
          <TrustMeter level={a.trust} />
        </div>
        <span style={{ fontSize: 11, color: "var(--fg-4)" }}>{a.lastActivity}</span>
      </div>
    </Card>
  );
}

function AgentsScreen() {
  const { newAgent } = useApp();
  const data = useStore();
  const agents = data.AGENTS;
  return (
    <div className="content__inner fade-up">
      <div className="between" style={{ marginBottom: 20 }}>
        <p className="muted" style={{ fontSize: 14, maxWidth: 540 }}>{agents.length} AI specialists handle outreach and replies. Each earns a higher trust level as it proves itself — you stay in control of what it can do.</p>
        <Button variant="ghost" icon="plus" onClick={newAgent}>New agent</Button>
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
        {agents.map((a) => <AgentCard key={a.id} a={a} />)}
      </div>
      <AgentPerformancePanel />
    </div>
  );
}

/* ---- Agent performance dashboard (real data only) --------------------- */
function AgentPerformancePanel() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => { let on = true; API.metrics.agents().then((d) => { if (on) setData(d); }).catch(() => {}); return () => { on = false; }; }, []);
  if (!data) return null;
  const rows = data.agents || [];
  const hasActivity = (data.totals && data.totals.leadsHandled > 0);
  const th = { padding: "8px 10px", fontSize: 11.5, fontWeight: 700, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: ".03em" };
  const td = { padding: "9px 10px", textAlign: "center", fontSize: 13 };
  const convTone = (r) => (r >= 50 ? "green" : r >= 25 ? "orange" : "neutral");
  return (
    <Card title="Agent performance" style={{ marginTop: 26 }} action={<Badge tone="neutral">Live · real data</Badge>}>
      {!hasActivity ? (
        <div className="muted" style={{ fontSize: 13, padding: "4px 2px" }}>No activity yet — these metrics populate from real leads, replies, Google&nbsp;Meet bookings and closed deals as your agents work. Nothing is simulated.</div>
      ) : (
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead><tr style={{ borderBottom: "1px solid var(--border-1)" }}>
              <th style={{ ...th, textAlign: "start" }}>Agent</th><th style={th}>Leads</th><th style={th}>Replies</th><th style={th}>Meetings</th><th style={th}>Opps</th><th style={th}>Won</th><th style={th}>Lost</th><th style={th}>Conversion</th>
            </tr></thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.agentId} style={{ borderBottom: "1px solid var(--border-1)" }}>
                  <td style={{ ...td, textAlign: "start", fontWeight: 600 }}>{r.name}{r.service ? <span className="muted" style={{ fontWeight: 400, marginInlineStart: 6, fontSize: 11 }}>{r.service}</span> : null}</td>
                  <td style={td}>{r.leadsHandled}</td>
                  <td style={td}>{r.repliesSent}</td>
                  <td style={td}>{r.meetingsBooked}</td>
                  <td style={td}>{r.opportunitiesCreated}</td>
                  <td style={{ ...td, color: "#15803D", fontWeight: 700 }}>{r.closedWon}</td>
                  <td style={{ ...td, color: "#B91C1C" }}>{r.closedLost}</td>
                  <td style={td}><Badge tone={convTone(r.conversionRate)}>{r.conversionRate}%</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

/* ---- Agent drawer ------------------------------------------------------ */
function AgentDrawer({ agent: a, onClose }) {
  const { editAgent } = useApp();
  // resolve by agentId (source of truth) so a renamed agent's campaigns never drop
  const myCampaigns = DATA.CAMPAIGNS.filter((c) => (c.agentId ? c.agentId === a.id : c.agent === a.name));
  // LIVE per-agent analytics (real leads/replies/meetings/conversion via /metrics/agents).
  // The old static seed fields (a.sent7/replyRate/approvalRate/winRate) are seeded 0 and
  // NEVER update, so the card was frozen — replaced with real data + honest empty state.
  const [perf, setPerf] = React.useState(null);
  React.useEffect(() => { let on = true; API.metrics.agents().then((d) => { if (on) setPerf((d.agents || []).find((r) => r.agentId === a.id) || {}); }).catch(() => {}); return () => { on = false; }; }, [a.id]);
  return (
    <Drawer onClose={onClose}>
      <DrawerHead title={a.name} sub={a.role} onClose={onClose}
        right={<Button variant="ghost" size="sm" icon="edit" onClick={() => editAgent(a)}>Edit</Button>} />
      <div style={{ overflowY: "auto", padding: 24, display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="row" style={{ gap: 14 }}>
          <Avatar name={a.name} color={a.color} size="lg" />
          <div style={{ flex: 1 }}>
            <div className="row wrap" style={{ gap: 6 }}>
              <Badge tone="neutral">{a.style}</Badge>
              <Badge tone="neutral"><Icon name="globe2" size={12} />{a.lang === "ar" ? "Arabic" : a.lang === "en" ? "English" : "Arabic + English"}</Badge>
              <Badge tone="green" dot="#22C55E">Active</Badge>
            </div>
          </div>
        </div>
        <p style={{ fontSize: 14, lineHeight: 1.55, color: "var(--fg-2)" }}>{a.blurb}</p>

        {/* performance — LIVE from real leads/replies/meetings/closed deals */}
        <Card title="Performance" action={<Badge tone="neutral">Live · real data</Badge>}>
          {perf && (perf.leadsHandled || perf.repliesSent || perf.meetingsBooked || perf.closedWon) ? (
            <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {[["Leads handled", perf.leadsHandled || 0], ["Replies sent", perf.repliesSent || 0], ["Meetings booked", perf.meetingsBooked || 0], ["Conversion", (perf.conversionRate || 0) + "%"]].map(([k, v]) => (
                <div key={k} style={{ background: "var(--bg-2)", borderRadius: 12, padding: "14px 16px" }}>
                  <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em" }}>{v}</div>
                  <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{k}</div>
                </div>
              ))}
            </div>
          ) : (
            <div className="muted" style={{ fontSize: 13 }}>No activity yet — performance populates from real leads, replies, meetings and closed deals as this agent works. Nothing is simulated.</div>
          )}
        </Card>

        {/* trust ladder */}
        <Card title="Trust level">
          <div className="row" style={{ gap: 10, marginBottom: 14 }}>
            <TrustMeter level={a.trust} /><b style={{ fontSize: 13 }}>{a.trustLabel}</b>
          </div>
          <div className="col" style={{ gap: 2 }}>
            {TRUST_LADDER.map((l) => {
              const on = l.n <= a.trust, current = l.n === a.trust;
              return (
                <div key={l.n} className="row" style={{ gap: 12, padding: "8px 10px", borderRadius: 10, background: current ? "var(--color-primary-tint-soft)" : "transparent", alignItems: "flex-start" }}>
                  <span style={{ width: 22, height: 22, flexShrink: 0, borderRadius: 999, fontSize: 11, fontWeight: 700, display: "inline-flex", alignItems: "center", justifyContent: "center", background: on ? "var(--color-primary)" : "var(--bg-2)", color: on ? "var(--color-secondary)" : "var(--fg-disabled)" }}>{on ? <Icon name="check" size={13} /> : l.n}</span>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: on ? "var(--fg-1)" : "var(--fg-4)" }}>{l.label}{current && <span style={{ color: "var(--color-secondary)", fontWeight: 700 }}> · current</span>}</div>
                    <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{l.desc}</div>
                  </div>
                </div>
              );
            })}
          </div>
          <p className="subtle" style={{ fontSize: 12, marginTop: 12, lineHeight: 1.5 }}>Agents move up automatically as approval and win rates stay high. You can cap the level any time.</p>
        </Card>

        {/* assigned campaigns */}
        <Card title="Campaigns">
          {myCampaigns.length ? myCampaigns.map((c) => (
            <div key={c.id} className="between" style={{ padding: "10px 0", borderBottom: "1px solid var(--border-1)" }}>
              <div><div style={{ fontSize: 13, fontWeight: 600 }}>{c.name}</div><div style={{ fontSize: 11, color: "var(--fg-4)" }}>{c.sent} sent · {c.interested} interested</div></div>
              <Badge tone={CAMP_STATUS[c.status].tone} dot={CAMP_STATUS[c.status].c}>{CAMP_STATUS[c.status].label}</Badge>
            </div>
          )) : <span className="muted" style={{ fontSize: 13 }}>No active campaigns.</span>}
        </Card>
      </div>
    </Drawer>
  );
}

window.AgentsScreen = AgentsScreen;
window.AgentDrawer = AgentDrawer;
