// PortalTable Dashboard — Overview view. KPI cards + revenue chart + status donut
// + "needs attention" queue + recent activity. Reads window primitives & data.

const { useState: useStateOv } = React;

/* Page header used across all views */
function PageHeader({ title, subtitle, actions }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 16, flexWrap: "wrap", marginBottom: 24 }}>
      <div style={{ flex: 1, minWidth: 240 }}>
        <h1 style={{ fontSize: 24, fontWeight: 600, letterSpacing: "-0.025em", color: "var(--fg-1)", margin: 0 }}>{title}</h1>
        {subtitle && <p style={{ fontSize: 14, color: "var(--fg-2)", margin: "6px 0 0", lineHeight: 1.5 }}>{subtitle}</p>}
      </div>
      {actions && <div className="pd-page-actions" style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", justifyContent: "flex-end" }}>{actions}</div>}
    </div>
  );
}

/* KPI stat card */
function StatCard({ label, value, delta, deltaUp, spark, sparkUp, footnote, icon }) {
  return (
    <Surface hover pad={18} style={{ display: "flex", flexDirection: "column", gap: 14, minHeight: 132 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ width: 30, height: 30, borderRadius: 8, display: "grid", placeItems: "center", background: "var(--ink-800)", color: "var(--fg-2)", flexShrink: 0 }}>
          <Ic name={icon} size={16} />
        </span>
        <span style={{ fontSize: 13, color: "var(--fg-2)", fontWeight: 500 }}>{label}</span>
      </div>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 10 }}>
        <div>
          <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.03em", color: "var(--fg-1)", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{value}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 9 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 2, fontSize: 12, fontWeight: 600, color: deltaUp ? "var(--green)" : "var(--red)" }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ transform: deltaUp ? "none" : "rotate(90deg)" }}><path d="M7 17 17 7M9 7h8v8" /></svg>
              {delta}
            </span>
            <span style={{ fontSize: 11.5, color: "var(--fg-3)" }}>{footnote}</span>
          </div>
        </div>
        {spark && <MiniSpark points={spark} up={sparkUp} width={84} height={34} />}
      </div>
    </Surface>
  );
}

function SectionCard({ title, action, children, pad = 18, style = {} }) {
  return (
    <Surface pad={0} style={style}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "15px 18px", borderBottom: "1px solid var(--line-2)" }}>
        <h3 style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-1)", margin: 0, letterSpacing: "-0.01em" }}>{title}</h3>
        <div style={{ marginLeft: "auto" }}>{action}</div>
      </div>
      <div style={{ padding: pad }}>{children}</div>
    </Surface>
  );
}

function OverviewView({ navigate }) {
  const [range, setRange] = useStateOv("30d");

  const pendingApprovals = PD_APPROVALS.filter((a) => a.status === "pending");
  const overdueInv = PD_INVOICES.filter((i) => i.status === "overdue");
  const dueInv = PD_INVOICES.filter((i) => i.status === "due");
  const outstanding = [...overdueInv, ...dueInv].reduce((s, i) => s + i.amount, 0);
  const liveClients = PD_CLIENTS.filter((c) => c.portal === "live").length;
  const openProjects = PD_PROJECTS.filter((p) => p.status !== "done").length;

  const statusCounts = Object.keys(PD_PROJECT_STATUS).map((k) => ({
    label: PD_PROJECT_STATUS[k].label,
    value: PD_PROJECTS.filter((p) => p.status === k).length,
    color: { in_progress: "#2D6FE0", review: "#B5790B", blocked: "#C8443B", done: "#15935E" }[k],
  }));

  // attention queue: approvals + overdue invoices + a blocked project
  const attention = [
    ...pendingApprovals.slice(0, 3).map((a) => ({
      id: a.id, icon: "checklist", tone: "amber",
      title: a.title, meta: `${a.client} · ${a.type} · submitted ${a.submitted}`,
      primary: "Review", kind: "approval",
    })),
    ...overdueInv.map((i) => ({
      id: i.id, icon: "card", tone: "red",
      title: `${i.id} overdue — $${i.amount.toLocaleString()}`, meta: `${i.client} · was due ${i.due}`,
      primary: "Send reminder", kind: "invoice",
    })),
    { id: "p3", icon: "clock", tone: "red", title: "Listing Microsite is blocked", meta: "Birchwood Realty · waiting on client assets since Jun 11", primary: "Nudge client", kind: "project" },
  ];

  return (
    <div>
      <PageHeader
        title="Overview"
        subtitle="Thursday, June 15 · Here's what's happening across your client portals."
        actions={
          <React.Fragment>
            <Segmented options={[{ id: "7d", label: "7d" }, { id: "30d", label: "30d" }, { id: "qtr", label: "Quarter" }]} value={range} onChange={setRange} />
            <Button variant="secondary" size="md" icon="users" onClick={() => navigate("clients")}>Invite client</Button>
            <Button variant="primary" size="md" icon="plus" onClick={() => window.pdNewProject && window.pdNewProject()}>New project</Button>
          </React.Fragment>
        }
      />

      {/* KPI row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 16 }} className="pd-kpi-grid">
        <StatCard label="Monthly recurring" value="$11,300" delta="4.3%" deltaUp footnote="vs last mo" icon="coins" spark={PD_REVENUE.map((r) => r.value)} sparkUp />
        <StatCard label="Active client portals" value={liveClients} delta="2" deltaUp footnote="new this mo" icon="globe" spark={[5, 5, 6, 6, 7, 7, 7, liveClients]} sparkUp />
        <StatCard label="Open projects" value={openProjects} delta="1" deltaUp={false} footnote="vs last wk" icon="grid" spark={[9, 8, 8, 7, 8, 7, 7, openProjects]} sparkUp={false} />
        <StatCard label="Outstanding" value={`$${(outstanding / 1000).toFixed(1)}k`} delta="3 invoices" deltaUp={false} footnote="awaiting" icon="coins" spark={[3, 4, 3, 5, 4, 5, 4, 4]} sparkUp={false} />
      </div>

      {/* charts row */}
      <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr", gap: 16, marginBottom: 16 }} className="pd-chart-grid">
        <SectionCard title="Recurring revenue"
          action={<Pill tone="green" dot>+62% YoY</Pill>}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 8 }}>
            <span style={{ fontSize: 26, fontWeight: 600, color: "var(--fg-1)", letterSpacing: "-0.02em" }}>$11,300</span>
            <span style={{ fontSize: 13, color: "var(--fg-3)" }}>/ month · {PD_CLIENTS.filter(c => c.mrr > 0).length} paying clients</span>
          </div>
          <AreaChart data={PD_REVENUE} valuePrefix="$" />
        </SectionCard>

        <SectionCard title="Project status">
          <div style={{ paddingTop: 6 }}>
            <Donut segments={statusCounts} centerValue={PD_PROJECTS.length} centerLabel="Projects" />
          </div>
        </SectionCard>
      </div>

      {/* attention + activity */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }} className="pd-bottom-grid">
        <SectionCard title="Needs your attention"
          action={<Pill tone="amber">{attention.length} items</Pill>} pad={0}>
          <div>
            {attention.map((item, i) => (
              <AttentionRow key={item.id + i} item={item} navigate={navigate} last={i === attention.length - 1} />
            ))}
          </div>
        </SectionCard>

        <SectionCard title="Recent activity"
          action={<button onClick={() => navigate("clients")} style={linkBtn}>View all</button>} pad={0}>
          <div style={{ padding: "6px 0" }}>
            {PD_ACTIVITY.map((a) => <ActivityRow key={a.id} a={a} />)}
          </div>
        </SectionCard>
      </div>
    </div>
  );
}

function AttentionRow({ item, navigate, last }) {
  const [h, setH] = useStateOv(false);
  const toneBg = { amber: "var(--amber-soft)", red: "var(--red-soft)", blue: "var(--blue-soft)" }[item.tone] || "var(--ink-800)";
  const toneFg = { amber: "var(--amber)", red: "var(--red)", blue: "var(--blue)" }[item.tone] || "var(--fg-2)";
  function handle() {
    if (item.kind === "approval") { navigate("approvals"); }
    else if (item.kind === "invoice") { window.pdToast({ tone: "success", title: "Reminder sent", body: `${item.title.split(" ")[0]} payment reminder emailed to the client.` }); }
    else { window.pdToast({ tone: "success", title: "Client nudged", body: "We pinged Birchwood Realty for the outstanding assets." }); }
  }
  return (
    <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 18px", borderBottom: last ? 0 : "1px solid var(--line-1)", background: h ? "var(--ink-800)" : "transparent", transition: "background var(--dur-1) var(--ease-out)" }}>
      <span style={{ width: 34, height: 34, borderRadius: 9, display: "grid", placeItems: "center", background: toneBg, color: toneFg, flexShrink: 0 }}>
        <Ic name={item.icon} size={17} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.title}</div>
        <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.meta}</div>
      </div>
      <Button variant={item.tone === "red" ? "secondary" : "primary"} size="sm" onClick={handle}>{item.primary}</Button>
    </div>
  );
}

function ActivityRow({ a }) {
  const toneFg = { green: "var(--green)", blue: "var(--blue)", teal: "var(--teal)", accent: "var(--accent-ink)", neutral: "var(--fg-2)" }[a.tone];
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "9px 18px" }}>
      <span style={{ width: 26, height: 26, borderRadius: 7, display: "grid", placeItems: "center", background: "var(--ink-800)", color: toneFg, flexShrink: 0, marginTop: 1 }}>
        <Ic name={a.icon} size={14} />
      </span>
      <div style={{ flex: 1, fontSize: 13, color: "var(--fg-2)", lineHeight: 1.45 }}>
        <span style={{ fontWeight: 600, color: "var(--fg-1)" }}>{a.who}</span> {a.what} <span style={{ fontWeight: 500, color: "var(--fg-1)" }}>{a.target}</span>
        {a.client && <span style={{ color: "var(--fg-3)" }}> · {a.client}</span>}
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-4)", marginTop: 2 }}>{a.time}</div>
      </div>
    </div>
  );
}

const linkBtn = { background: "none", border: 0, padding: 0, cursor: "pointer", fontSize: 12.5, fontWeight: 500, color: "var(--fg-2)", fontFamily: "inherit" };

Object.assign(window, { OverviewView, PageHeader, StatCard, SectionCard, linkBtn });
