// screens-dashboard.jsx
function NeedCard({ icon, tone, count, label, sub, onClick }) {
  return (
    <button className="card card--hover" onClick={onClick} style={{ textAlign: "start", display: "flex", flexDirection: "column", gap: 14, padding: 20, cursor: "pointer" }}>
      <div className="between" style={{ alignItems: "flex-start" }}>
        <span className={"opp"} style={{ width: 40, height: 40, borderRadius: 12, background: "var(--bg-2)", color: tone }}>
          <Icon name={icon} size={20} />
        </span>
        <Icon name="arrowRight" size={18} style={{ color: "var(--fg-disabled)" }} />
      </div>
      <div>
        <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1 }}>{count}</div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6 }}>{label}</div>
        <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 2 }}>{sub}</div>
      </div>
    </button>
  );
}

function ActionRow({ a }) {
  const { go, openContact } = useApp();
  const { t } = useLang();
  const meta = {
    reply: { icon: "message", tone: "purple", verb: t("open"), target: "conversations" },
    approve: { icon: "checkcircle", tone: "lime", verb: t("approve"), target: "conversations" },
    retarget: { icon: "refresh", tone: "blue", verb: "Re-engage", target: "contacts" },
    followup: { icon: "clock", tone: "orange", verb: "Schedule", target: "contacts" },
  }[a.kind];
  const pm = PRIORITY_META[a.priority];
  const contact = DATA.CONTACTS.find((c) => c.name === a.contact);
  return (
    <div className="row" style={{ padding: "14px 0", borderBottom: "1px solid var(--border-1)", gap: 14 }}>
      <span className="opp" style={{ width: 38, height: 38, borderRadius: 10, background: "var(--bg-2)", color: `var(--color-${meta.tone === "lime" ? "secondary" : meta.tone === "purple" ? "purple" : meta.tone === "blue" ? "blue" : "orange"})` }}>
        <Icon name={meta.icon} size={18} />
      </span>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div className="row" style={{ gap: 8 }}>
          <span style={{ fontWeight: 700, fontSize: 14 }}>{a.contact}</span>
          <Badge tone={meta.tone === "lime" ? "lime" : meta.tone}>{a.chip}</Badge>
          {a.priority === "urgent" && <span style={{ display: "inline-flex", alignItems: "center", gap: 3, color: pm.c, fontSize: 12, fontWeight: 700 }}><Icon name="flame" size={13} />Urgent</span>}
        </div>
        <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 3 }}>{a.text}</div>
      </div>
      <div className="row" style={{ gap: 8 }}>
        <Avatar name={a.agent} size="sm" />
        <Button variant="dark" size="sm" iconEnd="chevronRight" onClick={() => contact ? openContact(contact) : go(meta.target)}>{meta.verb}</Button>
      </div>
    </div>
  );
}

function DashboardScreen() {
  const { t } = useLang();
  const { go, startRetarget } = useApp();
  const data = useStore();

  const convos = data.CONVERSATIONS || [];
  const contacts = data.CONTACTS || [];
  const campaigns = data.CAMPAIGNS || [];
  const agents = data.AGENTS || [];
  const actions = data.NEXT_ACTIONS || [];

  const newReplies = convos.filter((c) => c.unread).length;
  const hotReplies = convos.filter((c) => c.unread && c.hot).length;
  const approvals = data.meta?.pendingApprovals ?? convos.filter((c) => c.needsApproval).length;
  const activeCampaigns = campaigns.filter((c) => c.status === "outreach_active");
  const sentActive = activeCampaigns.reduce((n, c) => n + (c.sent || 0), 0);
  const interested = contacts.filter((c) => c.status === "interested" || c.status === "proposal");
  const proposals = contacts.filter((c) => c.status === "proposal").length;
  const retargetable = contacts.filter((c) => c.status === "followup");

  // "Next best actions" — derived LIVE from real data (the seed ships an empty
  // NEXT_ACTIONS by design). Drafts awaiting approval and hot replies come first,
  // then interested-but-quiet leads to re-engage and follow-ups due. Ranked by
  // priority so the operator's home screen is an actionable triage, never empty.
  const PRI = { urgent: 3, high: 2, medium: 1, low: 0 };
  const derivedActions = [];
  for (const cv of convos) {
    if (cv.needsApproval || cv.pendingDraft) derivedActions.push({ id: "ap_" + cv.id, kind: "approve", priority: cv.hot ? "urgent" : "high", contact: cv.name, chip: "Draft ready", text: "Review and approve the AI-written reply." });
    else if (cv.unread) derivedActions.push({ id: "rp_" + cv.id, kind: "reply", priority: cv.hot ? "urgent" : "medium", contact: cv.name, chip: "New reply", text: "A lead replied — pick up the conversation." });
  }
  for (const c of contacts) {
    if ((c.status === "interested" || c.status === "proposal") && /day|week/.test(c.lastReply || "")) derivedActions.push({ id: "rt_" + c.id, kind: "retarget", priority: "medium", contact: c.name, chip: "Gone quiet", text: "Interested but silent — re-engage with a fresh angle." });
    else if (c.status === "followup") derivedActions.push({ id: "fu_" + c.id, kind: "followup", priority: "medium", contact: c.name, chip: "Follow-up due", text: "Scheduled follow-up is due." });
  }
  derivedActions.sort((a, b) => (PRI[b.priority] || 0) - (PRI[a.priority] || 0));
  const topActions = (actions.length ? actions : derivedActions).slice(0, 6);
  const urgentItems = topActions.filter((a) => a.priority === "urgent").length;

  // Top performer — derived LIVE from real per-agent outcomes (the seed's static
  // winRate/sent7/replyRate fields are never written by the backend, so we do NOT read
  // them; we rank by real won/engaged/contacted contacts and show an honest empty state).
  const agentPerf = agents.map((a) => {
    const leads = contacts.filter((c) => (c.agentId ? c.agentId === a.id : c.agent === a.name));
    const won = leads.filter((c) => c.status === "won").length;
    const engaged = leads.filter((c) => ["replied", "interested", "proposal", "won"].includes(c.status)).length;
    const contacted = leads.filter((c) => c.status && c.status !== "new").length;
    return { agent: a, leads: leads.length, won, engaged, contacted };
  });
  const topPerf = agentPerf.slice().sort((x, y) => (y.won - x.won) || (y.engaged - x.engaged) || (y.contacted - x.contacted))[0];
  const hasPerf = !!(topPerf && (topPerf.contacted > 0 || topPerf.won > 0));
  const topAgent = hasPerf ? topPerf.agent : null;

  return (
    <div className="content__inner fade-up">
      <div className="between" style={{ marginBottom: 24 }}>
        <div>
          <h4 style={{ marginBottom: 4 }}>{t("greeting")}{data.meta?.user?.name ? `, ${data.meta.user.name}` : ""}</h4>
          <div className="muted" style={{ fontSize: 14 }}>You have <b style={{ color: "var(--fg-1)" }}>{urgentItems} urgent</b> {urgentItems === 1 ? "item" : "items"} and <b style={{ color: "var(--fg-1)" }}>{approvals} {approvals === 1 ? "draft" : "drafts"}</b> waiting. Most are 1 click away.</div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          {data.meta?.live
            ? <Badge tone="green" dot="#22C55E">AI live</Badge>
            : <Badge tone="orange" dot="#EA580C">AI fallback</Badge>}
        </div>
      </div>

      <FallbackBanner />

      <div className="grid" style={{ gridTemplateColumns: "repeat(5, 1fr)", marginBottom: 24 }}>
        <NeedCard icon="message" tone="var(--color-purple)" count={newReplies} label={t("newReplies")} sub={`${hotReplies} hot`} onClick={() => go("conversations")} />
        <NeedCard icon="checkcircle" tone="var(--color-secondary)" count={approvals} label={t("waitingApprovals")} sub="ready to review" onClick={() => go("conversations")} />
        <NeedCard icon="megaphone" tone="var(--color-blue)" count={activeCampaigns.length} label={t("activeCampaigns")} sub={`${sentActive} sent`} onClick={() => go("campaigns")} />
        <NeedCard icon="flame" tone="var(--color-orange)" count={interested.length} label={t("interestedLeads")} sub={`${proposals} in proposal`} onClick={() => go("contacts")} />
        <NeedCard icon="refresh" tone="var(--color-blue)" count={retargetable.length} label={t("retarget")} sub="silent 5+ days" onClick={startRetarget} />
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.7fr 1fr" }}>
        <Card title={t("nextBest")} flush>
          <div style={{ padding: "0 24px 8px" }}>
            <div className="between" style={{ paddingTop: 20, paddingBottom: 4 }}>
              <span className="subtle" style={{ fontSize: 12 }}>Ranked by priority and heat</span>
              <button className="btn btn--subtle btn--sm" onClick={() => go("conversations")}>{t("reviewAll")}</button>
            </div>
            {topActions.length
              ? topActions.map((a) => <ActionRow key={a.id} a={a} />)
              : <div style={{ padding: "28px 0 24px", textAlign: "center", color: "var(--fg-3)" }}><Icon name="checkcircle" size={26} style={{ color: "var(--color-secondary)", marginBottom: 8 }} /><div style={{ fontWeight: 700, fontSize: 14, color: "var(--fg-1)" }}>You're all caught up</div><div style={{ fontSize: 13, marginTop: 3 }}>No drafts, replies or follow-ups need you right now.</div></div>}
          </div>
        </Card>

        <div className="col" style={{ gap: 24 }}>
          <Card title="WhatsApp lines" action={<button className="btn btn--subtle btn--sm" onClick={() => go("settings")}>Manage</button>}>
            <div className="col" style={{ gap: 14, marginTop: 4 }}>
              {(() => {
                // Live WhatsApp lines (real per-line senders), not the legacy empty SESSIONS store.
                const waLines = (DATA.SENDERS || []).filter((s) => s.channel === "whatsapp_web");
                if (!waLines.length) return <div className="muted" style={{ fontSize: 13 }}>No WhatsApp lines connected yet — connect a number in Settings.</div>;
                return waLines.slice(0, 3).map((s) => (
                  <div key={s.id} className="between">
                    <div className="row" style={{ gap: 10 }}>
                      <Icon name="phoneDevice" size={18} style={{ color: "var(--fg-3)" }} />
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600 }}>{s.label || s.displayName || "WhatsApp line"}</div>
                        <div style={{ fontSize: 11, color: "var(--fg-4)" }}>{s.sentToday || 0}/{s.dailyLimit ?? s.dailyCapacity ?? 500} today</div>
                      </div>
                    </div>
                    <WaChip state={s.status === "active" ? "connected" : "disconnected"} />
                  </div>
                ));
              })()}
            </div>
          </Card>

          <Card title="Top performer" action={<button className="btn btn--subtle btn--sm" onClick={() => go("agents")}>Team</button>}>
            {hasPerf ? (
              <>
                <div className="row" style={{ gap: 14, marginTop: 4 }}>
                  <Avatar name={topAgent.name} size="lg" color={topAgent.color || "#0891B2"} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700 }}>{topAgent.name} · {topAgent.role}</div>
                    <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{topPerf.won} won · {topPerf.engaged} engaged of {topPerf.leads} lead{topPerf.leads === 1 ? "" : "s"}</div>
                  </div>
                </div>
                <div className="grid" style={{ gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginTop: 16 }}>
                  {[["Contacted", topPerf.contacted], ["Engaged", topPerf.engaged], ["Won", topPerf.won]].map(([k, v]) => (
                    <div key={k} style={{ background: "var(--bg-2)", borderRadius: 12, padding: "12px 14px" }}>
                      <div style={{ fontSize: 20, fontWeight: 800 }}>{v}</div>
                      <div style={{ fontSize: 11, color: "var(--fg-4)" }}>{k}</div>
                    </div>
                  ))}
                </div>
              </>
            ) : (
              <div className="muted" style={{ fontSize: 13, padding: "14px 2px", lineHeight: 1.6 }}>No performance data yet — your top performer appears here once leads are contacted and won.</div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.DashboardScreen = DashboardScreen;
