// PortalTable — Client Portal views A: Home, Projects, Approvals.
// Depends on window: React, Ic, Surface, Pill, Button, Progress, Tabs,
// CP* data + CP UI helpers (cp-ui.jsx).

const { useState: useStateVA } = React;

const CP_STATUS_TONE = { in_progress: "blue", review: "amber", done: "green" };

/* ────────────────────────────────────────────────────────────────────────── */
/* HOME                                                                         */
/* ────────────────────────────────────────────────────────────────────────── */
function HomeView({ navigate, approvals, invoices, projects, onReview, onOpenProject }) {
  const pending = approvals.filter((a) => a.status === "pending");
  const dueInv = invoices.filter((i) => i.status === "due" || i.status === "overdue");
  const outstanding = dueInv.reduce((s, i) => s + i.amount, 0);
  const active = projects.filter((p) => p.status !== "done");

  const attention = [
    ...pending.map((a) => ({ id: a.id, icon: "checklist", tone: "amber", title: a.title, meta: `${a.project} · sent ${a.submitted}`, cta: "Review", go: () => navigate("approvals") })),
    ...dueInv.map((i) => ({ id: i.id, icon: "card", tone: i.status === "overdue" ? "red" : "amber", title: `${i.id} · ${cpMoney(i.amount)}`, meta: `${i.desc} · due ${i.due}`, cta: "Pay invoice", go: () => navigate("invoices") })),
  ];

  return (
    <div>
      <CPPageHeader
        title={`Welcome back, ${CP_CLIENT.contact.split(" ")[0]}`}
        subtitle={`Here's where ${CP_AGENCY.name} is on your projects.`}
        actions={<Button variant="secondary" size="md" icon="message" onClick={() => navigate("messages")}>Message the team</Button>} />

      {/* stats */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, marginBottom: 16 }} className="cp-grid-3">
        <CPStat icon="grid" label="Active projects" value={active.length} sub={`${projects.length} total with ${CP_AGENCY.name}`} />
        <CPStat icon="checklist" label="Awaiting your approval" value={pending.length} sub={pending.length ? "Needs a look" : "All clear"} tone={pending.length ? "amber" : undefined} />
        <CPStat icon="card" label="Outstanding" value={outstanding ? cpMoney(outstanding) : "$0"} sub={dueInv.length ? `${dueInv.length} invoice${dueInv.length === 1 ? "" : "s"} due` : "Nothing due"} tone={outstanding ? "amber" : undefined} />
      </div>

      {/* attention */}
      {attention.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <CPSection title="Needs your attention" action={<Pill tone="amber">{`${attention.length} item${attention.length === 1 ? "" : "s"}`}</Pill>} pad={0}>
            <div>
              {attention.map((it, i) => (
                <div key={it.id} style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 18px", borderBottom: i === attention.length - 1 ? 0 : "1px solid var(--line-1)" }}>
                  <span style={{ width: 34, height: 34, borderRadius: 9, display: "grid", placeItems: "center", flexShrink: 0, background: it.tone === "red" ? "var(--red-soft)" : "var(--amber-soft)", color: it.tone === "red" ? "var(--red)" : "var(--amber)" }}>
                    <Ic name={it.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" }}>{it.title}</div>
                    <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.meta}</div>
                  </div>
                  <Button variant="primary" size="sm" onClick={it.go}>{it.cta}</Button>
                </div>
              ))}
            </div>
          </CPSection>
        </div>
      )}

      {/* projects + activity */}
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 }} className="cp-bottom-grid">
        <CPSection title="Your projects" action={<button onClick={() => navigate("projects")} style={cpLinkBtn}>View all</button>} pad={0}>
          <div>
            {projects.map((p, i) => (
              <button key={p.id} onClick={() => onOpenProject(p)}
                style={{ width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", border: 0, borderTop: i === 0 ? 0 : "1px solid var(--line-1)", background: "transparent", cursor: "pointer", fontFamily: "inherit" }}
                onMouseEnter={(e) => (e.currentTarget.style.background = "var(--ink-800)")}
                onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)" }}>{p.name}</span>
                    <StatusPill map={CP_PROJECT_STATUS} value={p.status} />
                  </div>
                  <Progress value={p.progress} tone={CP_STATUS_TONE[p.status]} />
                </div>
                <div style={{ flexShrink: 0, textAlign: "right", minWidth: 64 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)", fontVariantNumeric: "tabular-nums" }}>{p.progress}%</div>
                  <div style={{ fontSize: 11, color: "var(--fg-3)", marginTop: 2 }}>{p.status === "done" ? "Delivered" : `Due ${p.due}`}</div>
                </div>
              </button>
            ))}
          </div>
        </CPSection>

        <CPSection title="Recent activity" pad={0}>
          <div style={{ padding: "6px 0" }}>
            {CP_ACTIVITY.map((a) => <CPActivityRow key={a.id} a={a} />)}
          </div>
        </CPSection>
      </div>
    </div>
  );
}

function CPActivityRow({ a }) {
  const toneFg = { green: "var(--green)", blue: "var(--blue)", teal: "var(--teal)", amber: "var(--amber)", 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>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-4)", marginTop: 2 }}>{a.time}</div>
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/* PROJECTS                                                                     */
/* ────────────────────────────────────────────────────────────────────────── */
function ProjectsView({ projects, onOpenProject }) {
  return (
    <div>
      <CPPageHeader title="Projects" subtitle={`${projects.filter((p) => p.status !== "done").length} active · ${projects.length} total`} />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="cp-grid-2">
        {projects.map((p) => {
          const lead = CP_TEAM[p.lead];
          return (
            <Surface key={p.id} hover pad={18} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15.5, fontWeight: 600, color: "var(--fg-1)", letterSpacing: "-0.01em" }}>{p.name}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-3)", marginTop: 4, lineHeight: 1.45 }}>{p.summary}</div>
                </div>
                <StatusPill map={CP_PROJECT_STATUS} value={p.status} />
              </div>

              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--fg-3)", marginBottom: 7 }}>
                  <span>{p.tasksDone} / {p.tasksTotal} tasks</span>
                  <span style={{ fontWeight: 600, color: "var(--fg-1)", fontVariantNumeric: "tabular-nums" }}>{p.progress}%</span>
                </div>
                <Progress value={p.progress} tone={CP_STATUS_TONE[p.status]} />
              </div>

              <div style={{ display: "flex", alignItems: "center", gap: 10, paddingTop: 4 }}>
                <CPAvatar initials={lead.initials} color={lead.color} size={26} />
                <span style={{ fontSize: 12, color: "var(--fg-2)" }}>{lead.name}</span>
                <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--fg-3)" }}>
                  <Ic name="calendar" size={14} />{p.status === "done" ? "Delivered " + p.due : "Due " + p.due}
                </span>
              </div>

              <div style={{ borderTop: "1px solid var(--line-1)", paddingTop: 14, display: "flex" }}>
                <Button variant="secondary" size="sm" icon="arrowRight" onClick={() => onOpenProject(p)} style={{ marginLeft: "auto" }}>View details</Button>
              </div>
            </Surface>
          );
        })}
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/* APPROVALS                                                                    */
/* ────────────────────────────────────────────────────────────────────────── */
function ApprovalsView({ approvals, onApprove, onRequestChanges }) {
  const [tab, setTab] = useStateVA("pending");
  const counts = {
    pending: approvals.filter((a) => a.status === "pending").length,
    approved: approvals.filter((a) => a.status === "approved").length,
    changes: approvals.filter((a) => a.status === "changes").length,
  };
  const rows = approvals.filter((a) => a.status === tab);

  return (
    <div>
      <CPPageHeader title="Approvals" subtitle={`Review what ${CP_AGENCY.name} sends, and keep work moving.`} />
      <Tabs style={{ marginBottom: 18 }} value={tab} onChange={setTab}
        tabs={[
          { id: "pending", label: "Awaiting you", count: counts.pending },
          { id: "approved", label: "Approved", count: counts.approved },
          { id: "changes", label: "Changes sent", count: counts.changes },
        ]} />

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {rows.length === 0 && (
          <Surface pad={40} style={{ textAlign: "center", color: "var(--fg-3)", fontSize: 14 }}>Nothing here.</Surface>
        )}
        {rows.map((a) => {
          const by = CP_TEAM[a.by];
          return (
            <Surface key={a.id} pad={18} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
                <span style={{ width: 40, height: 40, borderRadius: 10, display: "grid", placeItems: "center", background: "var(--ink-800)", color: "var(--fg-2)", flexShrink: 0 }}>
                  <Ic name={a.type === "Copy" ? "file" : a.type === "Asset" ? "image" : "palette"} size={18} />
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                    <span style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-1)" }}>{a.title}</span>
                    <StatusPill map={CP_APPROVAL_STATUS} value={a.status} />
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-3)", marginTop: 3 }}>
                    {a.project} · {a.type} · sent by {by.name} on {a.submitted}
                  </div>
                </div>
              </div>

              <p style={{ fontSize: 13.5, color: "var(--fg-2)", lineHeight: 1.55, margin: 0, paddingLeft: 54 }}>{a.note}</p>

              <div style={{ display: "flex", alignItems: "center", gap: 10, paddingLeft: 54 }} className="cp-approval-actions">
                <Button variant="secondary" size="sm" icon="eye" onClick={() => window.pdToast({ tone: "info", title: "Opening preview…", body: a.title })}>Preview</Button>
                {a.status === "pending" && (
                  <React.Fragment>
                    <span style={{ marginLeft: "auto" }} />
                    <Button variant="secondary" size="sm" onClick={() => onRequestChanges(a)}>Request changes</Button>
                    <Button variant="primary" size="sm" icon="check" onClick={() => onApprove(a.id)}>Approve</Button>
                  </React.Fragment>
                )}
              </div>
            </Surface>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { HomeView, ProjectsView, ApprovalsView, CPActivityRow, CP_STATUS_TONE });
