/* Admin — Config (Custom Types) + Users (hide/deactivate). window.AdminScreen */
const { useState } = React;

function TypeGroup({ title, items }) {
  const [list, setList] = useState(items);
  const [adding, setAdding] = useState("");
  return (
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xs)", padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
        <h3 style={{ fontSize: "var(--text-md)", fontWeight: 700, color: "var(--text-strong)" }}>{title}</h3>
        <span style={{ fontSize: "var(--text-xs)", color: "var(--text-subtle)" }}>{list.length}</span>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
        {list.map((it) => (
          <span key={it} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 6px 5px 11px", borderRadius: "var(--radius-pill)", background: "var(--surface-sunken)", border: "1px solid var(--border-default)", fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-body)" }}>
            {it}
            <button onClick={() => setList((l) => l.filter((x) => x !== it))} aria-label={"Remove " + it} style={{ display: "inline-flex", width: 18, height: 18, borderRadius: "50%", border: "none", background: "transparent", color: "var(--text-subtle)", cursor: "pointer", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={13} /></button>
          </span>
        ))}
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <div style={{ flex: 1, maxWidth: 220 }}><Input placeholder="Add a type…" value={adding} onChange={(e) => setAdding(e.target.value)} /></div>
        <Button variant="secondary" size="sm" icon="plus" onClick={() => { if (adding.trim()) { setList((l) => [...l, adding.trim()]); setAdding(""); } }}>Add</Button>
      </div>
    </div>
  );
}

function ConfigPane() {
  const d = window.PT_DATA;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Banner tone="info" title="Custom Types">Create, rename and delete custom statuses and types. Deleting a type that's in use prompts you to reassign affected records, so nothing is left orphaned.</Banner>
      {Object.entries(d.customTypes).map(([title, items]) => <TypeGroup key={title} title={title} items={items} />)}
    </div>
  );
}

function UsersPane() {
  const d = window.PT_DATA;
  const [users, setUsers] = useState(d.users);
  function toggle(i) { setUsers((us) => us.map((u, j) => j === i ? { ...u, active: !u.active } : u)); }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Banner tone="warning" title="Hidden users keep their history">Deactivating a departed user removes them from follow-up and task assignment lists, but their name still renders correctly on past notes. They are not deleted.</Banner>
      <div style={{ background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", overflow: "hidden", boxShadow: "var(--shadow-xs)" }}>
        <div className="pt-scroll-x">
        <table style={{ width: "100%", minWidth: 720, borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ background: "var(--surface-sunken)" }}>
              {["User", "Role", "Last active", "Assignable", ""].map((h, i) => (
                <th key={i} style={{ textAlign: i === 4 ? "right" : "left", padding: "9px 14px", fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", fontWeight: 700, color: "var(--text-muted)", borderBottom: "1px solid var(--border-default)", whiteSpace: "nowrap" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {users.map((u, i) => (
              <tr key={i} style={{ borderBottom: "1px solid var(--border-subtle)", opacity: u.active ? 1 : 0.62 }}>
                <td style={{ padding: "11px 14px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <Avatar name={u.name} size="sm" dot={u.active ? (u.last === "Active now" ? "online" : "off") : "off"} />
                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                        <span style={{ fontWeight: 700, color: "var(--text-strong)", fontSize: "var(--text-base)", whiteSpace: "nowrap" }}>{u.name}</span>
                        {!u.active && <Badge tone="neutral" size="sm" icon="eye-off">Hidden</Badge>}
                      </div>
                      <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{u.email}</div>
                    </div>
                  </div>
                </td>
                <td style={{ padding: "11px 14px" }}><Badge tone={u.role === "Admin" ? "brand" : "neutral"} size="sm">{u.role}</Badge></td>
                <td style={{ padding: "11px 14px", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>{u.last}</td>
                <td style={{ padding: "11px 14px" }}><Toggle checked={u.active} onChange={() => toggle(i)} size="sm" /></td>
                <td style={{ padding: "11px 8px", textAlign: "right" }}><IconButton icon="more-horizontal" label="More" /></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}

function AdminScreen() {
  const [pane, setPane] = useState("config");
  const nav = [["config", "Config — Custom Types", "sliders-horizontal"], ["users", "Users", "users"], ["billing", "Account & Billing", "credit-card"]];
  return (
    <div style={{ padding: 22, display: "grid", gridTemplateColumns: "220px minmax(0,1fr)", gap: 18, alignItems: "start" }} className="pt-detail-grid">
      <nav style={{ background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", padding: 8, boxShadow: "var(--shadow-xs)", display: "flex", flexDirection: "column", gap: 2 }}>
        {nav.map(([k, label, icon]) => (
          <button key={k} onClick={() => setPane(k)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", textAlign: "left", background: pane === k ? "var(--surface-selected)" : "transparent", color: pane === k ? "var(--text-brand)" : "var(--text-body)", fontWeight: pane === k ? 600 : 500, fontSize: "var(--text-sm)", fontFamily: "var(--font-sans)" }}>
            <Icon name={icon} size={16} /> {label}
          </button>
        ))}
      </nav>
      <div>
        {pane === "config" && <ConfigPane />}
        {pane === "users" && <UsersPane />}
        {pane === "billing" && <EmptyState icon="credit-card" title="Account & Billing" description="Subscription, invoices, and payment method live here (P3 in the rebuild scope)." />}
      </div>
    </div>
  );
}
window.AdminScreen = AdminScreen;
