// PortalTable — Client Portal views B: Invoices, Files, Messages.
// Depends on window: React, Ic, Surface, Pill, Button, DataTable, IconButton,
// CP* data + CP UI helpers.

const { useState: useStateVB, useRef: useRefVB, useEffect: useEffectVB } = React;

/* ────────────────────────────────────────────────────────────────────────── */
/* INVOICES & PAYMENTS                                                          */
/* ────────────────────────────────────────────────────────────────────────── */
function InvoicesView({ invoices, onPay }) {
  const outstanding = invoices.filter((i) => i.status === "due" || i.status === "overdue").reduce((s, i) => s + i.amount, 0);
  const paidYtd = invoices.filter((i) => i.status === "paid").reduce((s, i) => s + i.amount, 0);

  const columns = [
    { key: "id", header: "Invoice", render: (r) => (
      <div>
        <div style={{ fontWeight: 600, color: "var(--fg-1)", fontFamily: "var(--font-mono)", fontSize: 12.5 }}>{r.id}</div>
        <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2 }}>{r.desc}</div>
      </div>
    ) },
    { key: "amount", header: "Amount", align: "right", sortable: true, sortVal: (r) => r.amount, render: (r) => <span style={{ fontVariantNumeric: "tabular-nums", fontWeight: 600, color: "var(--fg-1)" }}>{cpMoney(r.amount)}</span> },
    { key: "due", header: "Due", render: (r) => <span style={{ color: "var(--fg-2)" }}>{r.due}</span> },
    { key: "status", header: "Status", render: (r) => <StatusPill map={CP_INVOICE_STATUS} value={r.status} /> },
    { key: "act", header: "", align: "right", render: (r) => (
      (r.status === "due" || r.status === "overdue")
        ? <Button variant="primary" size="sm" icon="card" onClick={() => onPay(r)}>Pay</Button>
        : r.status === "paid"
          ? <button onClick={() => window.pdToast({ tone: "info", title: "Downloading receipt…", body: r.id })} style={{ ...cpLinkBtn, display: "inline-flex", alignItems: "center", gap: 6, color: "var(--fg-2)" }}><Ic name="download" size={15} />Receipt</button>
          : <span style={{ fontSize: 12, color: "var(--fg-4)" }}>—</span>
    ) },
  ];

  return (
    <div>
      <CPPageHeader title="Invoices & payments" subtitle="Pay invoices and download receipts. Issued by Studio Northstar." />

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }} className="cp-grid-2">
        <CPStat icon="card" label="Outstanding" value={outstanding ? cpMoney(outstanding) : "$0"} sub={outstanding ? "Due now" : "Nothing due"} tone={outstanding ? "amber" : undefined} />
        <CPStat icon="check" label="Paid to date" value={cpMoney(paidYtd)} sub="Thanks!" tone="green" />
      </div>

      <Surface pad={0}>
        <DataTable columns={columns} rows={invoices} initialSort={{ key: "amount", dir: "desc" }} />
      </Surface>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/* FILES                                                                        */
/* ────────────────────────────────────────────────────────────────────────── */
function FilesView({ files, onDownload }) {
  return (
    <div>
      <CPPageHeader title="Files" subtitle={`${files.length} files shared with you`}
        actions={<Button variant="secondary" size="md" icon="download" onClick={() => window.pdToast({ tone: "info", title: "Preparing download…", body: "All files as a .zip" })}>Download all</Button>} />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="cp-grid-2">
        {files.map((f) => {
          const fi = CP_FILE_ICON[f.kind] || CP_FILE_ICON.doc;
          return (
            <Surface key={f.id} hover pad={16} style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <span style={{ width: 42, height: 42, borderRadius: 10, display: "grid", placeItems: "center", flexShrink: 0, background: "var(--ink-800)", color: fi.color }}>
                <Ic name={fi.icon} size={20} />
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 2, fontFamily: "var(--font-mono)" }}>
                  {f.kind.toUpperCase()} · {f.size} · {f.date}
                </div>
              </div>
              <IconButton icon="download" label={"Download " + f.name} onClick={() => onDownload(f)} />
            </Surface>
          );
        })}
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/* MESSAGES                                                                     */
/* ────────────────────────────────────────────────────────────────────────── */
function MessagesView({ messages, onSend }) {
  const [text, setText] = useStateVB("");
  const endRef = useRefVB(null);
  useEffectVB(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [messages.length]);

  function submit(e) {
    e.preventDefault();
    const t = text.trim();
    if (!t) return;
    onSend(t);
    setText("");
  }

  return (
    <div>
      <CPPageHeader title="Messages" subtitle={`Talk to your ${CP_AGENCY.name} team`} />
      <Surface pad={0} style={{ display: "flex", flexDirection: "column", overflow: "hidden" }}>
        {/* thread header */}
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "13px 18px", borderBottom: "1px solid var(--line-2)" }}>
          <div style={{ display: "flex" }}>
            {[CP_TEAM.alex, CP_TEAM.devin].map((m, i) => (
              <span key={m.initials} style={{ marginLeft: i ? -8 : 0, borderRadius: 999, boxShadow: "0 0 0 2px var(--ink-900)" }}>
                <CPAvatar initials={m.initials} color={m.color} size={28} />
              </span>
            ))}
          </div>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)" }}>{CP_AGENCY.name} team</div>
            <div style={{ fontSize: 11.5, color: "var(--fg-3)" }}>{CP_TEAM.alex.name} · {CP_TEAM.devin.name}</div>
          </div>
          <span style={{ marginLeft: "auto" }}><Pill tone="green" dot>Usually replies in a few hours</Pill></span>
        </div>

        {/* thread */}
        <div ref={endRef} className="cp-msg-thread" style={{ padding: 18, display: "flex", flexDirection: "column", gap: 14, height: 420, overflowY: "auto", background: "var(--ink-950)" }}>
          {messages.map((m) => <MessageBubble key={m.id} m={m} />)}
        </div>

        {/* composer */}
        <form onSubmit={submit} style={{ display: "flex", alignItems: "center", gap: 10, padding: 14, borderTop: "1px solid var(--line-2)", background: "var(--ink-900)" }}>
          <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Write a message…"
            style={{ flex: 1, height: 40, padding: "0 14px", borderRadius: 9, border: "1px solid var(--line-3)", background: "var(--ink-950)", color: "var(--fg-1)", fontSize: 14, fontFamily: "inherit", outline: "none" }}
            onFocus={(e) => { e.target.style.borderColor = "var(--accent-press)"; e.target.style.boxShadow = "var(--focus-ring)"; }}
            onBlur={(e) => { e.target.style.borderColor = "var(--line-3)"; e.target.style.boxShadow = "none"; }} />
          <Button variant="primary" size="md" icon="send" onClick={submit}>Send</Button>
        </form>
      </Surface>
    </div>
  );
}

function MessageBubble({ m }) {
  const mine = m.from === "me";
  const who = mine ? null : CP_TEAM[m.from];
  return (
    <div style={{ display: "flex", gap: 10, flexDirection: mine ? "row-reverse" : "row", alignItems: "flex-end" }}>
      {!mine && <CPAvatar initials={who.initials} color={who.color} size={28} />}
      <div style={{ maxWidth: "72%" }}>
        {!mine && <div style={{ fontSize: 11, color: "var(--fg-3)", marginBottom: 4, marginLeft: 2 }}>{who.name}</div>}
        <div style={{
          padding: "10px 13px", borderRadius: 12, fontSize: 13.5, lineHeight: 1.5,
          background: mine ? "var(--accent-soft)" : "var(--ink-900)",
          border: `1px solid ${mine ? "var(--accent-line)" : "var(--line-2)"}`,
          color: "var(--fg-1)",
          borderBottomRightRadius: mine ? 4 : 12, borderBottomLeftRadius: mine ? 12 : 4,
        }}>{m.text}</div>
        <div style={{ fontSize: 10.5, color: "var(--fg-4)", marginTop: 4, textAlign: mine ? "right" : "left", fontFamily: "var(--font-mono)" }}>{m.time}</div>
      </div>
    </div>
  );
}

Object.assign(window, { InvoicesView, FilesView, MessagesView, MessageBubble });
