/* global React, Icon, Badge, Tag, Avatar, Button, Field, Toggle, Tabs, Segmented, Card, Metric, Modal, Pager, StatusBadge */

var { useState, useMemo } = React;

// ============================================================
// PAGE: SUB USERS & ROLES
// ============================================================
function PageUsersRoles({ onNav }) {
  const [tab, setTab] = useState("users");
  const [usersCount, setUsersCount] = useState((window.MOCK && window.MOCK.SUB_USERS && window.MOCK.SUB_USERS.length) || 0);
  const [rolesCount, setRolesCount] = useState((window.MOCK && window.MOCK.ROLES && window.MOCK.ROLES.length) || 0);
  React.useEffect(() => {
    if (!window.TrekkoAPI) return;
    window.TrekkoAPI.getSubUsers().then((r) => { if (r) setUsersCount(r.length); });
    window.TrekkoAPI.getRoles().then((r) => { if (r) setRolesCount(r.length); });
  }, []);
  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Sub Users & Roles</h1>
          <div className="page-head__sub">Invite team members, control permissions and audit access.</div>
        </div>
        <div className="page-head__actions">
          <Button kind="secondary" icon={<Icon.Download />}>Export users</Button>
          {tab === "users"
            ? <Button kind="primary" icon={<Icon.Plus />} onClick={() => window.dispatchEvent(new CustomEvent("trekko:newUser"))}>Invite user</Button>
            : <Button kind="primary" icon={<Icon.Plus />} onClick={() => window.dispatchEvent(new CustomEvent("trekko:newRole"))}>New role</Button>}
        </div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "users", label: "Sub users", count: usersCount },
        { id: "roles", label: "Roles",      count: rolesCount },
        { id: "audit", label: "Activity log" },
      ]} />

      {tab === "users" && <SubUsersView />}
      {tab === "roles" && <RolesView />}
      {tab === "audit" && <AuditView />}
    </div>
  );
}

function SubUsersView() {
  const [page, setPage] = useState(1);
  const [q, setQ] = useState("");
  const [roleF, setRoleF] = useState("");
  const [newOpen, setNewOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(null);
  const [deleteOpen, setDeleteOpen] = useState(null);
  const [users, setUsers] = useState((window.MOCK && window.MOCK.SUB_USERS) || []);
  const [rolesForFilter, setRolesForFilter] = useState((window.MOCK && window.MOCK.ROLES) || []);
  const PAGE_SIZE = 8;

  React.useEffect(() => {
    const on = () => setNewOpen(true);
    window.addEventListener("trekko:newUser", on);
    return () => window.removeEventListener("trekko:newUser", on);
  }, []);

  React.useEffect(() => {
    if (!window.TrekkoAPI) return;
    window.TrekkoAPI.getSubUsers().then((rows) => { if (rows && rows.length) setUsers(rows); });
    window.TrekkoAPI.getRoles().then((rows) => { if (rows && rows.length) setRolesForFilter(rows); });
  }, []);

  const rows = useMemo(() => {
    let r = users;
    if (q) r = r.filter((u) => (u.name + u.email + u.role).toLowerCase().includes(q.toLowerCase()));
    if (roleF) r = r.filter((u) => u.role === roleF);
    return r;
  }, [q, roleF, users]);
  const slice = rows.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  return (
    <>
      <div className="grid grid--4" style={{ marginBottom: 18 }}>
        <Metric accent label="Total users" value={rows.length.toString()} delta="+1 this month" deltaDir="up" />
        <Metric label="Active" value={rows.filter((u) => u.status === "Active").length.toString()} hint={`${Math.round(rows.filter((u) => u.status === "Active").length / rows.length * 100)}% activation`} />
        <Metric label="2FA enrolled" value={rows.filter((u) => u.twoFA).length + " / " + rows.length} delta={`${Math.round(rows.filter((u) => u.twoFA).length / rows.length * 100)}% coverage`} deltaDir="up" />
        <Metric label="Pending invitations" value={rows.filter((u) => u.status === "Pending").length.toString()} hint="Sent in last 14 days" />
      </div>

      <div className="filter-bar">
        <input className="input input--search" placeholder="Search users by name, email or role…" style={{ width: 320 }} value={q} onChange={(e) => setQ(e.target.value)} />
        <select className="select" value={roleF} onChange={(e) => setRoleF(e.target.value)}>
          <option value="">All roles</option>
          {rolesForFilter.map((r) => <option key={r.id}>{r.name}</option>)}
        </select>
        <select className="select"><option>All statuses</option><option>Active</option><option>Suspended</option><option>Pending</option></select>
        <span className="spacer" />
        <Button kind="secondary" icon={<Icon.Filter />}>More filters</Button>
      </div>

      <div className="tbl-wrap tbl-wrap--linked">
        <table className="tbl">
          <thead>
            <tr>
              <th className="col-check"><input className="checkbox" type="checkbox" /></th>
              <th>User</th><th>Role</th><th>Market</th><th>Last login</th><th>2FA</th><th>Status</th><th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {slice.map((u) => (
              <tr key={u.id}>
                <td className="col-check"><input className="checkbox" type="checkbox" /></td>
                <td>
                  <span className="user-cell">
                    <Avatar name={u.name} size="sm" />
                    <span><div className="bold">{u.name}</div><div className="tiny muted">{u.email}</div></span>
                  </span>
                </td>
                <td><Badge tone={u.role === "Super Administrator" ? "indigo" : "neutral"} plain>{u.role}</Badge></td>
                <td className="muted">{u.market}</td>
                <td className="mono muted">{u.lastLogin}</td>
                <td>{u.twoFA ? <span className="row" style={{ gap: 4, color: "var(--success)" }}><Icon.Shield size={12} /> On</span> : <span className="muted">Off</span>}</td>
                <td><StatusBadge status={u.status} /></td>
                <td className="col-actions">
                  <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} onClick={() => setEditOpen(u)} />
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Trash />} onClick={() => setDeleteOpen(u)} />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <Pager page={page} pageSize={PAGE_SIZE} total={rows.length} onPage={setPage} />

      <NewUserModal open={newOpen} onClose={() => setNewOpen(false)} />
      <EditUserModal user={editOpen} onClose={() => setEditOpen(null)} />
      <DeleteUserModal user={deleteOpen} onClose={() => setDeleteOpen(null)} />
    </>
  );
}

function NewUserModal({ open, onClose }) {
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({ first_name: "", last_name: "", email: "", phone_number: "", market: "Iberia", role_id: null, role_name: "" });
  const [roles, setRoles] = useState((window.MOCK && window.MOCK.ROLES) || []);
  const [sending, setSending] = useState(false);
  React.useEffect(() => {
    if (!open || !window.TrekkoAPI) return;
    window.TrekkoAPI.getRoles().then((rows) => { if (rows && rows.length) setRoles(rows); });
  }, [open]);
  if (!open) return null;
  const send = async () => {
    if (!form.email || !form.first_name) { try { toast({ title: "Missing info", body: "First name + email required", tone: "danger" }); } catch (e) {} return; }
    if (!window.TrekkoAPI) { onClose(); return; }
    setSending(true);
    try {
      await window.TrekkoAPI.inviteSubUser({
        first_name: form.first_name,
        last_name: form.last_name,
        email: form.email,
        phone_number: form.phone_number,
        role_id: form.role_id,
      });
      try { toast({ title: "Invitation sent", body: form.email, tone: "success" }); } catch (e) {}
      onClose();
    } catch (e) {
      try { toast({ title: "Invite failed", body: e.message, tone: "danger" }); } catch (er) {}
    } finally { setSending(false); }
  };
  return (
    <Modal open onClose={onClose} title="Invite new sub user" size="lg"
      footer={<>
        <Button kind="secondary" onClick={onClose}>Cancel</Button>
        {step === 1 ? <Button kind="primary" onClick={() => setStep(2)}>Continue</Button>
                    : <Button kind="primary" icon={<Icon.Send />} loading={sending} onClick={send}>Send invitation</Button>}
      </>}>
      <div className="row" style={{ marginBottom: 18, fontSize: 12.5 }}>
        <StepDot n={1} active={step >= 1} done={step > 1} label="Account details" />
        <span style={{ flex: 1, height: 1, background: "var(--border)" }} />
        <StepDot n={2} active={step >= 2} done={false}    label="Role & permissions" />
      </div>

      {step === 1 && (
        <div className="grid grid--2" style={{ gap: 14 }}>
          <Field label="First name"><input className="input" value={form.first_name} onChange={(e) => setForm({ ...form, first_name: e.target.value })} placeholder="e.g. Adam" /></Field>
          <Field label="Last name"><input className="input" value={form.last_name} onChange={(e) => setForm({ ...form, last_name: e.target.value })} placeholder="e.g. Bauer" /></Field>
          <Field label="Email"><input className="input" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="user@trekko.com" /></Field>
          <Field label="Phone (optional)"><input className="input" value={form.phone_number} onChange={(e) => setForm({ ...form, phone_number: e.target.value })} placeholder="+34 690 530 5856" /></Field>
          <Field label="Market"><select className="select" value={form.market} onChange={(e) => setForm({ ...form, market: e.target.value })}><option>Iberia</option><option>DACH</option><option>UK</option><option>LATAM</option><option>Global</option></select></Field>
          <Field label="Language"><select className="select"><option>English</option><option>Spanish</option><option>French</option><option>German</option></select></Field>
          <div style={{ gridColumn: "1 / -1" }}>
            <Field label="Profile note (visible to admins)"><textarea className="textarea" placeholder="Short note about this team member..." /></Field>
          </div>
        </div>
      )}

      {step === 2 && (
        <>
          <Field label="Assign role">
            <select className="select" value={form.role_name} onChange={(e) => {
              const name = e.target.value;
              const r = roles.find((x) => x.name === name);
              setForm({ ...form, role_name: name, role_id: r ? r.id : null });
            }}>
              <option value="">Select role...</option>
              {roles.map((r) => <option key={r.id}>{r.name}</option>)}
            </select>
          </Field>
          <div className="field__hint" style={{ marginTop: 6 }}>The selected role's permissions will be pre-applied. You can override individual permissions below.</div>

          <div style={{ height: 14 }} />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <div className="bold" style={{ fontSize: 13 }}>Permissions</div>
            <Button kind="ghost" size="sm">Reset to role defaults</Button>
          </div>
          <PermissionsMatrix />

          <div style={{ height: 14 }} />
          <Card>
            <div className="row" style={{ justifyContent: "space-between" }}>
              <div>
                <div className="bold">Require two-factor authentication</div>
                <div className="tiny muted">Enforce TOTP at next login.</div>
              </div>
              <Toggle on onChange={() => {}} />
            </div>
            <div className="divider" />
            <div className="row" style={{ justifyContent: "space-between" }}>
              <div>
                <div className="bold">Send welcome email</div>
                <div className="tiny muted">With password setup link valid for 24 h.</div>
              </div>
              <Toggle on onChange={() => {}} />
            </div>
          </Card>
        </>
      )}
    </Modal>
  );
}

function StepDot({ n, active, done, label }) {
  return (
    <div className="row" style={{ gap: 8 }}>
      <span style={{
        width: 22, height: 22, borderRadius: 999,
        display: "grid", placeItems: "center",
        background: done ? "var(--success)" : active ? "var(--indigo)" : "var(--bg-subtle)",
        color: done || active ? "#fff" : "var(--ink-3)",
        fontSize: 11, fontWeight: 600,
      }}>{done ? <Icon.Check size={11} /> : n}</span>
      <span style={{ color: active ? "var(--ink-1)" : "var(--ink-3)", fontWeight: 500 }}>{label}</span>
    </div>
  );
}

function PermissionsMatrix({ readOnly }) {
  return (
    <div className="tbl-wrap" style={{ border: "1px solid var(--border)", borderRadius: 8, maxHeight: 320, overflowY: "auto" }}>
      <table className="tbl" style={{ fontSize: 12.5 }}>
        <thead><tr><th>Module</th><th>Permission</th><th className="center">Granted</th></tr></thead>
        <tbody>
          {window.MOCK.PERM_GROUPS.flatMap((g) => g.perms.map((p, i) => (
            <tr key={g.name + p}>
              {i === 0 && <td rowSpan={g.perms.length} className="bold" style={{ verticalAlign: "top", background: "var(--bg-subtle)" }}>{g.name}</td>}
              <td>{p}</td>
              <td className="center">{readOnly
                ? (Math.random() > 0.3 ? <Icon.Check stroke="var(--success)" /> : <span className="muted">—</span>)
                : <input className="checkbox" type="checkbox" defaultChecked={Math.random() > 0.3} />}</td>
            </tr>
          )))}
        </tbody>
      </table>
    </div>
  );
}

function EditUserModal({ user, onClose }) {
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState(user || {});
  const [roles, setRoles] = useState((window.MOCK && window.MOCK.ROLES) || []);
  React.useEffect(() => {
    setForm(user || {});
    if (!user || !window.TrekkoAPI) return;
    window.TrekkoAPI.getRoles().then((rows) => { if (rows && rows.length) setRoles(rows); });
  }, [user]);
  const save = async () => {
    if (!window.TrekkoAPI || !user) { onClose(); return; }
    setSaving(true);
    try {
      const [first_name, ...rest] = (form.name || "").split(" ");
      const last_name = rest.join(" ");
      const r = roles.find((x) => x.name === form.role);
      await window.TrekkoAPI.updateSubUser(user.id, {
        first_name,
        last_name,
        email: form.email,
        role_id: r ? r.id : (form.roleId || user.roleId || null),
        is_active: form.status !== "Inactive" && form.status !== "Suspended",
      });
      try { toast({ title: "User updated", body: form.name, tone: "success" }); } catch (e) {}
      onClose();
    } catch (e) {
      try { toast({ title: "Save failed", body: e.message, tone: "danger" }); } catch (er) {}
    } finally { setSaving(false); }
  };
  if (!user) return null;
  return (
    <Modal open onClose={onClose} title={`Edit ${user.name}`} size="lg"
      footer={<><Button kind="secondary" onClick={onClose}>Cancel</Button><Button kind="primary" icon={<Icon.Check />} loading={saving} onClick={save}>Save changes</Button></>}>
      <div className="row" style={{ gap: 12, marginBottom: 16 }}>
        <Avatar name={user.name} size="lg" />
        <div style={{ flex: 1 }}>
          <div className="bold">{user.name}</div>
          <div className="tiny muted">{user.email} · {user.market}</div>
        </div>
        <Button kind="secondary" size="sm" onClick={() => {
          if (!window.confirm("Force-reset password for " + (user.email || user.name) + "?")) return;
          window.TrekkoAPI.resetSubUserPassword(user.id, user.email)
            .then(function () { toast({ title: "Password reset queued", body: user.email, tone: "success" }); })
            .catch(function (e) { toast({ title: "Reset failed", body: String(e && e.message || e), tone: "danger" }); });
        }}>Reset password</Button>
        <Button kind="secondary" size="sm" onClick={() => {
          if (!window.confirm("Force-reset 2FA for " + (user.email || user.name) + "?")) return;
          window.TrekkoAPI.resetSubUserMfa(user.id, user.email)
            .then(function () { toast({ title: "2FA reset queued", body: user.email, tone: "success" }); })
            .catch(function (e) { toast({ title: "Reset failed", body: String(e && e.message || e), tone: "danger" }); });
        }}>Reset 2FA</Button>
      </div>
      <div className="grid grid--2" style={{ gap: 14 }}>
        <Field label="Name"><input className="input" value={form.name || ""} onChange={(e) => setForm({ ...form, name: e.target.value })} /></Field>
        <Field label="Email"><input className="input" value={form.email || ""} onChange={(e) => setForm({ ...form, email: e.target.value })} /></Field>
        <Field label="Role"><select className="select" value={form.role || ""} onChange={(e) => setForm({ ...form, role: e.target.value })}>{roles.map((r) => <option key={r.id}>{r.name}</option>)}</select></Field>
        <Field label="Market"><select className="select" value={form.market || ""} onChange={(e) => setForm({ ...form, market: e.target.value })}><option>Iberia</option><option>DACH</option><option>UK</option><option>LATAM</option><option>Global</option><option>Nordics</option><option>France</option><option>Greece</option></select></Field>
        <Field label="Status">
          <select className="select" value={form.status || "Active"} onChange={(e) => setForm({ ...form, status: e.target.value })}><option>Active</option><option>Suspended</option><option>Pending</option></select>
        </Field>
        <Field label="2FA">
          <div className="row" style={{ height: 34 }}><Toggle on={user.twoFA} onChange={() => {}} /> <span style={{ marginLeft: 8 }}>{user.twoFA ? "Required" : "Optional"}</span></div>
        </Field>
      </div>
      <div style={{ height: 14 }} />
      <div className="bold" style={{ fontSize: 13, marginBottom: 8 }}>Permission overrides</div>
      <PermissionsMatrix />
    </Modal>
  );
}

function DeleteUserModal({ user, onClose }) {
  const [confirmEmail, setConfirmEmail] = useState("");
  const [deleting, setDeleting] = useState(false);
  if (!user) return null;
  const doDelete = async () => {
    if (confirmEmail.trim().toLowerCase() !== (user.email || "").trim().toLowerCase()) {
      try { toast({ title: "Email mismatch", tone: "danger" }); } catch (e) {}
      return;
    }
    if (!window.TrekkoAPI) { onClose(); return; }
    setDeleting(true);
    try {
      await window.TrekkoAPI.deleteSubUser(user.id);
      try { toast({ title: "User deleted", body: user.name, tone: "success" }); } catch (e) {}
      onClose();
    } catch (e) {
      try { toast({ title: "Delete failed", body: e.message, tone: "danger" }); } catch (er) {}
    } finally { setDeleting(false); }
  };
  return (
    <Modal open onClose={onClose} title="Delete sub user"
      footer={<><Button kind="secondary" onClick={onClose}>Cancel</Button><Button kind="danger" icon={<Icon.Trash />} loading={deleting} onClick={doDelete}>Delete user</Button></>}>
      <div className="row" style={{ gap: 10, marginBottom: 14, background: "var(--danger-bg)", padding: "10px 12px", borderRadius: 8 }}>
        <Icon.Warning stroke="var(--danger)" />
        <div style={{ fontSize: 13, color: "var(--danger)" }}>This action will revoke all sessions for <b>{user.name}</b> and remove their access. Their audit log will be preserved.</div>
      </div>
      <Field label="Type the user's email to confirm">
        <input className="input" placeholder={user.email} value={confirmEmail} onChange={(e) => setConfirmEmail(e.target.value)} />
      </Field>
    </Modal>
  );
}

// ----------------- Roles tab -----------------
function RolesView() {
  const [newOpen, setNewOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(null);
  const [deleteOpen, setDeleteOpen] = useState(null);
  const [roles, setRoles] = useState((window.MOCK && window.MOCK.ROLES) || []);
  React.useEffect(() => {
    const on = () => setNewOpen(true);
    window.addEventListener("trekko:newRole", on);
    return () => window.removeEventListener("trekko:newRole", on);
  }, []);
  React.useEffect(() => {
    if (!window.TrekkoAPI) return;
    window.TrekkoAPI.getRoles().then((rows) => { if (rows && rows.length) setRoles(rows); });
  }, []);
  return (
    <>
      <div className="tbl-wrap tbl-wrap--linked" style={{ borderRadius: 8, borderTop: "1px solid var(--border)" }}>
        <table className="tbl">
          <thead><tr><th>Role</th><th className="num">Users</th><th className="num">Permissions</th><th>Scope</th><th>Last updated</th><th>Note</th><th className="col-actions"></th></tr></thead>
          <tbody>
            {roles.map((r) => (
              <tr key={r.id}>
                <td>
                  <div className="bold">{r.name}</div>
                  <div className="tiny muted">{r.id}</div>
                </td>
                <td className="num mono">{r.users}</td>
                <td className="num mono">{r.perms}</td>
                <td><Badge tone="neutral" plain>{r.scope}</Badge></td>
                <td className="mono muted">{r.updated}</td>
                <td className="muted">{r.note}</td>
                <td className="col-actions">
                  <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} onClick={() => setEditOpen(r)} />
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Trash />} onClick={() => setDeleteOpen(r)} />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <NewRoleModal open={newOpen} onClose={() => setNewOpen(false)} />
      <EditRoleModal role={editOpen} onClose={() => setEditOpen(null)} />
      <DeleteRoleModal role={deleteOpen} onClose={() => setDeleteOpen(null)} />
    </>
  );
}

function NewRoleModal({ open, onClose }) {
  if (!open) return null;
  return (
    <Modal open onClose={onClose} title="Create new role" size="lg"
      footer={<><Button kind="secondary" onClick={onClose}>Cancel</Button><Button kind="primary" onClick={onClose}>Create role</Button></>}>
      <div className="grid grid--2" style={{ gap: 14 }}>
        <Field label="Role name"><input className="input" placeholder="e.g. Regional Operations Lead" /></Field>
        <Field label="Scope"><select className="select"><option>Global</option><option>Sales</option><option>Operations</option><option>Finance</option><option>Vendors</option><option>Marketing</option></select></Field>
        <div style={{ gridColumn: "1 / -1" }}>
          <Field label="Description"><textarea className="textarea" placeholder="Short summary of this role…" /></Field>
        </div>
      </div>
      <div style={{ height: 12 }} />
      <div className="bold" style={{ fontSize: 13, marginBottom: 8 }}>Permissions</div>
      <PermissionsMatrix />
    </Modal>
  );
}

function EditRoleModal({ role, onClose }) {
  if (!role) return null;
  return (
    <Modal open onClose={onClose} title={`Edit ${role.name}`} size="lg"
      footer={<><Button kind="secondary" onClick={onClose}>Cancel</Button><Button kind="primary" icon={<Icon.Check />} onClick={onClose}>Save changes</Button></>}>
      <div className="grid grid--2" style={{ gap: 14 }}>
        <Field label="Role name"><input className="input" defaultValue={role.name} /></Field>
        <Field label="Scope"><select className="select" defaultValue={role.scope}><option>Global</option><option>Sales</option><option>Operations</option><option>Finance</option><option>Vendors</option><option>Marketing</option></select></Field>
        <div style={{ gridColumn: "1 / -1" }}>
          <Field label="Description"><textarea className="textarea" defaultValue={role.note} /></Field>
        </div>
      </div>
      <div style={{ height: 12 }} />
      <div className="bold" style={{ fontSize: 13, marginBottom: 8 }}>Permissions ({role.perms} granted)</div>
      <PermissionsMatrix />
    </Modal>
  );
}

function DeleteRoleModal({ role, onClose }) {
  const [allRoles, setAllRoles] = useState((window.MOCK && window.MOCK.ROLES) || []);
  React.useEffect(() => {
    if (!role || !window.TrekkoAPI) return;
    window.TrekkoAPI.getRoles().then((rows) => { if (rows && rows.length) setAllRoles(rows); });
  }, [role]);
  if (!role) return null;
  return (
    <Modal open onClose={onClose} title="Delete role"
      footer={<><Button kind="secondary" onClick={onClose}>Cancel</Button><Button kind="danger" icon={<Icon.Trash />} onClick={onClose}>Delete role</Button></>}>
      <div className="row" style={{ gap: 10, marginBottom: 14, background: "var(--danger-bg)", padding: "10px 12px", borderRadius: 8 }}>
        <Icon.Warning stroke="var(--danger)" />
        <div style={{ fontSize: 13, color: "var(--danger)" }}>The role <b>{role.name}</b> is currently assigned to <b>{role.users}</b> users. They will need to be reassigned before this role can be deleted.</div>
      </div>
      <Field label="Reassign users to">
        <select className="select">
          {allRoles.filter((r) => r.id !== role.id).map((r) => <option key={r.id}>{r.name}</option>)}
        </select>
      </Field>
      <div style={{ height: 12 }} />
      <Field label="Type the role name to confirm">
        <input className="input" placeholder={role.name} />
      </Field>
    </Modal>
  );
}

function AuditView() {
  const items = [
    { who: "Maria Lopez",   what: "Updated permissions for role Sales Manager",      when: "5 min ago",   ip: "85.92.18.4" },
    { who: "Bailey Chen",   what: "Invited new sub user Lars Berg as Content Editor", when: "1 hr ago",    ip: "82.18.40.21" },
    { who: "Hannah Briggs", what: "Suspended user Greta Nelson",                      when: "Today, 09:32",ip: "85.92.18.4" },
    { who: "System",        what: "Failed login attempts threshold reached for ip 91.220.18.40", when: "Yesterday", ip: "91.220.18.40" },
    { who: "Bailey Chen",   what: "Enabled SSO via Google Workspace",                 when: "2 days ago",  ip: "82.18.40.21" },
    { who: "Pierre Allain", what: "Reset 2FA for Sofia Vargas",                       when: "3 days ago",  ip: "78.92.40.18" },
    { who: "Bailey Chen",   what: "Rotated API key v3 for Public API",                when: "Last week",   ip: "82.18.40.21" },
  ];
  return (
    <Card flush>
      <table className="tbl">
        <thead><tr><th>When</th><th>Actor</th><th>Action</th><th>IP address</th></tr></thead>
        <tbody>
          {items.map((i, n) => (
            <tr key={n}>
              <td className="mono muted">{i.when}</td>
              <td><span className="user-cell"><Avatar name={i.who} size="sm" /><span className="bold">{i.who}</span></span></td>
              <td>{i.what}</td>
              <td className="mono muted">{i.ip}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

// ============================================================
// PAGE: HOMEPAGE & SEO
// ============================================================
function PageHomepage() {
  const [tab, setTab] = useState("seo");
  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Homepage & SEO</h1>
          <div className="page-head__sub">Edit hero, search modules, promo banners and per-page SEO metadata.</div>
        </div>
        <div className="page-head__actions">
          <Button kind="secondary" icon={<Icon.Eye />} onClick={() => window.open("https://trekko.co", "_blank", "noopener")}>Preview</Button>
          <Button kind="primary" icon={<Icon.Send />} onClick={() => {
            if (!window.confirm("Publish homepage/SEO changes to trekko.co?")) return;
            window.TrekkoAPI.publishHomepage("all")
              .then(function () { toast({ title: "Homepage publish queued", body: "Changes will propagate to trekko.co.", tone: "success" }); })
              .catch(function (e) { toast({ title: "Publish failed", body: String(e && e.message || e), tone: "danger" }); });
          }}>Publish changes</Button>
        </div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "hero",   label: "Hero" },
        { id: "modules",label: "Search modules" },
        { id: "promos", label: "Promotions" },
        { id: "seo",    label: "SEO configure" },
        { id: "redirects", label: "Redirects" },
        { id: "publish", label: "Publishing" },
      ]} />

      {tab === "hero"   && <HeroEditor />}
      {tab === "modules"&& <ModulesEditor />}
      {tab === "promos" && <PromosEditor />}
      {tab === "seo"    && <SeoEditor />}
      {tab === "redirects" && <RedirectsEditor />}
      {tab === "publish"&& <PublishingPanel />}
    </div>
  );
}

function HeroEditor() {
  return (
    <div className="grid" style={{ gridTemplateColumns: "1.2fr 1fr", gap: 18 }}>
      <Card title="Hero content">
        <Field label="Title"><input className="input" defaultValue="Explore the world the smart way." /></Field>
        <div style={{ height: 10 }} />
        <Field label="Subtitle"><input className="input" defaultValue="Hotels, transfers and rentals from one trusted travel partner." /></Field>
        <div style={{ height: 10 }} />
        <div className="grid grid--2" style={{ gap: 10 }}>
          <Field label="Primary CTA label"><input className="input" defaultValue="Plan my trip" /></Field>
          <Field label="Primary CTA link"><input className="input" defaultValue="/search" /></Field>
          <Field label="Secondary CTA label"><input className="input" defaultValue="See offers" /></Field>
          <Field label="Secondary CTA link"><input className="input" defaultValue="/offers" /></Field>
        </div>
        <div style={{ height: 10 }} />
        <Field label="Background"><select className="select"><option>Hero video — Mediterranean</option><option>Hero image — Alpine</option><option>Hero image — Tropical</option></select></Field>
      </Card>
      <Card title="Live preview" sub="Desktop · 1440px">
        <div style={{ aspectRatio: "16 / 9", borderRadius: 8, overflow: "hidden", background: "linear-gradient(135deg, #0a2540, #4b45c4)", position: "relative", color: "#fff" }}>
          <div style={{ position: "absolute", top: 18, left: 22, fontWeight: 700, letterSpacing: "-0.01em" }}>TREKKO</div>
          <div style={{ position: "absolute", bottom: 28, left: 22, right: 22 }}>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.015em", lineHeight: 1.15 }}>Explore the world the smart way.</div>
            <div style={{ marginTop: 6, opacity: 0.85, fontSize: 13 }}>Hotels, transfers and rentals from one trusted travel partner.</div>
            <div className="row" style={{ marginTop: 14, gap: 8 }}>
              <span style={{ background: "#fff", color: "#0a2540", padding: "6px 12px", borderRadius: 999, fontWeight: 600, fontSize: 12 }}>Plan my trip</span>
              <span style={{ border: "1px solid rgba(255,255,255,0.6)", padding: "6px 12px", borderRadius: 999, fontSize: 12 }}>See offers</span>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

function ModulesEditor() {
  const mods = [
    { name: "Hotels search", visible: true, order: 1 },
    { name: "Car rental search", visible: true, order: 2 },
    { name: "Transfer search", visible: true, order: 3 },
    { name: "Flight search", visible: false, order: 4 },
    { name: "Multi-trip builder", visible: true, order: 5 },
  ];
  return (
    <Card title="Search modules on homepage" sub="Toggle modules and reorder them" flush>
      <table className="tbl">
        <thead><tr><th className="num">Order</th><th>Module</th><th>Visible</th><th>Default tab</th><th className="col-actions"></th></tr></thead>
        <tbody>
          {mods.map((m) => (
            <tr key={m.name}>
              <td className="num mono">{m.order}</td>
              <td className="bold">{m.name}</td>
              <td><Toggle on={m.visible} onChange={() => {}} /></td>
              <td><label className="row" style={{ gap: 6 }}><input type="radio" name="dt" defaultChecked={m.order === 1} /> Default tab</label></td>
              <td className="col-actions">
                <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                  <Button kind="ghost" size="sm" iconOnly icon={<Icon.ChevronUp />} />
                  <Button kind="ghost" size="sm" iconOnly icon={<Icon.ChevronDown />} />
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function PromosEditor() {
  const promos = [
    { name: "Spring sale — 15% off hotels", status: "Live", from: "2026-04-01", to: "2026-06-30", cta: "Book hotels" },
    { name: "Free transfer at Barcelona", status: "Live", from: "2026-05-01", to: "2026-09-30", cta: "Get transfer" },
    { name: "Loyalty boost — 2x points", status: "Scheduled", from: "2026-06-01", to: "2026-08-31", cta: "Join Trekko+" },
    { name: "Winter weekend deals", status: "Draft", from: "2026-11-15", to: "2027-01-31", cta: "Plan winter" },
  ];
  return (
    <Card title="Promotions" actions={<Button kind="primary" size="sm" icon={<Icon.Plus />}>New promotion</Button>} flush>
      <table className="tbl">
        <thead><tr><th>Name</th><th>From</th><th>To</th><th>CTA</th><th>Status</th><th className="col-actions"></th></tr></thead>
        <tbody>
          {promos.map((p) => (
            <tr key={p.name}>
              <td className="bold">{p.name}</td>
              <td className="mono">{p.from}</td>
              <td className="mono">{p.to}</td>
              <td>{p.cta}</td>
              <td>{p.status === "Live" ? <Badge tone="success">Live</Badge> : p.status === "Scheduled" ? <Badge tone="info">Scheduled</Badge> : <Badge tone="neutral">Draft</Badge>}</td>
              <td className="col-actions"><Button kind="secondary" size="sm">Edit</Button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function SeoEditor() {
  const pages = [
    { path: "/",          title: "Trekko — Hotels, Cars and Transfers", desc: "Hotels, rentals and transfers in one place — built for travel agencies and pros.", index: true, sitemap: true },
    { path: "/hotels",    title: "Hotel deals across 120 countries",     desc: "Best price hotels handpicked for your trips.", index: true, sitemap: true },
    { path: "/cars",      title: "Rent a car with Trekko",               desc: "Cars from trusted rental partners with transparent pricing.", index: true, sitemap: true },
    { path: "/transfers", title: "Reliable airport transfers",           desc: "Pre-book your transfer and skip the queue.", index: true, sitemap: true },
    { path: "/flights",   title: "Flight search by Trekko",              desc: "Find flights with flexible rules and instant rebooking.", index: false, sitemap: true },
    { path: "/blog",      title: "Travel inspiration & tips",            desc: "Long reads, city guides and travel hacks from the Trekko team.", index: true, sitemap: true },
  ];
  const [active, setActive] = useState(pages[0]);
  const [form, setForm] = useState({ title: active.title, desc: active.desc, canonical: "", og: "", robots: active.index ? "index, follow" : "noindex, nofollow", priority: "0.8", sitemap: active.sitemap });
  const [saving, setSaving] = useState(false);
  React.useEffect(() => {
    setForm({ title: active.title, desc: active.desc, canonical: "https://trekko.com" + active.path, og: "/og" + active.path + ".jpg", robots: active.index ? "index, follow" : "noindex, nofollow", priority: "0.8", sitemap: active.sitemap });
    if (!window.TrekkoAPI) return;
    // Backend currently only supports per-locale SEO (not per-page).
    // We just request the active locale's SEO and let the editor apply
    // it as the per-page default until backend exposes per-page records.
    window.TrekkoAPI.getSeoDetails("en").then((d) => {
      if (!d) return;
      setForm((f) => ({
        ...f,
        title: d.title || f.title,
        desc: d.description || d.meta_description || f.desc,
        canonical: d.canonical_url || d.canonical || f.canonical,
        og: d.og_image || d.og_image_url || f.og,
        robots: d.robots || f.robots,
        priority: d.sitemap_priority || f.priority,
        sitemap: d.in_sitemap != null ? d.in_sitemap : f.sitemap,
      }));
    }).catch(() => {});
  }, [active.path]);
  const save = async () => {
    if (!window.TrekkoAPI) { try { toast({ title: "API unavailable", tone: "danger" }); } catch (e) {} return; }
    setSaving(true);
    try {
      await window.TrekkoAPI.saveSeoDetails({
        page: active.path,
        title: form.title,
        description: form.desc,
        canonical_url: form.canonical,
        og_image: form.og,
        robots: form.robots,
        sitemap_priority: form.priority,
        in_sitemap: !!form.sitemap,
      });
      try { toast({ title: "SEO saved", body: active.path, tone: "success" }); } catch (e) {}
    } catch (e) {
      try { toast({ title: "Save failed", body: e.message, tone: "danger" }); } catch (er) {}
    } finally { setSaving(false); }
  };
  return (
    <div className="grid" style={{ gridTemplateColumns: "1.2fr 1fr", gap: 18 }}>
      <Card title="Pages" flush>
        <table className="tbl">
          <thead><tr><th>Path</th><th>Title</th><th>Indexed</th><th>Sitemap</th></tr></thead>
          <tbody>
            {pages.map((p) => (
              <tr key={p.path} onClick={() => setActive(p)} style={{ cursor: "pointer", background: active.path === p.path ? "var(--indigo-50)" : undefined }}>
                <td className="mono">{p.path}</td>
                <td className="bold">{p.title.length > 36 ? p.title.slice(0, 36) + "…" : p.title}</td>
                <td>{p.index ? <Badge tone="success">Yes</Badge> : <Badge tone="neutral">No</Badge>}</td>
                <td>{p.sitemap ? <Badge tone="success">In</Badge> : <Badge tone="neutral">Out</Badge>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <Card title={`Editing — ${active.path}`} sub="Metadata, OG, canonical, robots"
        actions={<Button kind="primary" size="sm" icon={<Icon.Check />} loading={saving} onClick={save}>Save</Button>}>
        <Field label="Title (max 60)"><input className="input" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} /></Field>
        <div className="tiny muted" style={{ marginTop: 4 }}>{form.title.length} / 60 characters</div>
        <div style={{ height: 12 }} />
        <Field label="Meta description (max 160)"><textarea className="textarea" value={form.desc} rows={3} onChange={(e) => setForm({ ...form, desc: e.target.value })} /></Field>
        <div className="tiny muted" style={{ marginTop: 4 }}>{form.desc.length} / 160 characters</div>

        <div style={{ height: 14 }} />
        <div className="grid grid--2" style={{ gap: 10 }}>
          <Field label="Canonical URL"><input className="input" value={form.canonical} onChange={(e) => setForm({ ...form, canonical: e.target.value })} /></Field>
          <Field label="OG image"><input className="input" value={form.og} onChange={(e) => setForm({ ...form, og: e.target.value })} /></Field>
          <Field label="Robots"><select className="select" value={form.robots} onChange={(e) => setForm({ ...form, robots: e.target.value })}><option>index, follow</option><option>noindex, follow</option><option>index, nofollow</option><option>noindex, nofollow</option></select></Field>
          <Field label="Sitemap priority"><select className="select" value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })}><option>0.5</option><option>0.7</option><option>0.8</option><option>0.9</option><option>1.0</option></select></Field>
        </div>

        <div style={{ height: 14 }} />
        <div style={{ background: "var(--bg-subtle)", borderRadius: 8, padding: 14 }}>
          <div className="tiny muted">Google preview</div>
          <div style={{ marginTop: 4, color: "#1a0dab", fontSize: 17 }}>{form.title}</div>
          <div style={{ fontSize: 12.5, color: "#0e7c66" }}>https://trekko.com{active.path}</div>
          <div style={{ fontSize: 12.5, color: "#4d5156", marginTop: 4 }}>{form.desc}</div>
        </div>

        <div style={{ height: 14 }} />
        <Card>
          <div className="row" style={{ justifyContent: "space-between" }}>
            <div><div className="bold">Show in sitemap.xml</div><div className="tiny muted">Crawlers can discover this page through trekko.com/sitemap.xml</div></div>
            <Toggle on={form.sitemap} onChange={(v) => setForm({ ...form, sitemap: v })} />
          </div>
        </Card>
      </Card>
    </div>
  );
}

function RedirectsEditor() {
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const reload = React.useCallback(() => {
    if (!window.TrekkoAPI) { setLoading(false); return; }
    setLoading(true);
    window.TrekkoAPI.getRedirects().then((data) => {
      if (Array.isArray(data)) setRows(data);
    }).finally(() => setLoading(false));
  }, []);
  React.useEffect(() => { reload(); }, [reload]);
  return (
    <Card title="Redirects" sub="301 and 302 redirects for legacy URLs"
      actions={<Button kind="primary" size="sm" icon={<Icon.Plus />} onClick={() => {
        const from = window.prompt("From path (e.g. /old-page)");
        if (!from) return;
        const to = window.prompt("To URL (e.g. /new-page)");
        if (!to) return;
        const type = window.prompt("Type (301 or 302)", "301") || "301";
        window.TrekkoAPI.createRedirect({ source: from, destination: to, status_code: parseInt(type, 10) })
          .then(() => { try { toast({ title: "Redirect created", tone: "success" }); } catch (e) {} reload(); })
          .catch((e) => { try { toast({ title: "Create failed", body: e.message, tone: "danger" }); } catch (er) {} });
      }}>New redirect</Button>} flush>
      <table className="tbl">
        <thead><tr><th>From</th><th>To</th><th>Type</th><th>Hits (30d)</th><th>Last hit</th><th className="col-actions"></th></tr></thead>
        <tbody>
          {loading && <tr><td colSpan={6} className="muted" style={{ padding: 16 }}>Loading redirects...</td></tr>}
          {!loading && rows.length === 0 && <tr><td colSpan={6} className="muted" style={{ padding: 16 }}>No redirects configured yet.</td></tr>}
          {!loading && rows.map((r) => (
            <tr key={r.redirect_id || r.id || r.source}>
              <td className="mono">{r.source || r.from_path || r.from}</td>
              <td className="mono">{r.destination || r.to_path || r.to}</td>
              <td><Badge tone={String(r.status_code || r.type) === "302" ? "warning" : "info"}>{r.status_code || r.type || "301"}</Badge></td>
              <td className="num mono">{(r.hits_30d != null ? r.hits_30d : "-")}</td>
              <td className="mono">{r.last_hit || "-"}</td>
              <td className="col-actions">
                <Button kind="ghost" size="sm" iconOnly icon={<Icon.X />} onClick={() => {
                  const id = r.redirect_id || r.id;
                  if (!id) return;
                  if (!window.confirm("Delete redirect " + (r.source || id) + "?")) return;
                  window.TrekkoAPI.deleteRedirect(id)
                    .then(() => { try { toast({ title: "Redirect deleted", tone: "success" }); } catch (e) {} reload(); })
                    .catch((e) => { try { toast({ title: "Delete failed", body: e.message, tone: "danger" }); } catch (er) {} });
                }} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function PublishingPanel() {
  return (
    <div className="grid" style={{ gridTemplateColumns: "1.5fr 1fr", gap: 18 }}>
      <Card title="Recent publishes" flush>
        <table className="tbl">
          <thead><tr><th>Version</th><th>Published by</th><th>Pages</th><th>When</th><th>Status</th><th className="col-actions"></th></tr></thead>
          <tbody>
            <tr><td className="mono">v2026.5.12</td><td>Bailey Chen</td><td>4 pages</td><td className="mono">Today, 10:14</td><td><Badge tone="success">Live</Badge></td><td className="col-actions"><Button kind="ghost" size="sm">Rollback</Button></td></tr>
            <tr><td className="mono">v2026.5.10</td><td>Bailey Chen</td><td>2 pages</td><td className="mono">2 days ago</td><td><Badge tone="neutral">Archived</Badge></td><td className="col-actions"><Button kind="ghost" size="sm">Rollback</Button></td></tr>
            <tr><td className="mono">v2026.5.6</td><td>Maria Lopez</td><td>1 page</td><td className="mono">Last week</td><td><Badge tone="neutral">Archived</Badge></td><td className="col-actions"><Button kind="ghost" size="sm">Rollback</Button></td></tr>
          </tbody>
        </table>
      </Card>
      <Card title="Staging environment">
        <div className="row" style={{ justifyContent: "space-between", marginBottom: 12 }}>
          <div>
            <div className="bold">staging.trekko.com</div>
            <div className="tiny muted">Synced with v2026.5.13-rc</div>
          </div>
          <Badge tone="info">RC ready</Badge>
        </div>
        <Button kind="secondary" block icon={<Icon.Eye />}>Open staging</Button>
        <div style={{ height: 10 }} />
        <Button kind="primary" block icon={<Icon.Send />}>Promote to production</Button>
      </Card>
    </div>
  );
}

// ============================================================
// PAGE: SETTINGS (basic)
// ============================================================
function PageSettings() {
  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Settings</h1>
          <div className="page-head__sub">Organization, integrations and developer keys.</div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 18 }}>
        <Card title="Organization">
          <dl className="dl">
            <dt>Legal name</dt><dd>Trekko Travel Technologies SL</dd>
            <dt>Trading name</dt><dd>Trekko</dd>
            <dt>VAT ID</dt><dd className="mono">ESB87125640</dd>
            <dt>Currency</dt><dd>EUR</dd>
            <dt>Time zone</dt><dd>Europe/Madrid</dd>
            <dt>Default language</dt><dd>English</dd>
          </dl>
        </Card>
        <Card title="Branding">
          <Field label="Brand name"><input className="input" defaultValue="Trekko" /></Field>
          <div style={{ height: 10 }} />
          <Field label="Primary color">
            <div className="row" style={{ gap: 8 }}>
              <input className="input" defaultValue="#635BFF" style={{ width: 130 }} />
              <span style={{ width: 28, height: 28, borderRadius: 6, background: "#635bff", border: "1px solid var(--border)" }} />
              <span className="muted tiny">Stripe Indigo</span>
            </div>
          </Field>
          <div style={{ height: 10 }} />
          <Field label="Logo">
            <div className="row" style={{ gap: 8 }}>
              <Button kind="secondary" icon={<Icon.Upload />}>Upload SVG</Button>
              <span className="muted tiny">Recommended 1:1, transparent background</span>
            </div>
          </Field>
        </Card>
      </div>

      <Card title="Integrations" flush>
        <table className="tbl">
          <thead><tr><th>Service</th><th>Purpose</th><th>Status</th><th>Last sync</th><th className="col-actions"></th></tr></thead>
          <tbody>
            <tr><td className="bold">Stripe Connect</td><td>Payments & top-ups</td><td><Badge tone="success">Connected</Badge></td><td className="mono">2 min ago</td><td className="col-actions"><Button kind="secondary" size="sm">Configure</Button></td></tr>
            <tr><td className="bold">Mailgun</td><td>Transactional email</td><td><Badge tone="success">Connected</Badge></td><td className="mono">5 min ago</td><td className="col-actions"><Button kind="secondary" size="sm">Configure</Button></td></tr>
            <tr><td className="bold">Google Workspace SSO</td><td>Authentication</td><td><Badge tone="success">Connected</Badge></td><td className="mono">Yesterday</td><td className="col-actions"><Button kind="secondary" size="sm">Configure</Button></td></tr>
            <tr><td className="bold">Slack</td><td>Notifications</td><td><Badge tone="warning">Pending</Badge></td><td className="mono">—</td><td className="col-actions"><Button kind="primary" size="sm">Connect</Button></td></tr>
            <tr><td className="bold">Algolia</td><td>Search</td><td><Badge tone="success">Connected</Badge></td><td className="mono">Today</td><td className="col-actions"><Button kind="secondary" size="sm">Configure</Button></td></tr>
            <tr><td className="bold">Sentry</td><td>Error tracking</td><td><Badge tone="neutral">Disconnected</Badge></td><td className="mono">—</td><td className="col-actions"><Button kind="primary" size="sm">Connect</Button></td></tr>
          </tbody>
        </table>
      </Card>

      <div style={{ height: 18 }} />

      <Card title="API keys" actions={<Button kind="primary" size="sm" icon={<Icon.Plus />}>Create key</Button>} flush>
        <table className="tbl">
          <thead><tr><th>Name</th><th>Key</th><th>Scope</th><th>Created</th><th>Last used</th><th className="col-actions"></th></tr></thead>
          <tbody>
            <tr><td className="bold">Public web</td><td className="mono muted">pk_live_•••••••••••••••B41a</td><td><Badge tone="neutral">Read</Badge></td><td className="mono">2024-08-04</td><td className="mono">5 min ago</td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Copy />} /></td></tr>
            <tr><td className="bold">Server</td><td className="mono muted">sk_live_•••••••••••••••3Mqa</td><td><Badge tone="indigo">Read · Write</Badge></td><td className="mono">2024-08-04</td><td className="mono">2 min ago</td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Copy />} /></td></tr>
            <tr><td className="bold">Agency portal v3</td><td className="mono muted">sk_live_•••••••••••••••H92m</td><td><Badge tone="indigo">Read · Write</Badge></td><td className="mono">2025-02-18</td><td className="mono">Yesterday</td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Copy />} /></td></tr>
            <tr><td className="bold">Webhooks (Stripe)</td><td className="mono muted">whsec_•••••••••••••••K81</td><td><Badge tone="neutral">Webhook</Badge></td><td className="mono">2025-03-22</td><td className="mono">Today</td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Copy />} /></td></tr>
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ============================================================
// PAGE: SIGN IN
// ============================================================
function PageSignIn({ onSignIn }) {
  const [view, setView] = useState("signin"); // signin | forgot | sent | reset | done
  const [pwShown, setPwShown] = useState(false);

  return (
    <div className="app--auth" style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1fr 1fr" }}>
      {/* Brand panel */}
      <div style={{
        background: "linear-gradient(140deg, #0a2540 0%, #4b45c4 60%, #635bff 100%)",
        color: "#fff", padding: "48px", display: "flex", flexDirection: "column",
        position: "relative", overflow: "hidden",
      }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{ width: 36, height: 36, background: "rgba(255,255,255,0.16)", borderRadius: 9, display: "grid", placeItems: "center", fontWeight: 700, fontSize: 16 }}>T</div>
          <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.01em" }}>Trekko Admin</div>
        </div>
        <div style={{ marginTop: "auto", maxWidth: 460 }}>
          <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.15 }}>
            One console for every booking, agency and vendor on Trekko.
          </div>
          <div style={{ marginTop: 14, opacity: 0.82, fontSize: 14, lineHeight: 1.55 }}>
            Sales, operations, finance and marketing — all in one place. Designed to feel as fast and as clean as the products we love.
          </div>
          <div className="row" style={{ marginTop: 22, gap: 18, fontSize: 12 }}>
            <span className="row" style={{ gap: 6, opacity: 0.85 }}><Icon.Shield /> SOC 2 Type II</span>
            <span className="row" style={{ gap: 6, opacity: 0.85 }}><Icon.Lock /> GDPR ready</span>
            <span className="row" style={{ gap: 6, opacity: 0.85 }}><Icon.Globe /> 12 markets</span>
          </div>
        </div>
        {/* decorative orbs */}
        <div style={{ position: "absolute", top: -80, right: -80, width: 320, height: 320, background: "rgba(255,255,255,0.06)", borderRadius: 999 }} />
        <div style={{ position: "absolute", bottom: -120, left: -60, width: 240, height: 240, background: "rgba(0,212,255,0.18)", borderRadius: 999, filter: "blur(40px)" }} />
      </div>

      {/* Form panel */}
      <div style={{ display: "grid", placeItems: "center", padding: 48, background: "#fff" }}>
        <div style={{ width: "100%", maxWidth: 380 }}>
          {view === "signin" && (
            <>
              <h1 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", margin: 0 }}>Sign in</h1>
              <div className="muted" style={{ marginTop: 6 }}>Welcome back. Sign in to your Trekko Admin account.</div>

              <div style={{ height: 22 }} />
              <Field label="Work email">
                <input className="input" placeholder="username@adamo.com" defaultValue="nabil@trekko.com" />
              </Field>
              <div style={{ height: 12 }} />
              <Field label="Password">
                <div style={{ position: "relative" }}>
                  <input className="input" type={pwShown ? "text" : "password"} defaultValue="••••••••" style={{ paddingRight: 36 }} />
                  <button className="top__icon" onClick={() => setPwShown((v) => !v)} type="button" style={{ position: "absolute", right: 2, top: 2, width: 30, height: 30 }}>
                    {pwShown ? <Icon.EyeOff size={14} /> : <Icon.Eye size={14} />}
                  </button>
                </div>
              </Field>
              <div className="row" style={{ marginTop: 10, justifyContent: "space-between" }}>
                <label className="row" style={{ gap: 6, fontSize: 12.5 }}>
                  <input className="checkbox" type="checkbox" defaultChecked /> Remember me on this device
                </label>
                <a href="#" onClick={(e) => { e.preventDefault(); setView("forgot"); }} style={{ fontSize: 12.5 }}>Forgot password?</a>
              </div>
              <div style={{ height: 16 }} />
              <Button kind="primary" size="lg" block onClick={onSignIn}>Sign in</Button>

              <div className="row" style={{ marginTop: 18, gap: 8 }}>
                <span style={{ flex: 1, height: 1, background: "var(--border-hairline)" }} />
                <span className="tiny muted">or continue with</span>
                <span style={{ flex: 1, height: 1, background: "var(--border-hairline)" }} />
              </div>
              <div style={{ height: 12 }} />
              <Button kind="secondary" block icon={<span style={{ fontWeight: 700, fontSize: 13 }}>G</span>}>Google Workspace</Button>
              <div style={{ height: 8 }} />
              <Button kind="secondary" block icon={<Icon.Lock />}>SAML SSO</Button>

              <div className="tiny muted" style={{ marginTop: 22, textAlign: "center" }}>
                By signing in you agree to the <a href="#">Terms</a> and <a href="#">Privacy Policy</a>.
              </div>
            </>
          )}

          {view === "forgot" && (
            <>
              <button className="btn btn--ghost btn--sm" onClick={() => setView("signin")}><Icon.ChevronLeft /> Back to sign in</button>
              <h1 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", margin: "12px 0 6px" }}>Reset password</h1>
              <div className="muted">Enter your registered email and we'll send you a reset link.</div>
              <div style={{ height: 22 }} />
              <Field label="Registered email"><input className="input" placeholder="username@adamo.com" /></Field>
              <div style={{ height: 16 }} />
              <Button kind="primary" size="lg" block onClick={() => setView("sent")}>Send reset link</Button>
            </>
          )}

          {view === "sent" && (
            <div className="center">
              <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-bg)", color: "var(--success)", display: "inline-grid", placeItems: "center", margin: "0 auto 16px" }}>
                <Icon.Mail />
              </div>
              <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 6px" }}>Check your inbox</h1>
              <div className="muted">We sent a reset link to <b>nabil@trekko.com</b>. The link expires in 30 minutes.</div>
              <div style={{ height: 22 }} />
              <Button kind="secondary" block onClick={() => setView("reset")}>Open reset form (demo)</Button>
              <div style={{ height: 8 }} />
              <button className="btn btn--ghost" onClick={() => setView("signin")}>Back to sign in</button>
            </div>
          )}

          {view === "reset" && (
            <>
              <h1 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", margin: 0 }}>Set new password</h1>
              <div className="muted" style={{ marginTop: 6 }}>Use 8+ characters with at least one number and one symbol.</div>
              <div style={{ height: 22 }} />
              <Field label="New password"><input className="input" type="password" /></Field>
              <div style={{ height: 10 }} />
              <Field label="Confirm password"><input className="input" type="password" /></Field>
              <ul style={{ margin: "12px 0 0", padding: 0, listStyle: "none", fontSize: 12.5, color: "var(--ink-3)" }}>
                <li className="row" style={{ gap: 6 }}><Icon.Check stroke="var(--success)" size={12} /> At least 8 characters</li>
                <li className="row" style={{ gap: 6 }}><Icon.Check stroke="var(--success)" size={12} /> Contains a number</li>
                <li className="row" style={{ gap: 6 }}><Icon.X stroke="var(--ink-4)" size={12} /> Contains a symbol</li>
              </ul>
              <div style={{ height: 16 }} />
              <Button kind="primary" size="lg" block onClick={() => setView("done")}>Reset password</Button>
            </>
          )}

          {view === "done" && (
            <div className="center">
              <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-bg)", color: "var(--success)", display: "inline-grid", placeItems: "center", margin: "0 auto 16px" }}>
                <Icon.Check size={22} stroke="var(--success)" sw={2.2} />
              </div>
              <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 6px" }}>Password updated</h1>
              <div className="muted">You can now sign in with your new password.</div>
              <div style={{ height: 22 }} />
              <Button kind="primary" block onClick={() => setView("signin")}>Back to sign in</Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PageUsersRoles, PageHomepage, PageSettings, PageSignIn });
