/* Settings & Admin/Users. Exports: Settings, Admin. */

function ToggleSwitch({ on, onChange }) {
  return (
    <button className="focusable" onClick={() => onChange(!on)} role="switch" aria-checked={on}
      style={{ width: 42, height: 24, borderRadius: 999, border: "none", cursor: "pointer", padding: 2, background: on ? "var(--accent)" : "var(--border-strong)", transition: "background .16s ease" }}>
      <span style={{ display: "block", width: 20, height: 20, borderRadius: 999, background: "#fff", boxShadow: "var(--shadow-sm)", transform: on ? "translateX(18px)" : "none", transition: "transform .18s cubic-bezier(.2,.7,.3,1)" }} />
    </button>
  );
}

function PrefRow({ title, sub, children, icon }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 0", borderBottom: "1px solid var(--border)" }}>
      {icon && <div style={{ width: 34, height: 34, borderRadius: 9, flex: "none", display: "grid", placeItems: "center", background: "var(--surface-3)", color: "var(--text-muted)" }}><Icon name={icon} size={16} /></div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{ flex: "none" }}>{children}</div>
    </div>
  );
}

function Settings({ theme, onSetTheme, userName }) {
  const [notifEmail, setNotifEmail] = React.useState(true);
  const [notifDigest, setNotifDigest] = React.useState(false);
  const [projectsDefault, setProjectsDefault] = React.useState(false);
  const themeIcon = { light: "sun", dim: "dim", dark: "moon" }[theme] || "dim";
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "auto", background: "var(--bg)" }}>
      <div style={{ maxWidth: 720, margin: "0 auto", padding: "30px 30px 60px" }}>
        <div style={{ marginBottom: 22 }}>
          <div className="display" style={{ fontSize: 28 }}>Settings</div>
          <div style={{ fontSize: 14, color: "var(--text-muted)", marginTop: 3 }}>Manage your profile and preferences.</div>
        </div>

        <div className="card" style={{ padding: "8px 20px 18px", marginBottom: 16 }}>
          <SectionLabel>Profile</SectionLabel>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 6 }}>
            <Avatar name={userName} size={56} accent />
            <div>
              <div style={{ fontSize: 16, fontWeight: 650 }}>{userName}</div>
              <div style={{ fontSize: 13, color: "var(--text-muted)" }}>Programme Director · Admin</div>
            </div>
            <div style={{ flex: 1 }} />
            <button className="btn btn-sm">Change photo</button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 14 }}>
            <div><label className="field-label">Full name</label><input className="input focusable" defaultValue={userName} /></div>
            <div><label className="field-label">Email</label><input className="input focusable mono" defaultValue="maya.chen@wellspring.org" /></div>
          </div>
        </div>

        <div className="card" style={{ padding: "8px 20px 14px", marginBottom: 16 }}>
          <SectionLabel>Appearance</SectionLabel>
          <PrefRow icon={themeIcon} title="Theme" sub="Dim sits between light and dark - the default.">
            <Segmented value={theme} onChange={onSetTheme} options={[
              { value: "light", label: "Light", icon: "sun" },
              { value: "dim", label: "Dim", icon: "dim" },
              { value: "dark", label: "Dark", icon: "moon" },
            ]} />
          </PrefRow>
          <PrefRow icon="eye" title="Show projects on map by default" sub="Surface project nodes when opening the Org Map.">
            <ToggleSwitch on={projectsDefault} onChange={setProjectsDefault} />
          </PrefRow>
        </div>

        <div className="card" style={{ padding: "8px 20px 14px" }}>
          <SectionLabel>Notifications</SectionLabel>
          <PrefRow icon="mail" title="Email notifications" sub="Get notified when records you own change.">
            <ToggleSwitch on={notifEmail} onChange={setNotifEmail} />
          </PrefRow>
          <PrefRow icon="bell" title="Weekly digest" sub="A Monday summary of ecosystem activity.">
            <ToggleSwitch on={notifDigest} onChange={setNotifDigest} />
          </PrefRow>
        </div>
      </div>
    </div>
  );
}

function RoleBadge({ role }) {
  const map = {
    Admin: { c: "var(--accent)", b: "var(--accent-soft)" },
    Editor: { c: "var(--info)", b: "var(--info-bg)" },
    Viewer: { c: "var(--text-muted)", b: "var(--surface-2)" },
  };
  const s = map[role];
  return <span className="badge" style={{ color: s.c, background: s.b, borderColor: "transparent" }}>{role}</span>;
}

function Admin() {
  const [invite, setInvite] = React.useState(false);
  const users = [
    { name: "Maya Chen", email: "maya.chen@wellspring.org", role: "Admin", status: "Active" },
    { name: "David Okafor", email: "david.okafor@wellspring.org", role: "Editor", status: "Active" },
    { name: "Sarah Lindqvist", email: "sarah.l@wellspring.org", role: "Editor", status: "Active" },
    { name: "Tom Becker", email: "tom.becker@wellspring.org", role: "Viewer", status: "Active" },
    { name: "Rachel Adeyemi", email: "rachel.a@wellspring.org", role: "Viewer", status: "Invited" },
  ];
  const roleDesc = [
    { role: "Viewer", desc: "Browse the map and records. No edits. Cannot see funding data." },
    { role: "Editor", desc: "Add and link entities, edit records, edit the map." },
    { role: "Admin", desc: "Everything, plus manage users and roles." },
  ];
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "auto", background: "var(--bg)" }}>
      <div style={{ maxWidth: 880, margin: "0 auto", padding: "30px 30px 60px" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 22, gap: 16, flexWrap: "wrap" }}>
          <div>
            <div className="display" style={{ fontSize: 28 }}>Users</div>
            <div style={{ fontSize: 14, color: "var(--text-muted)", marginTop: 3 }}>Manage who can access the ecosystem and what they can do.</div>
          </div>
          <button className="btn btn-primary" onClick={() => setInvite(!invite)}><Icon name="plus" size={16} /> Invite user</button>
        </div>

        {invite && (
          <div className="card fade-up" style={{ padding: 18, marginBottom: 16 }}>
            <div style={{ fontWeight: 650, fontSize: 14.5, marginBottom: 12 }}>Invite a team member</div>
            <div style={{ display: "flex", gap: 12, alignItems: "flex-end", flexWrap: "wrap" }}>
              <div style={{ flex: 2, minWidth: 200 }}><label className="field-label">Email address</label><input className="input focusable" placeholder="name@wellspring.org" /></div>
              <div style={{ flex: 1, minWidth: 130 }}><label className="field-label">Role</label>
                <select className="input focusable" defaultValue="Viewer"><option>Viewer</option><option>Editor</option><option>Admin</option></select>
              </div>
              <button className="btn btn-primary" onClick={() => setInvite(false)}>Send invite</button>
            </div>
          </div>
        )}

        <div className="card" style={{ overflow: "hidden", marginBottom: 20 }}>
          <table className="tbl">
            <thead><tr><th>User</th><th>Email</th><th>Role</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.email}>
                  <td><div style={{ display: "flex", alignItems: "center", gap: 10, fontWeight: 600 }}><Avatar name={u.name} size={28} />{u.name}</div></td>
                  <td className="mono" style={{ color: "var(--text-muted)", fontSize: 13 }}>{u.email}</td>
                  <td><RoleBadge role={u.role} /></td>
                  <td><span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, color: u.status === "Active" ? "var(--good)" : "var(--warn)" }}><span className="statdot" style={{ background: "currentColor" }} />{u.status}</span></td>
                  <td style={{ textAlign: "right" }}><button className="btn btn-icon btn-ghost"><Icon name="dots" size={16} /></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <SectionLabel>Roles & permissions</SectionLabel>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          {roleDesc.map((r) => (
            <div key={r.role} className="card" style={{ padding: 16 }}>
              <div style={{ marginBottom: 8 }}><RoleBadge role={r.role} /></div>
              <div style={{ fontSize: 13, color: "var(--text-muted)", lineHeight: 1.5 }}>{r.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Settings, Admin, ToggleSwitch });
