/* Willow Creek Portal — Admin & House Manager: approvals, houses, residents, payments, forms CMS, rates & site content.
   role="admin" (full) or "manager" (house manager — minimum admin access: no forms builder, no rates/site content). */
const { PIcon: AIcon, PSection: ASection, KindBadge: AKindBadge, makeReceiptNo: aMakeReceiptNo, ReceiptModal: AReceiptModal } = window.WCPortal;
const { useState: adUseState } = React;

function AdminPortal({ store, setStore, onLogout, role = "admin" }) {
  const [tab, setTab] = adUseState("approvals");
  const isAdmin = role === "admin";
  const navItems = [
    ["approvals", "inbox", "Approvals"],
    ["houses", "home", "Houses & beds"],
    ["residents", "users", "Residents"],
    ["payments", "receipt-text", "Payments"],
    ...(isAdmin ? [
      ["forms", "file-stack", "Forms builder"],
      ["cms", "panel-top", "Rates & site content"],
    ] : []),
  ];
  const pending = store.applications.filter((a) => a.status === "pending").length;

  return (
    <div style={{ display: "flex", minHeight: "100vh", background: "var(--surface-sunken)" }} className="wcp-shell">
      <aside style={{ width: 250, flexShrink: 0, background: "var(--ink-900)", color: "var(--sand-200)",
        display: "flex", flexDirection: "column", padding: "22px 16px" }} className="wcp-sidebar">
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 30 }}>
          <img src="../assets/logo-mark.svg" alt="" style={{ height: 34 }} />
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, color: "#fffdf8", fontSize: 16, letterSpacing: "0.03em", textTransform: "uppercase" }}>{isAdmin ? "Admin" : "Manager"}</div>
            <div style={{ fontSize: 11, color: "var(--sand-400)" }}>Willow Creek</div>
          </div>
        </div>
        <nav style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          {navItems.map(([id, icon, label]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", borderRadius: "var(--radius-md)",
              background: tab === id ? "rgba(255,255,255,.1)" : "transparent", border: "none", cursor: "pointer",
              color: tab === id ? "#fffdf8" : "var(--sand-300)", fontFamily: "var(--font-sans)", fontWeight: 600,
              fontSize: "var(--text-sm)", textAlign: "left", transition: "all var(--dur-fast) var(--ease-out)",
            }}>
              <AIcon name={icon} size={18} /> {label}
              {id === "approvals" && pending > 0 && (
                <span style={{ marginLeft: "auto", background: "var(--clay-500)", color: "#fffdf8", borderRadius: 999,
                  fontSize: 11, fontWeight: 700, padding: "2px 8px" }}>{pending}</span>
              )}
            </button>
          ))}
        </nav>
        <div style={{ marginTop: "auto", paddingTop: 20, borderTop: "1px solid rgba(255,255,255,.1)" }}>
          {!isAdmin && (
            <div style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "rgba(214,154,104,.18)", color: "var(--clay-400)",
              fontSize: 11, fontWeight: 700, padding: "4px 10px", borderRadius: 999, marginBottom: 12, letterSpacing: "0.04em" }}>
              <AIcon name="shield-alert" size={12} /> LIMITED ACCESS
            </div>
          )}
          <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "#fffdf8" }}>{isAdmin ? "Rebecca Hale" : "James Ortiz"}</div>
          <div style={{ fontSize: 12, color: "var(--sand-400)", margin: "2px 0 12px" }}>{isAdmin ? "Founder & Director · System admin" : "House Manager · Creekside"}</div>
          <button onClick={onLogout} style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "none",
            border: "none", cursor: "pointer", color: "var(--sand-300)", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "var(--text-sm)", padding: 0 }}>
            <AIcon name="log-out" size={15} /> Sign out</button>
        </div>
      </aside>

      <main style={{ flex: 1, padding: "34px clamp(20px, 4vw, 48px)", maxWidth: 1120 }}>
        {tab === "approvals" && <ApprovalsTab store={store} setStore={setStore} />}
        {tab === "houses" && <HousesTab store={store} setStore={setStore} />}
        {tab === "residents" && <ResidentsTab store={store} setStore={setStore} />}
        {tab === "payments" && <PaymentsTab store={store} setStore={setStore} />}
        {tab === "forms" && isAdmin && <FormsTab store={store} setStore={setStore} />}
        {tab === "cms" && isAdmin && <CmsTab store={store} setStore={setStore} />}
      </main>
    </div>
  );
}

/* ---------- Approvals ---------- */
function ApprovalsTab({ store, setStore }) {
  const { Card, Button, Badge } = window.WillowCreekDesignSystem_90378c;
  const published = store.forms.filter((f) => f.status === "published");
  const act = (id, status) => setStore((s) => {
    const app = s.applications.find((a) => a.id === id);
    let residents = s.residents;
    if (status === "approved" && app && !s.residents.some((r) => r.name === app.name)) {
      residents = [...s.residents, { id: "r" + Date.now(), name: app.name, phone: app.phone || "—",
        house: "Awaiting bed", phase: 1, status: "Onboarding", balance: s.cms.weeklyRate }];
    }
    return { ...s, residents, applications: s.applications.map((a) => a.id === id ? { ...a, status } : a) };
  });
  return (
    <>
      <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 4px" }}>Applications & approvals</h2>
      <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>New intake applications from the website land here. Approving adds the person to Residents automatically.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {store.applications.map((a) => {
          const signedCount = (store.signedForms[a.name] || []).length;
          const allSigned = published.length > 0 && signedCount >= published.length;
          return (
          <Card key={a.id} elevation="sm" padding="md" style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
            <span style={{ width: 44, height: 44, borderRadius: "50%", flexShrink: 0, background: "var(--surface-accent-soft)",
              color: "var(--brand-primary)", display: "inline-flex", alignItems: "center", justifyContent: "center",
              fontFamily: "var(--font-display)", fontWeight: 800 }}>{a.name.split(" ").map((w) => w[0]).join("")}</span>
            <div style={{ flex: 1, minWidth: 180 }}>
              <strong style={{ color: "var(--text-heading)" }}>{a.name}</strong>
              <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>{a.situation} · Submitted {a.submitted}</div>
            </div>
            {a.status === "approved" && (
              <Badge variant={allSigned ? "success" : "warning"} size="sm">
                {allSigned ? "All forms signed" : `${signedCount}/${published.length} forms signed`}
              </Badge>
            )}
            {a.status === "pending" ? (
              <div style={{ display: "flex", gap: 8 }}>
                <Button variant="secondary" size="sm" onClick={() => act(a.id, "declined")}>Decline</Button>
                <Button variant="primary" size="sm" onClick={() => act(a.id, "approved")}
                  leftIcon={<AIcon name="check" size={15} />}>Approve</Button>
              </div>
            ) : (
              <Badge variant={a.status === "approved" ? "success" : "danger"} dot>{a.status === "approved" ? "Approved · in Residents" : "Declined"}</Badge>
            )}
          </Card>
        );})}
      </div>
    </>
  );
}

/* ---------- Houses & beds ---------- */
function HousesTab({ store, setStore }) {
  const { Card, Button, Badge, Select, Input } = window.WillowCreekDesignSystem_90378c;
  const [assigning, setAssigning] = adUseState(null); // bed id
  const unhoused = store.residents.filter((r) => !store.houses.some((h) => h.beds.some((b) => b.resident === r.name)));

  const setManager = (houseId, manager) =>
    setStore((s) => ({ ...s, houses: s.houses.map((h) => h.id === houseId ? { ...h, manager } : h) }));
  const addBed = (houseId) =>
    setStore((s) => ({ ...s, houses: s.houses.map((h) => h.id === houseId
      ? { ...h, beds: [...h.beds, { id: "b" + Date.now(), label: `Bed ${h.beds.length + 1} (new)`, resident: null }] } : h) }));
  const assign = (bedId, name) => {
    setStore((s) => ({ ...s, houses: s.houses.map((h) => ({ ...h, beds: h.beds.map((b) =>
      b.id === bedId ? { ...b, resident: name || null } : (name && b.resident === name ? { ...b, resident: null } : b)) })) }));
    setAssigning(null);
  };

  return (
    <>
      <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 4px" }}>Houses & bed allocation</h2>
      <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>Assign house managers, add beds, and allocate residents.</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, alignItems: "start" }} className="wcp-two">
        {store.houses.map((h) => {
          const open = h.beds.filter((b) => !b.resident).length;
          return (
            <Card key={h.id} elevation="sm" padding="lg">
              <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10, marginBottom: 4 }}>
                <div>
                  <h3 style={{ margin: 0, fontSize: "var(--text-xl)" }}>{h.name}</h3>
                  <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>{h.address}</div>
                </div>
                <Badge variant={open > 0 ? "success" : "neutral"} dot>{open > 0 ? `${open} open` : "Full"}</Badge>
              </div>
              <div style={{ margin: "14px 0" }}>
                <Select label="House manager" value={h.manager} onChange={(e) => setManager(h.id, e.target.value)} options={store.staff} />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {h.beds.map((b) => (
                  <div key={b.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px",
                    background: "var(--surface-sunken)", borderRadius: "var(--radius-md)" }}>
                    <AIcon name="bed" size={17} color={b.resident ? "var(--brand-primary)" : "var(--text-subtle)"} />
                    <span style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-heading)", flex: 1 }}>{b.label}</span>
                    {assigning === b.id ? (
                      <select autoFocus onChange={(e) => assign(b.id, e.target.value)} defaultValue=""
                        style={{ fontFamily: "var(--font-sans)", fontSize: 13, padding: "5px 8px", borderRadius: 6, border: "1px solid var(--border-default)" }}>
                        <option value="">— Unassigned —</option>
                        {store.residents.map((r) => <option key={r.id} value={r.name}>{r.name}</option>)}
                      </select>
                    ) : b.resident ? (
                      <button onClick={() => setAssigning(b.id)} style={{ background: "none", border: "none", cursor: "pointer",
                        fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-body)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                        {b.resident} <AIcon name="pencil" size={13} color="var(--text-subtle)" /></button>
                    ) : (
                      <Button variant="ghost" size="sm" onClick={() => setAssigning(b.id)}>Assign</Button>
                    )}
                  </div>
                ))}
              </div>
              <Button variant="secondary" size="sm" style={{ marginTop: 14 }} onClick={() => addBed(h.id)}
                leftIcon={<AIcon name="plus" size={15} />}>Add bed</Button>
            </Card>
          );
        })}
      </div>
      {unhoused.length > 0 && (
        <p style={{ marginTop: 18, fontSize: "var(--text-sm)", color: "var(--clay-600)", fontWeight: 600 }}>
          Awaiting a bed: {unhoused.map((r) => r.name).join(", ")}
        </p>
      )}
    </>
  );
}

/* ---------- Residents ---------- */
function ResidentsTab({ store, setStore }) {
  const { Card, Button, Badge, Input, Select } = window.WillowCreekDesignSystem_90378c;
  const [adding, setAdding] = adUseState(false);
  const [draft, setDraft] = adUseState({ name: "", phone: "", house: "Creekside House" });
  const published = store.forms.filter((f) => f.status === "published");
  const addResident = () => {
    if (!draft.name.trim()) return;
    setStore((s) => ({ ...s, residents: [...s.residents, { id: "r" + Date.now(), name: draft.name.trim(), phone: draft.phone, house: draft.house, phase: 1, status: "Active", balance: s.cms.weeklyRate }] }));
    setDraft({ name: "", phone: "", house: "Creekside House" });
    setAdding(false);
  };
  return (
    <>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
        <h2 style={{ fontSize: "var(--text-d3)", margin: 0 }}>Residents</h2>
        <Button variant="primary" size="sm" onClick={() => setAdding(!adding)} leftIcon={<AIcon name="user-plus" size={15} />}>Add resident</Button>
      </div>
      <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>Phase, paperwork, and balance at a glance.</p>
      {adding && (
        <Card elevation="md" padding="lg" style={{ marginBottom: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr 1fr auto", gap: 12, alignItems: "end" }} className="wcp-addrow">
            <Input label="Full name" value={draft.name} onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))} placeholder="Jordan Rivera" />
            <Input label="Phone" value={draft.phone} onChange={(e) => setDraft((d) => ({ ...d, phone: e.target.value }))} placeholder="(940) 555-0100" />
            <Select label="House" value={draft.house} onChange={(e) => setDraft((d) => ({ ...d, house: e.target.value }))} options={store.houses.map((h) => h.name)} />
            <Button variant="accent" onClick={addResident}>Save</Button>
          </div>
        </Card>
      )}
      <Card elevation="sm" padding="none">
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)" }}>
          <thead>
            <tr style={{ textAlign: "left", color: "var(--text-muted)", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em" }}>
              {["Resident", "House", "Phase", "Paperwork", "Balance", "Status"].map((hd) => (
                <th key={hd} style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", fontWeight: 700 }}>{hd}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {store.residents.map((r) => {
              const signedCount = (store.signedForms[r.name] || []).length;
              return (
                <tr key={r.id}>
                  <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
                    <strong style={{ color: "var(--text-heading)" }}>{r.name}</strong>
                    <div style={{ color: "var(--text-muted)", fontSize: 12 }}>{r.phone}</div>
                  </td>
                  <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", color: "var(--text-body)" }}>{r.house}</td>
                  <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", color: "var(--text-body)" }}>Phase {r.phase}</td>
                  <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
                    <Badge variant={signedCount >= published.length ? "success" : "warning"} size="sm">{signedCount}/{published.length} signed</Badge>
                  </td>
                  <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", fontWeight: 700,
                    color: r.balance > 0 ? "var(--clay-600)" : "var(--text-body)" }}>${r.balance}</td>
                  <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
                    <Badge variant="forest" size="sm" dot>{r.status}</Badge>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </>
  );
}

/* ---------- Forms builder ---------- */
function FormsTab({ store, setStore }) {
  const { Card, Button, Badge, Input, Textarea, Select } = window.WillowCreekDesignSystem_90378c;
  const [editing, setEditing] = adUseState(null); // form id or "new"
  const blank = { title: "", kind: "form", required: false, status: "draft", body: "", fields: [{ label: "Full legal name", type: "text" }] };
  const [draft, setDraft] = adUseState(blank);

  const startEdit = (f) => { setDraft(f ? JSON.parse(JSON.stringify(f)) : { ...blank }); setEditing(f ? f.id : "new"); };
  const save = () => {
    if (!draft.title.trim()) return;
    setStore((s) => editing === "new"
      ? { ...s, forms: [...s.forms, { ...draft, id: "f" + Date.now() }] }
      : { ...s, forms: s.forms.map((f) => f.id === editing ? { ...draft, id: f.id } : f) });
    setEditing(null);
  };
  const togglePublish = (id) => setStore((s) => ({ ...s, forms: s.forms.map((f) => f.id === id ? { ...f, status: f.status === "published" ? "draft" : "published" } : f) }));
  const remove = (id) => setStore((s) => ({ ...s, forms: s.forms.filter((f) => f.id !== id) }));

  if (editing) {
    return (
      <div style={{ maxWidth: 720 }}>
        <button onClick={() => setEditing(null)} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none",
          cursor: "pointer", color: "var(--text-link)", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "var(--text-sm)", padding: 0, marginBottom: 16 }}>
          <AIcon name="arrow-left" size={16} /> All forms
        </button>
        <Card elevation="lg" padding="xl">
          <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 20px" }}>{editing === "new" ? "New form" : "Edit form"}</h2>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Input label="Title" value={draft.title} onChange={(e) => setDraft((d) => ({ ...d, title: e.target.value }))} placeholder="e.g. Overnight Pass Request" />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Select label="Type" value={draft.kind} onChange={(e) => setDraft((d) => ({ ...d, kind: e.target.value }))}
                options={[{ value: "waiver", label: "Waiver" }, { value: "declaration", label: "Declaration" }, { value: "form", label: "General form" }]} />
              <Select label="Requirement" value={draft.required ? "req" : "opt"} onChange={(e) => setDraft((d) => ({ ...d, required: e.target.value === "req" }))}
                options={[{ value: "req", label: "Required for all residents" }, { value: "opt", label: "Optional" }]} />
            </div>
            <Textarea label="Document text" rows={6} value={draft.body} onChange={(e) => setDraft((d) => ({ ...d, body: e.target.value }))}
              hint="This is the text residents read and agree to." />
            <div>
              <label style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-heading)", display: "block", marginBottom: 8 }}>Fillable fields</label>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {draft.fields.map((fl, i) => (
                  <div key={i} style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <input value={fl.label} onChange={(e) => setDraft((d) => ({ ...d, fields: d.fields.map((x, j) => j === i ? { ...x, label: e.target.value } : x) }))}
                      style={{ flex: 1, padding: "9px 12px", borderRadius: "var(--radius-sm)", border: "1.5px solid var(--border-default)",
                        fontFamily: "var(--font-sans)", fontSize: 14 }} placeholder="Field label" />
                    <select value={fl.type} onChange={(e) => setDraft((d) => ({ ...d, fields: d.fields.map((x, j) => j === i ? { ...x, type: e.target.value } : x) }))}
                      style={{ padding: "9px 10px", borderRadius: "var(--radius-sm)", border: "1.5px solid var(--border-default)", fontFamily: "var(--font-sans)", fontSize: 13 }}>
                      <option value="text">Text</option><option value="date">Date</option><option value="textarea">Paragraph</option>
                    </select>
                    <button onClick={() => setDraft((d) => ({ ...d, fields: d.fields.filter((_, j) => j !== i) }))} aria-label="Remove field"
                      style={{ background: "none", border: "none", cursor: "pointer", color: "var(--danger)", display: "inline-flex" }}>
                      <AIcon name="trash-2" size={17} /></button>
                  </div>
                ))}
              </div>
              <Button variant="ghost" size="sm" style={{ marginTop: 10 }} leftIcon={<AIcon name="plus" size={14} />}
                onClick={() => setDraft((d) => ({ ...d, fields: [...d.fields, { label: "", type: "text" }] }))}>Add field</Button>
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", paddingTop: 8, borderTop: "1px solid var(--border-subtle)" }}>
              <Button variant="ghost" onClick={() => setEditing(null)}>Cancel</Button>
              <Button variant="primary" onClick={save} leftIcon={<AIcon name="save" size={16} />}>Save form</Button>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
        <h2 style={{ fontSize: "var(--text-d3)", margin: 0 }}>Forms builder</h2>
        <Button variant="primary" size="sm" onClick={() => startEdit(null)} leftIcon={<AIcon name="plus" size={15} />}>New form</Button>
      </div>
      <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>Waivers, declarations and fillable forms residents sign in their portal.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {store.forms.map((f) => (
          <Card key={f.id} elevation="sm" padding="md" style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
            <AIcon name={f.kind === "waiver" ? "shield" : f.kind === "declaration" ? "scroll-text" : "file-text"} size={22} color="var(--brand-primary)" />
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <strong style={{ color: "var(--text-heading)" }}>{f.title}</strong>
                <AKindBadge kind={f.kind} />
                {f.required && <Badge variant="warning" size="sm">Required</Badge>}
              </div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 2 }}>{f.fields.length} field{f.fields.length !== 1 ? "s" : ""} + signature</div>
            </div>
            <Badge variant={f.status === "published" ? "success" : "neutral"} dot>{f.status === "published" ? "Published" : "Draft"}</Badge>
            <div style={{ display: "flex", gap: 6 }}>
              <Button variant="ghost" size="sm" onClick={() => togglePublish(f.id)}>{f.status === "published" ? "Unpublish" : "Publish"}</Button>
              <Button variant="secondary" size="sm" onClick={() => startEdit(f)} leftIcon={<AIcon name="pencil" size={14} />}>Edit</Button>
              <button onClick={() => remove(f.id)} aria-label="Delete form" style={{ background: "none", border: "none", cursor: "pointer", color: "var(--danger)", display: "inline-flex", padding: 6 }}>
                <AIcon name="trash-2" size={17} /></button>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

/* ---------- Payments (all residents) ---------- */
function PaymentsTab({ store, setStore }) {
  const { Card, Button, Badge, Select } = window.WillowCreekDesignSystem_90378c;
  const [filter, setFilter] = adUseState("All residents");
  const [receipt, setReceipt] = adUseState(null);
  const rows = store.payments.filter((p) => filter === "All residents" || p.resident === filter);
  const regenerate = (p) => {
    const updated = { ...p, receiptNo: aMakeReceiptNo() };
    setStore((s) => ({ ...s, payments: s.payments.map((x) => x.id === p.id ? updated : x) }));
    setReceipt(updated);
  };
  const collected = rows.reduce((sum, p) => sum + p.amount, 0);
  return (
    <>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 14, marginBottom: 4, flexWrap: "wrap" }}>
        <div>
          <h2 style={{ fontSize: "var(--text-d3)", margin: 0 }}>Payments</h2>
          <p style={{ color: "var(--text-muted)", margin: "4px 0 0" }}>Processed securely via Stripe. Regenerate and reprint any receipt.</p>
        </div>
        <div style={{ width: 220 }}>
          <Select value={filter} onChange={(e) => setFilter(e.target.value)}
            options={["All residents", ...store.residents.map((r) => r.name)]} />
        </div>
      </div>
      <div style={{ display: "flex", gap: 20, margin: "18px 0", flexWrap: "wrap" }}>
        <Card elevation="sm" padding="md" style={{ minWidth: 180 }}>
          <div style={{ fontSize: 12, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 700 }}>Collected</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 30, color: "var(--brand-primary)" }}>${collected}</div>
        </Card>
        <Card elevation="sm" padding="md" style={{ minWidth: 180 }}>
          <div style={{ fontSize: 12, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 700 }}>Outstanding</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 30, color: "var(--clay-600)" }}>
            ${store.residents.reduce((sum, r) => sum + r.balance, 0)}</div>
        </Card>
      </div>
      <Card elevation="sm" padding="none">
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)" }}>
          <thead>
            <tr style={{ textAlign: "left", color: "var(--text-muted)", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em" }}>
              {["Receipt #", "Resident", "Date", "Method", "Amount", "Status", ""].map((hd, i) => (
                <th key={i} style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", fontWeight: 700 }}>{hd}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((p) => (
              <tr key={p.id}>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", fontWeight: 700, color: "var(--text-heading)" }}>{p.receiptNo}</td>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", color: "var(--text-body)" }}>{p.resident}</td>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", color: "var(--text-body)" }}>{p.date}</td>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", color: "var(--text-body)" }}>{p.method}</td>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", fontWeight: 700, color: "var(--text-heading)" }}>${p.amount}</td>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)" }}><Badge variant="success" size="sm" dot>{p.status}</Badge></td>
                <td style={{ padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)", textAlign: "right", whiteSpace: "nowrap" }}>
                  <Button variant="ghost" size="sm" onClick={() => setReceipt(p)} leftIcon={<AIcon name="receipt-text" size={14} />}>Receipt</Button>
                  <Button variant="secondary" size="sm" onClick={() => regenerate(p)} leftIcon={<AIcon name="refresh-cw" size={13} />}>Regenerate</Button>
                </td>
              </tr>
            ))}
            {rows.length === 0 && (
              <tr><td colSpan={7} style={{ padding: "22px 18px", color: "var(--text-muted)", textAlign: "center" }}>No payments yet for this resident.</td></tr>
            )}
          </tbody>
        </table>
      </Card>
      {receipt && <AReceiptModal payment={receipt} cms={store.cms} onClose={() => setReceipt(null)} onRegenerate={() => regenerate(receipt)} />}
    </>
  );
}

/* ---------- CMS ---------- */
function CmsTab({ store, setStore }) {
  const { Card, Button, Input, Textarea, Alert } = window.WillowCreekDesignSystem_90378c;
  const [draft, setDraft] = adUseState(store.cms);
  const [saved, setSaved] = adUseState(false);
  const save = () => { setStore((s) => ({ ...s, cms: draft })); setSaved(true); setTimeout(() => setSaved(false), 2200); };
  return (
    <>
      <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 4px" }}>Rates & site content</h2>
      <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>Set program rates and edit what the public website says. Admin only.</p>
      <div style={{ maxWidth: 680 }}>
        {saved && <Alert variant="success" title="Saved" style={{ marginBottom: 16 }}>Content updated. The website will reflect it on next publish.</Alert>}
        <Card elevation="sm" padding="lg" style={{ marginBottom: 18 }}>
          <h3 style={{ margin: "0 0 4px", fontSize: "var(--text-lg)" }}>Rates & billing</h3>
          <p style={{ color: "var(--text-muted)", fontSize: "var(--text-sm)", margin: "0 0 16px" }}>Changes apply to new balances and are reflected in resident portals.</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }} className="wcp-addrow">
            <Input label="Weekly rate ($)" type="number" value={draft.weeklyRate} onChange={(e) => setDraft((d) => ({ ...d, weeklyRate: +e.target.value }))} />
            <Input label="Move-in deposit ($)" type="number" value={draft.depositFee ?? 150} onChange={(e) => setDraft((d) => ({ ...d, depositFee: +e.target.value }))} />
            <Input label="Late fee ($)" type="number" value={draft.lateFee ?? 25} onChange={(e) => setDraft((d) => ({ ...d, lateFee: +e.target.value }))} />
          </div>
        </Card>
        <Card elevation="sm" padding="lg">
          <h3 style={{ margin: "0 0 16px", fontSize: "var(--text-lg)" }}>Website content</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Input label="Hero headline" value={draft.heroHeadline} onChange={(e) => setDraft((d) => ({ ...d, heroHeadline: e.target.value }))} />
            <Textarea label="Hero subtitle" rows={3} value={draft.heroSub} onChange={(e) => setDraft((d) => ({ ...d, heroSub: e.target.value }))} />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="wcp-addrow">
              <Input label="Availability note" value={draft.bedsOpenNote} onChange={(e) => setDraft((d) => ({ ...d, bedsOpenNote: e.target.value }))} />
              <Input label="Public phone" value={draft.phone} onChange={(e) => setDraft((d) => ({ ...d, phone: e.target.value }))} />
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <Button variant="primary" onClick={save} leftIcon={<AIcon name="save" size={16} />}>Save changes</Button>
            </div>
          </div>
        </Card>
      </div>
    </>
  );
}

window.WCPortal.AdminPortal = AdminPortal;
