// PortalTable Dashboard — secondary views: Files, Messages, Portal branding, Team, Settings.

const { useState: useStateM, useEffect: useEffectM } = React;

function usePdNarrow(maxWidth = 860) {
  const [narrow, setNarrow] = useStateM(() => typeof window !== "undefined" && window.matchMedia(`(max-width:${maxWidth}px)`).matches);
  useEffectM(() => {
    const mq = window.matchMedia(`(max-width:${maxWidth}px)`);
    const on = () => setNarrow(mq.matches);
    mq.addEventListener ? mq.addEventListener("change", on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", on) : mq.removeListener(on); };
  }, [maxWidth]);
  return narrow;
}

/* ========================================================================== */
/* FILES — grid of recent shared files                                         */
/* ========================================================================== */
const PD_FILES = [
  { name: "Brand-Guidelines-v3.pdf", kind: "pdf", size: "4.2 MB", client: "Northwind Studio", when: "2h ago" },
  { name: "Hero-Mock-Final.fig", kind: "fig", size: "11.8 MB", client: "Halcyon Health", when: "5h ago" },
  { name: "Summer-Banners.zip", kind: "zip", size: "28.4 MB", client: "Northstar Media", when: "1d ago" },
  { name: "Content-Calendar.xlsx", kind: "sheet", size: "320 KB", client: "Tidewater Co.", when: "1d ago" },
  { name: "Listing-Photos", kind: "folder", size: "62 items", client: "Birchwood Realty", when: "2d ago" },
  { name: "Fleet-Wireframes.pdf", kind: "pdf", size: "6.1 MB", client: "Orbit Logistics", when: "3d ago" },
];
function FilesView() {
  const tints = { pdf: ["var(--red)", "var(--red-soft)"], fig: ["var(--blue)", "var(--blue-soft)"], zip: ["var(--amber)", "var(--amber-soft)"], sheet: ["var(--green)", "var(--green-soft)"], folder: ["var(--teal)", "var(--teal-soft)"] };
  return (
    <div>
      <PageHeader title="Files" subtitle="Assets shared across client portals"
        actions={<Button variant="primary" size="md" icon="upload" onClick={() => window.pdToast({ tone: "success", title: "Upload ready", body: "Drop files to share with a client portal." })}>Upload</Button>} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 16 }}>
        {PD_FILES.map((f) => {
          const [fg, bg] = tints[f.kind] || ["var(--fg-2)", "var(--ink-800)"];
          return (
            <Surface key={f.name} hover pad={16} style={{ cursor: "pointer" }}>
              <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
                <span style={{ width: 40, height: 40, borderRadius: 10, display: "grid", placeItems: "center", background: bg, color: fg }}><Ic name={f.kind === "folder" ? "grid" : "file"} size={20} /></span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.06em", color: fg, textTransform: "uppercase" }}>{f.kind}</span>
              </div>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)", marginTop: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.name}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 3 }}>{f.size} · {f.client}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-4)", marginTop: 10 }}>{f.when}</div>
            </Surface>
          );
        })}
      </div>
    </div>
  );
}

/* ========================================================================== */
/* MESSAGES — thread list + reading pane                                       */
/* ========================================================================== */
const PD_THREADS = [
  { id: "t1", client: "Halcyon Health", who: "Devin Park", preview: "The intake form looks great — one note on the consent step…", when: "1h", unread: true, color: "#2D6FE0" },
  { id: "t2", client: "Northstar Media", who: "Jonah Klein", preview: "Approved the banners! Can we get a square format too?", when: "3h", unread: true, color: "#D9488B" },
  { id: "t3", client: "Northwind Studio", who: "Maya Okonkwo", preview: "Thanks for the quick turnaround on the hero copy.", when: "Yesterday", unread: false, color: "#0E9888" },
  { id: "t4", client: "Birchwood Realty", who: "Sam Hale", preview: "Sending over the listing photos this afternoon.", when: "2d", unread: false, color: "#15935E" },
];
function MessagesView() {
  const [active, setActive] = useStateM(PD_THREADS[0].id);
  const [draft, setDraft] = useStateM("");
  const [openThread, setOpenThread] = useStateM(false);
  const narrow = usePdNarrow(860);
  const thread = PD_THREADS.find((t) => t.id === active);
  const showList = !narrow || !openThread;
  const showPane = !narrow || openThread;
  function openConvo(id) { setActive(id); setOpenThread(true); }
  return (
    <div className="pd-msg-view" style={{ display: "flex", flexDirection: "column", height: "calc(100dvh - 152px)" }}>
      <PageHeader title="Messages" subtitle="Client conversations, in one place" />
      <Surface pad={0} style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "320px 1fr", flex: 1, minHeight: 0, overflow: "hidden" }} className="pd-msg-grid">
        <div className="pd-msg-list" style={{ display: showList ? "block" : "none", borderRight: narrow ? 0 : "1px solid var(--line-2)", overflowY: "auto", minHeight: 0 }}>
          {PD_THREADS.map((t) => (
            <button key={t.id} onClick={() => openConvo(t.id)}
              style={{ width: "100%", textAlign: "left", display: "flex", gap: 11, padding: "14px 16px", border: 0, borderBottom: "1px solid var(--line-1)", cursor: "pointer", background: (!narrow && active === t.id) ? "var(--ink-800)" : "transparent", fontFamily: "inherit" }}>
              <span style={{ width: 34, height: 34, borderRadius: 9, flexShrink: 0, display: "grid", placeItems: "center", background: t.color, color: "#fff", fontSize: 12, fontWeight: 600, fontFamily: "var(--font-mono)" }}>{t.client.split(" ").map((p) => p[0]).slice(0, 2).join("")}</span>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.client}</span>
                  {t.unread && <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--accent-press)", flexShrink: 0 }} />}
                  <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-4)", flexShrink: 0 }}>{t.when}</span>
                </div>
                <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.preview}</div>
              </div>
            </button>
          ))}
        </div>
        <div className="pd-msg-pane" style={{ display: showPane ? "flex" : "none", flexDirection: "column", minWidth: 0, minHeight: 0 }}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line-2)", display: "flex", alignItems: "center", gap: 11 }}>
            {narrow && (
              <button onClick={() => setOpenThread(false)} aria-label="Back to conversations"
                style={{ width: 32, height: 32, marginLeft: -6, flexShrink: 0, display: "grid", placeItems: "center", borderRadius: 8, background: "transparent", border: "1px solid transparent", color: "var(--fg-2)", cursor: "pointer" }}>
                <Ic name="chevronLeft" size={20} />
              </button>
            )}
            <span style={{ width: 32, height: 32, borderRadius: 8, flexShrink: 0, display: "grid", placeItems: "center", background: thread.color, color: "#fff", fontSize: 12, fontWeight: 600, fontFamily: "var(--font-mono)" }}>{thread.client.split(" ").map((p) => p[0]).slice(0, 2).join("")}</span>
            <div style={{ minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{thread.client}</div><div style={{ fontSize: 12, color: "var(--fg-3)" }}>{thread.who}</div></div>
          </div>
          <div style={{ flex: 1, minHeight: 0, padding: 20, display: "flex", flexDirection: "column", gap: 14, overflowY: "auto" }}>
            <div style={{ maxWidth: "78%", padding: "11px 14px", borderRadius: "12px 12px 12px 4px", background: "var(--ink-800)", fontSize: 13.5, color: "var(--fg-1)", lineHeight: 1.5 }}>{thread.preview}</div>
            <div style={{ maxWidth: "78%", alignSelf: "flex-end", padding: "11px 14px", borderRadius: "12px 12px 4px 12px", background: "var(--accent)", color: "var(--fg-inverse)", fontSize: 13.5, lineHeight: 1.5 }}>On it — I'll have a revision in the portal by end of day.</div>
          </div>
          <div style={{ padding: 14, borderTop: "1px solid var(--line-2)", display: "flex", gap: 10 }}>
            <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Write a reply…"
              onKeyDown={(e) => { if (e.key === "Enter" && draft.trim()) { window.pdToast({ tone: "success", title: "Reply sent", body: thread.client }); setDraft(""); } }}
              style={{ flex: 1, minWidth: 0, height: 40, padding: "0 13px", borderRadius: 9, fontSize: 13.5, background: "var(--ink-900)", color: "var(--fg-1)", border: "1px solid var(--line-3)", outline: "none" }} />
            <Button variant="primary" size="lg" icon="message" onClick={() => { if (draft.trim()) { window.pdToast({ tone: "success", title: "Reply sent", body: thread.client }); setDraft(""); } }}>Send</Button>
          </div>
        </div>
      </Surface>
    </div>
  );
}

/* ========================================================================== */
/* PORTAL BRANDING — white-label settings with live preview                    */
/* ========================================================================== */
function BrandingView() {
  const [name, setName] = useStateM("Northwind Studio");
  const [accent, setAccent] = useStateM("#0E9888");
  const [subdomain, setSubdomain] = useStateM("northwind");
  const [customDomain, setCustomDomain] = useStateM(true);
  const [showPortalTable, setShowPortalTable] = useStateM(false);
  const swatches = ["#0E9888", "#2D6FE0", "#7C5CE0", "#C8443B", "#B5790B", "#15935E", "#111317"];

  return (
    <div>
      <PageHeader title="Portal branding" subtitle="White-label the client experience — your name, your domain, your colors."
        actions={<Button variant="primary" size="md" icon="check" onClick={() => window.pdToast({ tone: "success", title: "Branding saved", body: "Changes are live on the client portal." })}>Save changes</Button>} />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="pd-chart-grid">
        <SectionCard title="Identity">
          <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
            <Setting label="Workspace name" hint="Shown in the portal header and emails.">
              <input value={name} onChange={(e) => setName(e.target.value)} style={inputStyleM} />
            </Setting>
            <Setting label="Accent color" hint="Applied to buttons, links, and highlights.">
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {swatches.map((s) => (
                  <button key={s} onClick={() => setAccent(s)} aria-label={s}
                    style={{ width: 30, height: 30, borderRadius: 8, background: s, cursor: "pointer", border: accent === s ? "2px solid var(--fg-1)" : "1px solid var(--line-3)", boxShadow: accent === s ? "0 0 0 2px var(--ink-900)" : "none", outline: accent === s ? "2px solid " + s : "none" }} />
                ))}
              </div>
            </Setting>
            <Setting label="Logo" hint="SVG or PNG, square. Falls back to workspace initials.">
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ width: 44, height: 44, borderRadius: 10, background: accent, color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontFamily: "var(--font-mono)" }}>{name.split(" ").map((p) => p[0]).slice(0, 2).join("")}</span>
                <Button variant="secondary" size="md" icon="upload">Upload logo</Button>
              </div>
            </Setting>
          </div>
        </SectionCard>

        <SectionCard title="Domain & visibility">
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Setting label="Portal subdomain">
              <div style={{ display: "flex", alignItems: "center", borderRadius: 9, border: "1px solid var(--line-3)", overflow: "hidden", background: "var(--ink-900)" }}>
                <input value={subdomain} onChange={(e) => setSubdomain(e.target.value)} style={{ ...inputStyleM, border: 0, borderRadius: 0, flex: 1 }} />
                <span style={{ padding: "0 12px", fontSize: 13, color: "var(--fg-3)", fontFamily: "var(--font-mono)", borderLeft: "1px solid var(--line-2)", height: 40, display: "grid", placeItems: "center", background: "var(--ink-950)" }}>.portaltable.com</span>
              </div>
            </Setting>
            <ToggleRow label="Custom domain" hint="portal.northwind.co · SSL active" checked={customDomain} onChange={setCustomDomain} />
            <ToggleRow label='Show "Powered by PortalTable"' hint="Off on Scale plan — fully white-label." checked={showPortalTable} onChange={setShowPortalTable} />
            <div style={{ marginTop: 4 }}>
              <div style={{ marginBottom: 10 }}><MonoLabel>Live preview</MonoLabel></div>
              <div style={{ borderRadius: 12, border: "1px solid var(--line-2)", overflow: "hidden", boxShadow: "var(--pd-shadow-sm)" }}>
                <div style={{ height: 44, background: accent, display: "flex", alignItems: "center", gap: 9, padding: "0 14px" }}>
                  <span style={{ width: 22, height: 22, borderRadius: 6, background: "rgba(255,255,255,0.9)", color: accent, display: "grid", placeItems: "center", fontSize: 9, fontWeight: 700, fontFamily: "var(--font-mono)" }}>{name.split(" ").map((p) => p[0]).slice(0, 2).join("")}</span>
                  <span style={{ color: "#fff", fontWeight: 600, fontSize: 13 }}>{name}</span>
                  <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10, color: "rgba(255,255,255,0.8)" }}>{customDomain ? "portal.northwind.co" : subdomain + ".portaltable.com"}</span>
                </div>
                <div style={{ padding: 16, background: "var(--ink-900)" }}>
                  <div style={{ height: 8, width: "45%", borderRadius: 4, background: "var(--ink-700)" }} />
                  <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                    <span style={{ height: 26, padding: "0 12px", borderRadius: 7, background: accent, color: "#fff", fontSize: 11, fontWeight: 600, display: "grid", placeItems: "center" }}>Approve</span>
                    <span style={{ height: 26, padding: "0 12px", borderRadius: 7, background: "var(--ink-800)", color: "var(--fg-2)", fontSize: 11, fontWeight: 500, display: "grid", placeItems: "center", border: "1px solid var(--line-2)" }}>Comment</span>
                  </div>
                  {!showPortalTable ? null : <div style={{ marginTop: 12, fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--fg-4)" }}>Powered by PortalTable</div>}
                </div>
              </div>
            </div>
          </div>
        </SectionCard>
      </div>
    </div>
  );
}
function Setting({ label, hint, children }) {
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)" }}>{label}</div>
      {hint && <div style={{ fontSize: 12, color: "var(--fg-3)", margin: "3px 0 9px" }}>{hint}</div>}
      {!hint && <div style={{ height: 9 }} />}
      {children}
    </div>
  );
}
function ToggleRow({ label, hint, checked, onChange }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)" }}>{label}</div>
        {hint && <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2 }}>{hint}</div>}
      </div>
      <Switch checked={checked} onChange={onChange} />
    </div>
  );
}
const inputStyleM = { width: "100%", height: 40, padding: "0 13px", boxSizing: "border-box", borderRadius: 9, fontSize: 13.5, background: "var(--ink-900)", color: "var(--fg-1)", border: "1px solid var(--line-3)", outline: "none" };

/* ========================================================================== */
/* TEAM                                                                        */
/* ========================================================================== */
const PD_TEAM = [
  { id: "u1", name: "You (Alex Rivera)", email: "alex@studio.com", role: "Owner", access: "All clients", color: "#111317", you: true },
  { id: "u2", name: "Maya Okonkwo", email: "maya@studio.com", role: "Admin", access: "All clients", color: "#0E9888" },
  { id: "u3", name: "Devin Park", email: "devin@studio.com", role: "Member", access: "4 clients", color: "#2D6FE0" },
  { id: "u4", name: "Priya Nair", email: "priya@studio.com", role: "Member", access: "3 clients", color: "#B5790B" },
  { id: "u5", name: "Jonah Klein", email: "jonah@studio.com", role: "Member", access: "2 clients", color: "#D9488B" },
];
function TeamView() {
  const SEATS_TOTAL = 20;
  const seatsUsed = PD_TEAM.length;
  const [inviteEmail, setInviteEmail] = useStateM("");
  const [inviteRole, setInviteRole] = useStateM("Member");
  const [linkInvites, setLinkInvites] = useStateM([]);
  function makeToken() { let s = ""; const h = "0123456789abcdef"; for (let i = 0; i < 64; i++) s += h[Math.floor(Math.random() * 16)]; return s; }
  function copyLink(url) {
    if (navigator.clipboard) navigator.clipboard.writeText(url);
    window.pdToast({ tone: "success", title: "Link copied" });
  }
  function sendInvite(e) {
    e.preventDefault();
    const email = inviteEmail.trim();
    if (!email) {
      const expires = new Date(Date.now() + 14 * 864e5).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
      setLinkInvites((prev) => [{ id: Date.now(), role: inviteRole, expires, token: makeToken() }, ...prev]);
      window.pdToast({ tone: "success", title: "Invite link created", body: `Anyone with the link joins as ${inviteRole}` });
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      window.pdToast({ tone: "error", title: "Enter a valid email" });
      return;
    }
    window.pdToast({ tone: "success", title: "Invite sent", body: `${email} · ${inviteRole}` });
    setInviteEmail("");
  }
  const columns = [
    { key: "name", header: "Member", sortable: true, render: (r) => <div style={{ display: "flex", alignItems: "center", gap: 11 }}><span style={{ width: 32, height: 32, borderRadius: 999, background: r.color, color: "#fff", display: "grid", placeItems: "center", fontSize: 11.5, fontWeight: 600, fontFamily: "var(--font-mono)" }}>{r.name.replace(/[()]/g, "").split(" ").map((p) => p[0]).slice(0, 2).join("")}</span><div><div style={{ fontWeight: 600, color: "var(--fg-1)", fontSize: 13.5 }}>{r.name}</div><div style={{ fontSize: 12, color: "var(--fg-3)" }}>{r.email}</div></div></div> },
    { key: "role", header: "Role", sortable: true, render: (r) => <Pill tone={r.role === "Owner" ? "accent" : r.role === "Admin" ? "blue" : "neutral"}>{r.role}</Pill> },
    { key: "access", header: "Portal access", sortable: true, render: (r) => <span style={{ fontSize: 13, color: "var(--fg-2)" }}>{r.access}</span> },
    { key: "_act", header: "", align: "right", width: 52, render: (r) => r.you ? <span style={{ fontSize: 12, color: "var(--fg-4)" }}>—</span> : (
      <DropdownMenu align="right" width={170} trigger={(open) => <span style={{ width: 28, height: 28, display: "grid", placeItems: "center", borderRadius: 7, cursor: "pointer", color: "var(--fg-3)", background: open ? "var(--ink-800)" : "transparent" }}><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.6" /><circle cx="12" cy="12" r="1.6" /><circle cx="12" cy="19" r="1.6" /></svg></span>}
        items={[{ label: "Change role", icon: "users", onClick: () => window.pdToast(r.name) }, { label: "Manage access", icon: "shield", onClick: () => window.pdToast(r.name) }, { separator: true }, { label: "Remove", icon: "x", tone: "danger", onClick: () => window.pdToast({ tone: "error", title: "Removed", body: r.name }) }] } />
    ) },
  ];
  return (
    <div>
      <PageHeader title="Team" subtitle={`${PD_TEAM.length} people · invite teammates and scope them to specific client portals`} />
      <SectionCard title="Invite teammates"
        action={<Pill tone={seatsUsed >= SEATS_TOTAL ? "amber" : "neutral"}>{seatsUsed} / {SEATS_TOTAL} seats</Pill>}
        style={{ marginBottom: 20 }}>
        <form onSubmit={sendInvite} style={{ display: "flex", alignItems: "flex-end", gap: 12, flexWrap: "wrap" }}>
          <label style={{ flex: "1 1 260px", display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>Email address</span>
            <input type="email" value={inviteEmail} onChange={(e) => setInviteEmail(e.target.value)} placeholder="teammate@studio.com" style={inputStyleM} />
          </label>
          <label style={{ flex: "0 0 150px", display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>Role</span>
            <div style={{ position: "relative" }}>
              <select value={inviteRole} onChange={(e) => setInviteRole(e.target.value)} style={{ ...inputStyleM, appearance: "none", cursor: "pointer" }}>
                <option>Member</option>
                <option>Admin</option>
              </select>
              <span style={{ position: "absolute", right: 12, top: 12, color: "var(--fg-3)", pointerEvents: "none" }}><Ic name="arrowDown" size={15} /></span>
            </div>
          </label>
          <Button variant="primary" size="lg" icon="plus" type="submit">Send invite</Button>
        </form>
        <p style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.5, margin: "14px 0 0" }}>Leave the email blank for a link anyone can use. Links expire in 14 days.</p>
      </SectionCard>
      {linkInvites.length > 0 && (
        <SectionCard title="Pending invites" style={{ marginBottom: 20 }}>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {linkInvites.map((inv, idx) => {
              const url = `https://portaltable.com/invite/${inv.token}`;
              return (
                <div key={inv.id} style={{ display: "flex", flexDirection: "column", gap: 10, padding: "16px 0", borderTop: idx === 0 ? "none" : "1px solid var(--line-2)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <span style={{ width: 32, height: 32, borderRadius: 8, display: "grid", placeItems: "center", background: "var(--ink-800)", color: "var(--fg-2)", flexShrink: 0 }}><Ic name="link" size={16} /></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)" }}>Anyone with the link</div>
                      <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 1 }}>{inv.role} · expires {inv.expires}</div>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => setLinkInvites((prev) => prev.filter((x) => x.id !== inv.id))}>Revoke</Button>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <div style={{ flex: 1, minWidth: 0, height: 36, display: "flex", alignItems: "center", padding: "0 12px", borderRadius: 8, background: "var(--ink-800)", border: "1px solid var(--line-2)", fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-2)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{url}</div>
                    <Button variant="secondary" size="sm" onClick={() => copyLink(url)}>Copy</Button>
                  </div>
                </div>
              );
            })}
          </div>
        </SectionCard>
      )}
      <Surface pad={0}><DataTable columns={columns} rows={PD_TEAM} initialSort={{ key: "role", dir: "asc" }} /></Surface>
    </div>
  );
}

/* ========================================================================== */
/* SETTINGS                                                                     */
/* ========================================================================== */
function SettingsView() {
  const [tab, setTab] = useStateM("general");
  const [notif, setNotif] = useStateM({ approvals: true, messages: true, payments: true, weekly: false });
  return (
    <div>
      <PageHeader title="Settings" subtitle="Workspace preferences and integrations" />
      <Tabs style={{ marginBottom: 20 }} value={tab} onChange={setTab}
        tabs={[{ id: "general", label: "General" }, { id: "notifications", label: "Notifications" }, { id: "integrations", label: "Integrations" }, { id: "billing", label: "Billing" }]} />
      {tab === "general" && (
        <SectionCard title="Workspace" style={{ maxWidth: 620 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Setting label="Workspaces" hint="Each workspace is a separate set of client portals."><div style={{ position: "relative" }}><select style={{ ...inputStyleM, appearance: "none", cursor: "pointer" }}><option>Studio Northstar</option><option>Northstar — EU</option><option>Internal projects</option></select><span style={{ position: "absolute", right: 12, top: 12, color: "var(--fg-3)", pointerEvents: "none" }}><Ic name="arrowDown" size={15} /></span></div></Setting>
            <Setting label="Support email" hint="Where client replies are routed."><input defaultValue="hello@studio.com" style={inputStyleM} /></Setting>
          </div>
        </SectionCard>
      )}
      {tab === "notifications" && (
        <SectionCard title="Email notifications" style={{ maxWidth: 620 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <ToggleRow label="New approval requests" hint="When a client submits something for review" checked={notif.approvals} onChange={(v) => setNotif({ ...notif, approvals: v })} />
            <ToggleRow label="Client messages" hint="New replies in portal conversations" checked={notif.messages} onChange={(v) => setNotif({ ...notif, messages: v })} />
            <ToggleRow label="Payments" hint="Invoice paid, due, or overdue" checked={notif.payments} onChange={(v) => setNotif({ ...notif, payments: v })} />
            <ToggleRow label="Weekly digest" hint="A Monday summary across all portals" checked={notif.weekly} onChange={(v) => setNotif({ ...notif, weekly: v })} />
          </div>
        </SectionCard>
      )}
      {tab === "integrations" && (
        <div style={{ maxWidth: 620, display: "flex", flexDirection: "column", gap: 16 }}>
          {[{ n: "Your workspace", d: "Source of truth for every portal", on: true, ic: "database" }].map((i) => (
            <Surface key={i.n} pad={16} style={{ display: "flex", alignItems: "center", gap: 13 }}>
              <span style={{ width: 40, height: 40, borderRadius: 10, display: "grid", placeItems: "center", background: i.on ? "var(--accent)" : "var(--ink-800)", color: i.on ? "var(--fg-inverse)" : "var(--fg-2)" }}><Ic name={i.ic} size={19} /></span>
              <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-1)" }}>{i.n}</div><div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 1 }}>{i.d}</div></div>
              {i.on ? <Pill tone="green" dot>Connected</Pill> : <Button variant="secondary" size="sm" onClick={() => window.pdToast({ tone: "success", title: "Connected", body: i.n })}>Connect</Button>}
            </Surface>
          ))}
          <SectionCard title="Workspace data" action={<Button variant="secondary" size="sm">Manage</Button>}>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {[
                { n: "Studio Northstar HQ", tables: 6, rec: 270 },
                { n: "Client Delivery", tables: 4, rec: 184 },
                { n: "Finance & Invoicing", tables: 3, rec: 92 },
              ].map((t, idx) => (
                <div key={t.n} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderTop: idx === 0 ? "none" : "1px solid var(--line-2)" }}>
                  <span style={{ width: 32, height: 32, borderRadius: 8, display: "grid", placeItems: "center", background: "var(--ink-800)", color: "var(--fg-2)", flexShrink: 0 }}><Ic name="database" size={16} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)" }}>{t.n}</div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-3)", marginTop: 1 }}>{t.tables} tables · {t.rec} records</div>
                  </div>
                  <Pill tone="green" dot>Live</Pill>
                </div>
              ))}
            </div>
          </SectionCard>
        </div>
      )}
      {tab === "billing" && (
        <SectionCard title="Your plan" style={{ maxWidth: 620 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9 }}><span style={{ fontSize: 20, fontWeight: 600, color: "var(--fg-1)" }}>Agency</span><Pill tone="accent">Current</Pill></div>
              <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 4 }}>Unlimited client portals · $149/mo · renews Jul 1</div>
            </div>
            <Button variant="secondary" size="md">Manage billing</Button>
          </div>
        </SectionCard>
      )}
    </div>
  );
}

Object.assign(window, { FilesView, MessagesView, BrandingView, TeamView, SettingsView });
