// ============================================
// Reliq — Settings (general) — Step 10
// Profile · Workspace · Notifications · Scan defaults · Security · Danger zone
// All state backed by localStorage. No real backend calls.
// ============================================

// ── localStorage helpers (local to this file) ────────────────────────────────
const _sgLoad = (key, def) => {
  try {
    const raw = localStorage.getItem(key);
    if (raw) { const p = JSON.parse(raw); if (p !== null && p !== undefined) return p; }
  } catch (_) {}
  return typeof def === "function" ? def() : def;
};
const _sgSave = (key, val) => {
  try { localStorage.setItem(key, JSON.stringify(val)); } catch (_) {}
};

// ── localStorage key constants ─────────────────────────────────────────────────
const SG_KEYS = {
  USER_PROFILE:       "reliq_user_profile",
  SECURITY_SETTINGS:  "reliq_security_settings",
  ACTIVE_SESSIONS:    "reliq_active_sessions",
  SECURITY_EVENTS:    "reliq_security_events",
  NOTIFICATION_PREFS: "reliq_notification_preferences",
  SCAN_DEFAULTS:      "reliq_scan_defaults",
};

// ── Default/initial values ────────────────────────────────────────────────────
const SG_DEFAULT_PROFILE = window.DEFAULT_USER_PROFILE || {
  id: "usr_zola", name: "Zola Lena", email: "zola@holt.africa",
  avatarInitials: "ZL", timezone: "Africa/Johannesburg",
  notificationEmail: "zola@holt.africa", authProvider: "email",
  roleDisplay: "Owner", isMock: true,
};
const SG_DEFAULT_SECURITY = window.DEFAULT_SECURITY_SETTINGS || {
  twoFactorEnabled: true, twoFactorMethod: "app",
  passwordLastChanged: "2026-03-15T10:00:00.000Z",
  githubConnected: false, isMock: true,
};
const SG_INITIAL_SESSIONS = window.INITIAL_ACTIVE_SESSIONS || [
  { id:"sess_current", label:"Current session", device:"macOS · Chrome", location:"Johannesburg, ZA", ip:"196.25.x.x", startedAt: new Date().toISOString(), lastActiveAt: new Date().toISOString(), isCurrent:true, isMock:true },
  { id:"sess_mobile",  label:"Mobile",          device:"iOS · Safari",   location:"Cape Town, ZA",    ip:"41.185.x.x", startedAt:"2026-05-25T08:00:00.000Z", lastActiveAt:"2026-05-26T14:22:00.000Z", isCurrent:false, isMock:true },
  { id:"sess_ci",      label:"CI environment",  device:"Linux · Reliq CLI", location:"us-east-1 (AWS)", ip:"18.206.x.x", startedAt:"2026-05-20T00:00:00.000Z", lastActiveAt:"2026-05-27T06:15:00.000Z", isCurrent:false, isMock:true },
];
const SG_INITIAL_EVENTS = window.INITIAL_SECURITY_EVENTS || [
  { id:"sevt_001", event:"login_success",    actor:"zola@holt.africa", device:"macOS · Chrome", location:"Johannesburg, ZA", timestamp:"2026-05-27T09:14:00.000Z", isMock:true },
  { id:"sevt_002", event:"2fa_verified",     actor:"zola@holt.africa", device:"macOS · Chrome", location:"Johannesburg, ZA", timestamp:"2026-05-27T09:14:01.000Z", isMock:true },
  { id:"sevt_003", event:"api_key_created",  actor:"zola@holt.africa", device:"macOS · Chrome", location:"Johannesburg, ZA", timestamp:"2026-05-26T13:48:00.000Z", isMock:true },
  { id:"sevt_004", event:"login_success",    actor:"zola@holt.africa", device:"iOS · Safari",   location:"Cape Town, ZA",    timestamp:"2026-05-25T08:00:00.000Z", isMock:true },
  { id:"sevt_005", event:"password_changed", actor:"zola@holt.africa", device:"macOS · Chrome", location:"Johannesburg, ZA", timestamp:"2026-03-15T10:00:00.000Z", isMock:true },
];
const SG_DEFAULT_NOTIF = window.DEFAULT_NOTIFICATION_PREFS || {
  scanCompleted: true, highRiskFinding: true, reportGenerated: true,
  webhookFailure: true, billingAlerts: true, teamInvites: true,
  policyUpdates: true, securityAlerts: true, productUpdates: false,
  emailNotifications: true, inAppNotifications: true,
};
const SG_DEFAULT_SCAN = window.DEFAULT_SCAN_DEFAULTS || {
  autoRescan: true, publicReports: false, aiChecks: true, deepScan: false, storeBeta: false,
};

// ── Section divider used inside cards ────────────────────────────────────────
const SgSection = ({ label, first }) => (
  <div style={{
    padding: "13px 18px 5px",
    borderTop: first ? "1px solid var(--line-1)" : "1px solid var(--line-1)",
    fontFamily: "var(--font-mono)", fontSize: 10.5,
    letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--fg-3)",
  }}>
    {label}
  </div>
);

// ── Row: toggle preference row ────────────────────────────────────────────────
const PrefRow = ({ title, sub, value, onChange, required, last }) => (
  <div style={{
    display: "flex", alignItems: "center", gap: 14,
    padding: "14px 18px",
    borderBottom: last ? 0 : "1px solid var(--line-1)",
  }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13.5, fontWeight: 500 }}>
        {title}
        {required && (
          <span className="chip" style={{
            marginLeft: 8, fontSize: 10, color: "var(--amber)",
            borderColor: "rgba(245,158,11,0.25)", background: "var(--amber-bg)",
          }}>Required</span>
        )}
      </div>
      <div style={{ fontSize: 12, color: "var(--fg-2)", marginTop: 2 }}>{sub}</div>
    </div>
    <div
      className={`toggle ${value ? "on" : ""} ${required ? "disabled" : ""}`}
      onClick={required ? undefined : onChange}
      title={required ? "This notification cannot be disabled" : undefined}
      style={required ? { opacity: 0.6, cursor: "not-allowed" } : { cursor: "pointer" }}
    />
  </div>
);

// ── Mock-only notice banner ───────────────────────────────────────────────────
const MockBanner = ({ msg }) => (
  <div style={{
    margin: "0 18px 18px", padding: "9px 13px",
    background: "var(--bg-2)", border: "1px solid var(--line-2)",
    borderRadius: 6, display: "flex", alignItems: "flex-start", gap: 8,
    fontSize: 12, color: "var(--fg-3)",
  }}>
    <Icon name="info" size={12} style={{ marginTop: 1, flexShrink: 0, color: "var(--blue)" }} />
    <span>{msg}</span>
  </div>
);

// ── Simple email validation helper ────────────────────────────────────────────
const isValidEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test((v || "").trim());

// ── Security event labels ─────────────────────────────────────────────────────
const SEVT_LABELS = {
  login_success:  "Signed in",
  login_failed:   "Failed sign-in attempt",
  "2fa_verified": "2FA verified",
  api_key_created:"API key created",
  api_key_rotated:"API key rotated",
  password_changed:"Password changed",
  session_revoked: "Session revoked",
  "2fa_enabled":  "2FA enabled",
  "2fa_disabled": "2FA disabled",
};

// ─────────────────────────────────────────────────────────────────────────────
// SettingsGeneral
// Route: /settings
// ─────────────────────────────────────────────────────────────────────────────
const SettingsGeneral = ({ go }) => {

  // ── Tab routing (supports __reliq_pending_focus) ──────────────────────────
  const [tab, setTab] = React.useState(() => {
    const t = window.__reliq_pending_focus;
    if (t && t.type === "settings-tab" && t.tab) {
      window.__reliq_pending_focus = null;
      return t.tab;
    }
    return "profile";
  });

  // ── Profile state ─────────────────────────────────────────────────────────
  const [profile, setProfile] = React.useState(() => _sgLoad(SG_KEYS.USER_PROFILE, SG_DEFAULT_PROFILE));
  const [profileErrors, setProfileErrors] = React.useState({});

  const updateProfile = (k, v) => setProfile(p => ({ ...p, [k]: v }));

  const saveProfile = () => {
    const errs = {};
    if (!profile.name.trim()) errs.name = "Name is required";
    if (!isValidEmail(profile.email)) errs.email = "Enter a valid email address";
    if (profile.notificationEmail && !isValidEmail(profile.notificationEmail))
      errs.notificationEmail = "Enter a valid email address";
    setProfileErrors(errs);
    if (Object.keys(errs).length) {
      window.reliqToast?.error("Fix the errors below before saving.");
      return;
    }
    // Derive avatar initials from name
    const parts = profile.name.trim().split(" ").filter(Boolean);
    const initials = parts.length >= 2
      ? (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
      : profile.name.slice(0, 2).toUpperCase();
    const saved = { ...profile, avatarInitials: initials };
    _sgSave(SG_KEYS.USER_PROFILE, saved);
    setProfile(saved);
    window.reliqToast?.success("Profile saved.");
  };

  // ── Workspace state ───────────────────────────────────────────────────────
  const [workspace, setWorkspace] = React.useState(() =>
    window.reliqWorkspace?.getWorkspace() || { name:"Roamly", slug:"roamly", billingEmail:"zola@holt.africa", timezone:"Africa/Johannesburg" }
  );
  const canEditWorkspace = window.reliqRoles?.hasPermission("manage_team") ?? true;

  const updateWorkspace = (k, v) => setWorkspace(w => ({ ...w, [k]: v }));

  const saveWorkspace = () => {
    if (!workspace.name?.trim()) {
      window.reliqToast?.error("Workspace name is required.");
      return;
    }
    window.reliqWorkspace?.saveWorkspace(workspace);
    window.reliqToast?.success("Workspace settings saved.");
  };

  // ── Notification prefs ────────────────────────────────────────────────────
  const [notifPrefs, setNotifPrefs] = React.useState(() => _sgLoad(SG_KEYS.NOTIFICATION_PREFS, SG_DEFAULT_NOTIF));
  const REQUIRED_NOTIFS = ["billingAlerts", "securityAlerts"];

  const toggleNotif = (k) => {
    if (REQUIRED_NOTIFS.includes(k)) return; // protected
    setNotifPrefs(p => ({ ...p, [k]: !p[k] }));
  };

  const saveNotifPrefs = () => {
    _sgSave(SG_KEYS.NOTIFICATION_PREFS, notifPrefs);
    window.reliqToast?.success("Notification preferences saved.");
  };

  const resetNotifPrefs = () => {
    window.reliqConfirm?.show({
      title: "Reset notification preferences?",
      message: "All preferences will be reset to the default values.",
      danger: false,
      confirmLabel: "Reset to defaults",
      onConfirm: () => {
        setNotifPrefs(SG_DEFAULT_NOTIF);
        _sgSave(SG_KEYS.NOTIFICATION_PREFS, SG_DEFAULT_NOTIF);
        window.reliqToast?.info("Notification preferences reset to defaults.");
      },
    });
  };

  // ── Scan defaults ─────────────────────────────────────────────────────────
  const [scanDefs, setScanDefs] = React.useState(() => _sgLoad(SG_KEYS.SCAN_DEFAULTS, SG_DEFAULT_SCAN));

  const toggleScan = (k) => setScanDefs(p => ({ ...p, [k]: !p[k] }));

  const saveScanDefs = () => {
    _sgSave(SG_KEYS.SCAN_DEFAULTS, scanDefs);
    window.reliqToast?.success("Scan defaults saved.");
  };

  // ── Security state ────────────────────────────────────────────────────────
  const [security, setSecurity] = React.useState(() => _sgLoad(SG_KEYS.SECURITY_SETTINGS, SG_DEFAULT_SECURITY));
  const [sessions, setSessions] = React.useState(() => _sgLoad(SG_KEYS.ACTIVE_SESSIONS, SG_INITIAL_SESSIONS));
  const [secEvents] = React.useState(() => _sgLoad(SG_KEYS.SECURITY_EVENTS, SG_INITIAL_EVENTS));

  // Password change form
  const [pwForm, setPwForm] = React.useState({ current: "", next: "", confirm: "" });
  const [pwErrors, setPwErrors] = React.useState({});

  const updatePw = (k, v) => setPwForm(f => ({ ...f, [k]: v }));

  const submitPassword = () => {
    const errs = {};
    if (!pwForm.current.trim()) errs.current = "Current password is required";
    if (pwForm.next.length < 8) errs.next = "New password must be at least 8 characters";
    if (pwForm.next !== pwForm.confirm) errs.confirm = "Passwords do not match";
    setPwErrors(errs);
    if (Object.keys(errs).length) {
      window.reliqToast?.error("Fix the password errors below.");
      return;
    }
    window.reliqConfirm?.show({
      title: "Update password?",
      message: "Your password will be changed. All other sessions will remain active. (Mock — no real change occurs.)",
      danger: false,
      confirmLabel: "Update password",
      onConfirm: () => {
        const now = new Date().toISOString();
        const updated = { ...security, passwordLastChanged: now };
        setSecurity(updated);
        _sgSave(SG_KEYS.SECURITY_SETTINGS, updated);
        setPwForm({ current: "", next: "", confirm: "" });
        setPwErrors({});
        window.reliqToast?.success("Password updated successfully. (Mock — no real change.)");
      },
    });
  };

  // 2FA toggle
  const toggle2FA = () => {
    const enabling = !security.twoFactorEnabled;
    window.reliqConfirm?.show({
      title: enabling ? "Enable two-factor authentication?" : "Disable two-factor authentication?",
      message: enabling
        ? "You'll be prompted to scan a QR code with your authenticator app. (Mock — no real 2FA setup.)"
        : "Disabling 2FA reduces account security. You can re-enable it at any time. (Mock — no real change.)",
      danger: !enabling,
      confirmLabel: enabling ? "Enable 2FA" : "Disable 2FA",
      onConfirm: () => {
        const updated = { ...security, twoFactorEnabled: enabling };
        setSecurity(updated);
        _sgSave(SG_KEYS.SECURITY_SETTINGS, updated);
        window.reliqToast?.success(enabling
          ? "2FA enabled. Scan the QR code in your authenticator app. (Mock)"
          : "2FA disabled. (Mock — no real change.)");
      },
    });
  };

  const viewRecoveryCodes = () => {
    window.reliqConfirm?.show({
      title: "View recovery codes",
      message: "Recovery codes are one-time-use backup codes for 2FA. Store them somewhere safe. (Mock — codes shown below are not real.)\n\n  A1B2-C3D4   E5F6-G7H8\n  I9J0-K1L2   M3N4-O5P6\n  Q7R8-S9T0   U1V2-W3X4\n  Y5Z6-A7B8   C9D0-E1F2",
      danger: false,
      confirmLabel: "I've saved my codes",
      onConfirm: () => window.reliqToast?.info("Recovery codes acknowledged."),
    });
  };

  // Session revoke
  const revokeSession = (session) => {
    window.reliqConfirm?.show({
      title: "Revoke this session?",
      message: `The session on "${session.device}" (${session.location}) will be signed out immediately. (Mock — no real invalidation.)`,
      danger: true,
      confirmLabel: "Revoke session",
      onConfirm: () => {
        const updated = sessions.filter(s => s.id !== session.id);
        setSessions(updated);
        _sgSave(SG_KEYS.ACTIVE_SESSIONS, updated);
        window.reliqToast?.success(`Session on "${session.device}" revoked. (Mock)`);
      },
    });
  };

  const revokeAllOther = () => {
    const others = sessions.filter(s => !s.isCurrent);
    if (!others.length) { window.reliqToast?.info("No other sessions to revoke."); return; }
    window.reliqConfirm?.show({
      title: `Revoke ${others.length} other session${others.length !== 1 ? "s" : ""}?`,
      message: "All sessions other than this one will be signed out. (Mock — no real invalidation.)",
      danger: true,
      confirmLabel: "Revoke all other sessions",
      onConfirm: () => {
        const updated = sessions.filter(s => s.isCurrent);
        setSessions(updated);
        _sgSave(SG_KEYS.ACTIVE_SESSIONS, updated);
        window.reliqToast?.success(`${others.length} session${others.length !== 1 ? "s" : ""} revoked. (Mock)`);
      },
    });
  };

  // GitHub connection status
  const authProvider = window.reliqSubscription?.getAuthProvider() || security.authProvider || "email";
  const githubConnected = authProvider === "github" || security.githubConnected;

  // ── Auth provider display ─────────────────────────────────────────────────
  const currentRole = window.reliqRoles?.getCurrentUserRole() || "owner";
  const roleLabel = window.RELIQ_ROLES?.[currentRole]?.label || "Owner";

  // ── Password last changed display ─────────────────────────────────────────
  const fmtDate = (iso) => {
    if (!iso) return "Unknown";
    try { return new Date(iso).toLocaleDateString("en-US", { year:"numeric", month:"long", day:"numeric" }); }
    catch (_) { return iso; }
  };

  // ── Tab-aware save action (AuthLayout header button) ──────────────────────
  const handleHeaderSave = () => {
    if (tab === "profile")        saveProfile();
    else if (tab === "workspace") saveWorkspace();
    else if (tab === "notifications") saveNotifPrefs();
    else if (tab === "scan")      saveScanDefs();
    // security and danger tabs handle their own actions
  };

  const showHeaderSave = ["profile","workspace","notifications","scan"].includes(tab);

  // ── Danger zone ───────────────────────────────────────────────────────────
  const isOwner = window.reliqRoles?.canDeleteWorkspace() ?? true;

  const exportAccountData = () => {
    window.reliqConfirm?.show({
      title: "Export account data?",
      message: "A JSON file with your profile, notification preferences, and security settings will be generated and downloaded. (Mock — export is simulated.)",
      danger: false,
      confirmLabel: "Export my data",
      onConfirm: () => {
        const data = {
          profile: _sgLoad(SG_KEYS.USER_PROFILE, SG_DEFAULT_PROFILE),
          notificationPrefs: _sgLoad(SG_KEYS.NOTIFICATION_PREFS, SG_DEFAULT_NOTIF),
          securitySettings: _sgLoad(SG_KEYS.SECURITY_SETTINGS, SG_DEFAULT_SECURITY),
          exportedAt: new Date().toISOString(),
          isMock: true,
        };
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url; a.download = "reliq-account-data.json"; a.click();
        URL.revokeObjectURL(url);
        window.reliqToast?.success("Account data exported. (Mock)");
      },
    });
  };

  const exportWorkspaceData = () => {
    window.reliqConfirm?.show({
      title: "Export workspace data?",
      message: "A JSON file with your workspace settings, team members, and audit log will be generated. (Mock — export is simulated.)",
      danger: false,
      confirmLabel: "Export workspace data",
      onConfirm: () => {
        const data = {
          workspace:   window.reliqWorkspace?.getWorkspace(),
          teamMembers: window.reliqWorkspace?.getTeamMembers(),
          auditLog:    window.reliqWorkspace?.getAuditLog(),
          exportedAt:  new Date().toISOString(),
          isMock:      true,
        };
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url; a.download = "reliq-workspace-data.json"; a.click();
        URL.revokeObjectURL(url);
        window.reliqToast?.success("Workspace data exported. (Mock)");
      },
    });
  };

  const clearLocalData = () => {
    window.reliqConfirm?.show({
      title: "Clear all local prototype data?",
      message: "This resets all localStorage data including your auth session, subscription state, team members, scan history, and settings. You will be signed out and returned to the landing page. This only clears local data — no server data is affected.",
      danger: true,
      confirmLabel: "Clear all local data",
      onConfirm: () => {
        try {
          const keys = Object.keys(localStorage).filter(k => k.startsWith("reliq"));
          keys.forEach(k => localStorage.removeItem(k));
        } catch (_) {}
        window.reliqToast?.success("All local prototype data cleared. Redirecting…");
        setTimeout(() => { go("/"); }, 1200);
      },
    });
  };

  const deleteAccount = () => {
    window.reliqConfirm?.show({
      title: "Delete your account?",
      message: "Your account profile, session, and personal settings will be cleared locally. Workspace data is not deleted — workspace ownership must be transferred first. (Mock — no real account deletion occurs.)",
      danger: true,
      confirmLabel: "Delete my account",
      onConfirm: () => {
        // Clear only account-scoped keys, not workspace data
        const accountKeys = [
          SG_KEYS.USER_PROFILE, SG_KEYS.SECURITY_SETTINGS,
          SG_KEYS.ACTIVE_SESSIONS, SG_KEYS.SECURITY_EVENTS,
          SG_KEYS.NOTIFICATION_PREFS, SG_KEYS.SCAN_DEFAULTS,
        ];
        accountKeys.forEach(k => { try { localStorage.removeItem(k); } catch (_) {} });
        try { window.reliqAuth?.logoutRequest?.(); } catch (_) {}
        window.reliqSubscription?.logout();
        window.reliqToast?.info("Account deleted locally. (Mock — no real deletion.) Redirecting…");
        setTimeout(() => { go("/signin"); }, 1500);
      },
    });
  };

  const deleteWorkspace = () => {
    if (!isOwner) {
      window.reliqToast?.error("Only the workspace owner can delete the workspace.");
      return;
    }
    window.reliqConfirm?.show({
      title: "Delete this workspace?",
      message: "All apps, scans, reports, API keys, team members, and billing data will be permanently erased locally. (Mock — no real deletion occurs.) This cannot be recovered.",
      danger: true,
      confirmLabel: "Delete workspace",
      onConfirm: () => {
        const workspaceKeys = [
          "reliq_workspace","reliq_team_members","reliq_sso_settings","reliq_audit_log",
          "reliq_api_keys","reliq_webhook_endpoints","reliq_webhook_deliveries",
        ];
        workspaceKeys.forEach(k => { try { localStorage.removeItem(k); } catch (_) {} });
        try { window.reliqAuth?.logoutRequest?.(); } catch (_) {}
        window.reliqSubscription?.logout();
        window.reliqToast?.error("Workspace deleted locally. (Mock — no real deletion.) Redirecting…");
        setTimeout(() => { go("/"); }, 1500);
      },
    });
  };

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <AuthLayout
      route="settings"
      go={go}
      crumbs={["Workspace", "Developer", "Settings"]}
      maxWidth={1080}
      actions={showHeaderSave ? (
        <button className="btn btn-sm btn-primary" onClick={handleHeaderSave}>
          <Icon name="check" size={13} /> Save changes
        </button>
      ) : null}
    >
      <div className="page-head">
        <div>
          <h1 className="page-title">Settings</h1>
          <p className="page-sub">Profile, workspace, notifications, scan defaults, and security.</p>
        </div>
      </div>

      <div className="tabs">
        {[
          { id: "profile",       label: "Profile",       ic: "users" },
          { id: "workspace",     label: "Workspace",     ic: "folder" },
          { id: "notifications", label: "Notifications", ic: "bell" },
          { id: "scan",          label: "Scan defaults", ic: "scan" },
          { id: "security",      label: "Security",      ic: "lock" },
          { id: "danger",        label: "Danger zone",   ic: "alert" },
        ].map(t => (
          <div key={t.id}
            className={`tab ${tab === t.id ? "active" : ""}`}
            onClick={() => setTab(t.id)}
          >
            <Icon name={t.ic} size={14} />{t.label}
          </div>
        ))}
      </div>

      {/* ── PROFILE TAB ───────────────────────────────────────────────────── */}
      {tab === "profile" && (
        <div style={{ display:"grid", gridTemplateColumns:"1.5fr 1fr", gap:16 }}>
          {/* Personal details */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Personal details</div>
            </div>
            <div className="card-body" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16 }}>

              <div className="field">
                <label>Full name</label>
                <input
                  value={profile.name}
                  onChange={e => updateProfile("name", e.target.value)}
                  placeholder="Your full name"
                />
                {profileErrors.name && <div className="hint" style={{color:"var(--red)"}}>{profileErrors.name}</div>}
              </div>

              <div className="field">
                <label>Role</label>
                <input value={roleLabel} readOnly
                  style={{ background:"var(--bg-2)", color:"var(--fg-2)", cursor:"default" }}
                />
                <div className="hint">Your role is set by the workspace owner.</div>
              </div>

              <div className="field" style={{ gridColumn:"1 / -1" }}>
                <label>Account email</label>
                <input
                  value={profile.email}
                  onChange={e => updateProfile("email", e.target.value)}
                  placeholder="you@example.com"
                />
                {profileErrors.email && <div className="hint" style={{color:"var(--red)"}}>{profileErrors.email}</div>}
              </div>

              <div className="field" style={{ gridColumn:"1 / -1" }}>
                <label>Notification email</label>
                <input
                  value={profile.notificationEmail}
                  onChange={e => updateProfile("notificationEmail", e.target.value)}
                  placeholder="you@example.com"
                />
                {profileErrors.notificationEmail && <div className="hint" style={{color:"var(--red)"}}>{profileErrors.notificationEmail}</div>}
                <div className="hint">Scan alerts and digest emails go here. Defaults to your account email.</div>
              </div>

              <div className="field">
                <label>Timezone</label>
                <select value={profile.timezone} onChange={e => updateProfile("timezone", e.target.value)}>
                  <option value="Africa/Johannesburg">Africa/Johannesburg (UTC+2)</option>
                  <option value="America/New_York">America/New_York (UTC-5)</option>
                  <option value="America/Los_Angeles">America/Los_Angeles (UTC-8)</option>
                  <option value="Europe/London">Europe/London (UTC+0)</option>
                  <option value="Europe/Berlin">Europe/Berlin (UTC+1)</option>
                  <option value="Asia/Singapore">Asia/Singapore (UTC+8)</option>
                  <option value="Asia/Tokyo">Asia/Tokyo (UTC+9)</option>
                  <option value="Australia/Sydney">Australia/Sydney (UTC+11)</option>
                </select>
              </div>

              <div className="field">
                <label>Sign-in method</label>
                <div style={{
                  display:"flex", alignItems:"center", gap:8,
                  padding:"9px 12px",
                  background:"var(--bg-2)", border:"1px solid var(--line-2)",
                  borderRadius:6, fontSize:13, color:"var(--fg-2)",
                }}>
                  <Icon name={authProvider === "github" ? "git-branch" : "lock"} size={13} />
                  {authProvider === "github" ? "GitHub OAuth" : "Email & password"}
                </div>
              </div>

              <div style={{ gridColumn:"1 / -1" }}>
                <button className="btn btn-primary" onClick={saveProfile}>
                  <Icon name="check" size={13} /> Save profile
                </button>
              </div>
            </div>
          </div>

          {/* Avatar */}
          <div className="card">
            <div className="card-head"><div className="card-title">Avatar</div></div>
            <div className="card-body" style={{
              display:"flex", flexDirection:"column",
              alignItems:"center", gap:18, padding:"32px 18px",
            }}>
              <div className="avatar" style={{
                width:92, height:92, fontSize:32,
                background:"linear-gradient(135deg, #A78BFA, #5B9DFF)",
              }}>
                {profile.avatarInitials || "ZL"}
              </div>
              <div style={{ textAlign:"center" }}>
                <div style={{ fontWeight:500, fontSize:14 }}>{profile.name || "—"}</div>
                <div className="mono" style={{ fontSize:12, color:"var(--fg-2)" }}>
                  {roleLabel} · {(window.reliqPlans?.getCurrentPlanLabel?.() || window.reliqSubscription?.getPlan() || "Pro")} plan
                </div>
              </div>
              <div style={{ display:"flex", gap:8 }}>
                <button
                  className="btn btn-sm"
                  onClick={() => window.reliqToast?.info("Avatar upload is not available in the prototype.")}
                >
                  <Icon name="upload" size={12} /> Upload
                </button>
                <button
                  className="btn btn-sm btn-ghost"
                  style={{ color:"var(--red)" }}
                  onClick={() => window.reliqConfirm?.show({
                    title: "Remove profile picture?",
                    message: "Your profile picture will be removed and replaced with your initials.",
                    danger: false,
                    confirmLabel: "Remove photo",
                    onConfirm: () => window.reliqToast?.info("Profile picture removed. (Mock)"),
                  })}
                >Remove</button>
              </div>
              <div className="mono" style={{ fontSize:11, color:"var(--fg-3)", textAlign:"center" }}>
                PNG or JPG · 256×256 min · 2 MB max
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── WORKSPACE TAB ─────────────────────────────────────────────────── */}
      {tab === "workspace" && (
        <div className="card">
          <div className="card-head">
            <div className="card-title">Workspace settings</div>
            {!canEditWorkspace && (
              <span className="chip" style={{ marginLeft:"auto", color:"var(--fg-3)" }}>
                <Icon name="lock" size={10} /> View only
              </span>
            )}
          </div>
          <div className="card-body" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:18 }}>

            <div className="field">
              <label>Workspace name</label>
              <input
                value={workspace.name || ""}
                onChange={e => updateWorkspace("name", e.target.value)}
                disabled={!canEditWorkspace}
              />
            </div>

            <div className="field">
              <label>URL slug</label>
              <div style={{
                display:"flex", alignItems:"center",
                background:"var(--bg-1)", border:"1px solid var(--line-2)",
                borderRadius:6, padding:"0 10px",
              }}>
                <span className="mono" style={{ fontSize:13, color:"var(--fg-3)" }}>reliq.dev/</span>
                <input
                  value={workspace.slug || ""}
                  onChange={e => updateWorkspace("slug", e.target.value.toLowerCase().replace(/[^a-z0-9-]/g,""))}
                  disabled={!canEditWorkspace}
                  style={{ border:0, padding:"9px 0" }}
                />
              </div>
            </div>

            <div className="field" style={{ gridColumn:"1 / -1" }}>
              <label>Workspace logo</label>
              <div style={{ display:"flex", alignItems:"center", gap:14 }}>
                <AppIcon letters="R" size={48} gradient="linear-gradient(135deg,#5B9DFF,#A78BFA)" />
                <button
                  className="btn btn-sm"
                  disabled={!canEditWorkspace}
                  onClick={() => window.reliqToast?.info("Logo upload is not available in the prototype.")}
                >
                  <Icon name="upload" size={12} /> Change logo
                </button>
                <span className="mono" style={{ fontSize:11.5, color:"var(--fg-3)" }}>
                  Shown on shared reports and PDF exports
                </span>
              </div>
            </div>

            <div className="field">
              <label>Billing email</label>
              <input
                value={workspace.billingEmail || ""}
                onChange={e => updateWorkspace("billingEmail", e.target.value)}
                disabled={!canEditWorkspace}
                placeholder="billing@example.com"
              />
            </div>

            <div className="field">
              <label>Workspace timezone</label>
              <select
                value={workspace.timezone || "Africa/Johannesburg"}
                onChange={e => updateWorkspace("timezone", e.target.value)}
                disabled={!canEditWorkspace}
              >
                <option value="Africa/Johannesburg">Africa/Johannesburg (UTC+2)</option>
                <option value="America/New_York">America/New_York (UTC-5)</option>
                <option value="Europe/London">Europe/London (UTC+0)</option>
                <option value="Europe/Berlin">Europe/Berlin (UTC+1)</option>
                <option value="Asia/Singapore">Asia/Singapore (UTC+8)</option>
              </select>
            </div>

            <div className="field" style={{ gridColumn:"1 / -1" }}>
              <label>Custom domain (white-label reports)</label>
              <input placeholder="reports.roamly.app" disabled />
              <div className="hint">
                Available on Team plan ·{" "}
                <span style={{ color:"var(--teal)", cursor:"pointer" }} onClick={() => go("/billing")}>
                  upgrade to enable
                </span>
              </div>
            </div>

            {canEditWorkspace && (
              <div style={{ gridColumn:"1 / -1" }}>
                <button className="btn btn-primary" onClick={saveWorkspace}>
                  <Icon name="check" size={13} /> Save workspace settings
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ── NOTIFICATIONS TAB ─────────────────────────────────────────────── */}
      {tab === "notifications" && (
        <div className="card">
          <div className="card-head">
            <div className="card-title">Notification preferences</div>
            <div className="card-sub" style={{ marginLeft:"auto", display:"flex", gap:8 }}>
              <button className="btn btn-sm btn-ghost" onClick={resetNotifPrefs}>Reset to defaults</button>
              <button className="btn btn-sm btn-primary" onClick={saveNotifPrefs}>
                <Icon name="check" size={13} /> Save
              </button>
            </div>
          </div>

          <SgSection label="Scan activity" first />
          <PrefRow
            title="Scan completed"
            sub="Notify when any scan finishes — pass or fail."
            value={notifPrefs.scanCompleted}
            onChange={() => toggleNotif("scanCompleted")}
          />
          <PrefRow
            title="High-risk finding"
            sub="Alert immediately when a critical or high severity issue is detected."
            value={notifPrefs.highRiskFinding}
            onChange={() => toggleNotif("highRiskFinding")}
          />
          <PrefRow
            title="Report generated"
            sub="Notify when a compliance report is ready to view or share."
            value={notifPrefs.reportGenerated}
            onChange={() => toggleNotif("reportGenerated")}
          />

          <SgSection label="Integrations" />
          <PrefRow
            title="Webhook failure"
            sub="Alert when a webhook endpoint returns an error or times out."
            value={notifPrefs.webhookFailure}
            onChange={() => toggleNotif("webhookFailure")}
          />

          <SgSection label="Account & billing" />
          <PrefRow
            title="Billing alerts"
            sub="Payment failures, plan changes, and usage limit warnings. Required for account safety."
            value={notifPrefs.billingAlerts}
            onChange={() => toggleNotif("billingAlerts")}
            required
          />
          <PrefRow
            title="Security alerts"
            sub="New sign-ins, password changes, and 2FA events. Required for account safety."
            value={notifPrefs.securityAlerts}
            onChange={() => toggleNotif("securityAlerts")}
            required
          />
          <PrefRow
            title="Team invites"
            sub="Notify when a new member is invited to or joins your workspace."
            value={notifPrefs.teamInvites}
            onChange={() => toggleNotif("teamInvites")}
          />
          <PrefRow
            title="Policy updates"
            sub="When new or changed Apple/Google Play policy checks are added to the library."
            value={notifPrefs.policyUpdates}
            onChange={() => toggleNotif("policyUpdates")}
          />
          <PrefRow
            title="Product updates"
            sub="Occasional emails about new features, integrations, and release notes."
            value={notifPrefs.productUpdates}
            onChange={() => toggleNotif("productUpdates")}
          />

          <SgSection label="Channels" />
          <PrefRow
            title="Email notifications"
            sub="Receive the above events via email to your notification email address."
            value={notifPrefs.emailNotifications}
            onChange={() => toggleNotif("emailNotifications")}
          />
          <PrefRow
            title="In-app notifications"
            sub="Show the above events in the notification bell inside the Reliq dashboard."
            value={notifPrefs.inAppNotifications}
            onChange={() => toggleNotif("inAppNotifications")}
            last
          />
        </div>
      )}

      {/* ── SCAN DEFAULTS TAB ─────────────────────────────────────────────── */}
      {tab === "scan" && (
        <div className="card">
          <div className="card-head">
            <div className="card-title">Scan defaults</div>
            <div style={{ marginLeft:"auto" }}>
              <button className="btn btn-sm btn-primary" onClick={saveScanDefs}>
                <Icon name="check" size={13} /> Save
              </button>
            </div>
          </div>
          <div>
            {[
              { k:"aiChecks",     title:"AI policy review",             sub:"Use Claude to review metadata and string resources for policy violations. Adds ~30 s per scan." },
              { k:"deepScan",     title:"Deep static analysis",         sub:"Decompile to source level and run extended secret scans. Slower but more thorough." },
              { k:"autoRescan",   title:"Auto re-scan on push",         sub:"When a connected GitHub repo pushes a tagged build, re-run Reliq automatically." },
              { k:"publicReports",title:"Public-by-default reports",    sub:"New scan reports are accessible via shareable link without authentication." },
              { k:"storeBeta",    title:"Enable beta policy checks",     sub:"Include checks for upcoming Play/App Store policy changes (may flag false positives)." },
            ].map((s, i) => (
              <div key={s.k} style={{
                display:"flex", alignItems:"center", gap:14,
                padding:"16px 18px",
                borderTop:"1px solid var(--line-1)",
              }}>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13.5, fontWeight:500 }}>{s.title}</div>
                  <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:2, maxWidth:600 }}>{s.sub}</div>
                </div>
                <div
                  className={`toggle ${scanDefs[s.k] ? "on" : ""}`}
                  onClick={() => toggleScan(s.k)}
                />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── SECURITY TAB ──────────────────────────────────────────────────── */}
      {tab === "security" && (
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>

          {/* Password */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Password</div>
              <span className="card-sub" style={{ marginLeft:"auto" }}>
                Last changed {fmtDate(security.passwordLastChanged)}
              </span>
            </div>
            {authProvider === "github" ? (
              <div className="card-body">
                <div style={{ display:"flex", alignItems:"center", gap:10, color:"var(--fg-2)", fontSize:13 }}>
                  <Icon name="git-branch" size={14} />
                  You signed in with GitHub. Password management is handled by GitHub.
                </div>
              </div>
            ) : (
              <div className="card-body" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16 }}>
                <div className="field" style={{ gridColumn:"1 / -1" }}>
                  <label>Current password</label>
                  <input type="password" value={pwForm.current}
                    onChange={e => updatePw("current", e.target.value)}
                    placeholder="Enter current password"
                  />
                  {pwErrors.current && <div className="hint" style={{color:"var(--red)"}}>{pwErrors.current}</div>}
                </div>
                <div className="field">
                  <label>New password</label>
                  <input type="password" value={pwForm.next}
                    onChange={e => updatePw("next", e.target.value)}
                    placeholder="8+ characters"
                  />
                  {pwErrors.next && <div className="hint" style={{color:"var(--red)"}}>{pwErrors.next}</div>}
                </div>
                <div className="field">
                  <label>Confirm new password</label>
                  <input type="password" value={pwForm.confirm}
                    onChange={e => updatePw("confirm", e.target.value)}
                    placeholder="Repeat new password"
                  />
                  {pwErrors.confirm && <div className="hint" style={{color:"var(--red)"}}>{pwErrors.confirm}</div>}
                </div>
                <div style={{ gridColumn:"1 / -1" }}>
                  <button className="btn btn-primary" onClick={submitPassword}>
                    <Icon name="lock" size={13} /> Update password
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* 2FA */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Two-factor authentication</div>
              <span className="chip" style={{
                marginLeft:"auto",
                color: security.twoFactorEnabled ? "var(--teal)" : "var(--fg-3)",
                borderColor: security.twoFactorEnabled ? "rgba(0,212,170,0.25)" : "var(--line-2)",
                background: security.twoFactorEnabled ? "var(--teal-bg)" : "var(--bg-2)",
              }}>
                {security.twoFactorEnabled
                  ? <><Icon name="check" size={10} /> Enabled</>
                  : <><Icon name="x" size={10} /> Disabled</>}
              </span>
            </div>
            <div className="card-body" style={{ display:"flex", alignItems:"center", gap:18 }}>
              <div style={{
                width:44, height:44, borderRadius:10, flexShrink:0,
                background: security.twoFactorEnabled ? "var(--teal-bg)" : "var(--bg-2)",
                border: security.twoFactorEnabled ? "1px solid rgba(0,212,170,0.3)" : "1px solid var(--line-2)",
                display:"grid", placeItems:"center",
                color: security.twoFactorEnabled ? "var(--teal)" : "var(--fg-3)",
              }}>
                <Icon name="shield" size={20} />
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>
                  {security.twoFactorEnabled ? "Authenticator app" : "Not configured"}
                </div>
                <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:2 }}>
                  {security.twoFactorEnabled
                    ? "6-digit TOTP · 8 recovery codes available (Mock)"
                    : "Enable 2FA for stronger account security."}
                </div>
              </div>
              {security.twoFactorEnabled && (
                <button className="btn btn-sm" onClick={viewRecoveryCodes}>View recovery codes</button>
              )}
              <button
                className="btn btn-sm btn-ghost"
                style={{ color: security.twoFactorEnabled ? "var(--red)" : "var(--teal)" }}
                onClick={toggle2FA}
              >
                {security.twoFactorEnabled ? "Disable 2FA" : "Enable 2FA"}
              </button>
            </div>
          </div>

          {/* Connected accounts */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Connected accounts</div>
            </div>
            <div style={{
              display:"flex", alignItems:"center", gap:14,
              padding:"14px 18px", borderTop:"1px solid var(--line-1)",
            }}>
              <div style={{
                width:32, height:32, borderRadius:8,
                background:"var(--bg-2)", border:"1px solid var(--line-2)",
                display:"grid", placeItems:"center",
              }}>
                <Icon name="git-branch" size={14} />
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>GitHub</div>
                <div className="mono" style={{ fontSize:11.5, color:"var(--fg-3)", marginTop:2 }}>
                  {githubConnected
                    ? `Connected · ${profile.email}`
                    : "Not connected"}
                </div>
              </div>
              {githubConnected ? (
                <button
                  className="btn btn-sm btn-ghost"
                  style={{ color:"var(--red)" }}
                  onClick={() => window.reliqConfirm?.show({
                    title: "Disconnect GitHub?",
                    message: "You will no longer be able to sign in with GitHub. You must have a password set before disconnecting. (Mock — no real change.)",
                    danger: true,
                    confirmLabel: "Disconnect GitHub",
                    onConfirm: () => {
                      const updated = { ...security, githubConnected: false };
                      setSecurity(updated);
                      _sgSave(SG_KEYS.SECURITY_SETTINGS, updated);
                      window.reliqToast?.info("GitHub disconnected. (Mock)");
                    },
                  })}
                >Disconnect</button>
              ) : (
                <button
                  className="btn btn-sm"
                  onClick={() => window.reliqToast?.info("GitHub OAuth connection is not available in the prototype.")}
                >Connect</button>
              )}
            </div>
          </div>

          {/* Active sessions */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Active sessions</div>
              <span className="card-sub">Auto-expire after 30 days of inactivity</span>
              {sessions.filter(s => !s.isCurrent).length > 0 && (
                <button
                  className="btn btn-sm btn-ghost"
                  style={{ marginLeft:"auto", color:"var(--red)" }}
                  onClick={revokeAllOther}
                >
                  Revoke all other
                </button>
              )}
            </div>
            <div>
              {sessions.map((s, i) => (
                <div key={s.id} style={{
                  display:"flex", alignItems:"center", gap:14,
                  padding:"14px 18px", borderTop:"1px solid var(--line-1)",
                }}>
                  <div style={{
                    width:32, height:32, borderRadius:8,
                    background:"var(--bg-2)", border:"1px solid var(--line-2)",
                    display:"grid", placeItems:"center",
                  }}>
                    <Icon name="cpu" size={14} />
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13.5, fontWeight:500 }}>
                      {s.device}
                      {s.isCurrent && (
                        <span className="chip" style={{
                          marginLeft:8, fontSize:10.5,
                          color:"var(--teal)", borderColor:"rgba(0,212,170,0.25)",
                          background:"var(--teal-bg)",
                        }}>
                          <span className="live-dot" style={{width:5, height:5}} />
                          Current
                        </span>
                      )}
                    </div>
                    <div className="mono" style={{ fontSize:11.5, color:"var(--fg-3)", marginTop:2 }}>
                      {s.location} · {s.ip}
                      {s.isCurrent ? " · Active now" : ` · Last active ${fmtDate(s.lastActiveAt)}`}
                    </div>
                  </div>
                  {!s.isCurrent && (
                    <button
                      className="btn btn-sm btn-ghost"
                      style={{ color:"var(--red)" }}
                      onClick={() => revokeSession(s)}
                    >Revoke</button>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Security events */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Security events</div>
              <span className="card-sub">Recent account activity</span>
            </div>
            <div>
              {secEvents.slice(0, 8).map((ev, i) => (
                <div key={ev.id} style={{
                  display:"flex", alignItems:"flex-start", gap:12,
                  padding:"12px 18px", borderTop:"1px solid var(--line-1)",
                }}>
                  <div style={{
                    width:28, height:28, borderRadius:7, flexShrink:0,
                    background:"var(--bg-2)", border:"1px solid var(--line-2)",
                    display:"grid", placeItems:"center", marginTop:1,
                  }}>
                    <Icon name="lock" size={12} style={{ color:"var(--fg-3)" }} />
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:500 }}>
                      {SEVT_LABELS[ev.event] || ev.event}
                    </div>
                    <div className="mono" style={{ fontSize:11, color:"var(--fg-3)", marginTop:2 }}>
                      {ev.device || ev.actor} · {ev.location} · {fmtDate(ev.timestamp)}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ── DANGER ZONE TAB ───────────────────────────────────────────────── */}
      {tab === "danger" && (
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>

          {/* Data export */}
          <div className="card">
            <div className="card-head">
              <Icon name="download" size={15} style={{ color:"var(--blue)" }} />
              <div className="card-title">Data export</div>
            </div>
            <MockBanner msg="Exports are generated locally from your prototype data. No server data is included." />
            {[
              {
                title: "Export account data",
                sub: "Download a JSON file with your profile, notification preferences, and security settings.",
                action: "Export account",
                onClick: exportAccountData,
              },
              {
                title: "Export workspace data",
                sub: "Download a JSON file with workspace settings, team members, and the audit log.",
                action: "Export workspace",
                onClick: exportWorkspaceData,
              },
            ].map((d) => (
              <div key={d.title} style={{
                display:"flex", alignItems:"center", gap:16,
                padding:"18px", borderTop:"1px solid var(--line-1)",
              }}>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13.5, fontWeight:500 }}>{d.title}</div>
                  <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>{d.sub}</div>
                </div>
                <button className="btn btn-sm" onClick={d.onClick}>
                  <Icon name="download" size={12} /> {d.action}
                </button>
              </div>
            ))}
          </div>

          {/* Danger zone */}
          <div className="card" style={{ borderColor:"rgba(239,68,68,0.25)" }}>
            <div className="card-head" style={{ borderColor:"rgba(239,68,68,0.18)" }}>
              <Icon name="alert" size={16} style={{ color:"var(--red)" }} />
              <div className="card-title" style={{ color:"var(--red)" }}>Danger zone</div>
            </div>
            <MockBanner msg="All actions below are local prototype operations only. No real data is deleted from any server." />

            {/* Reset scan history */}
            <div style={{
              display:"flex", alignItems:"center", gap:16,
              padding:"18px", borderTop:"1px solid rgba(239,68,68,0.12)",
            }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>Reset scan history</div>
                <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>
                  Permanently delete all stored scans, reports and shared links from local storage. API keys remain.
                </div>
              </div>
              <button
                className="btn btn-sm"
                style={{ borderColor:"rgba(239,68,68,0.35)", color:"var(--red)", background:"var(--red-bg)" }}
                onClick={() => window.reliqConfirm?.show({
                  title: "Reset scan history?",
                  message: "All scans, reports, and shared links will be cleared from local storage. API keys are not affected. (Mock — no real deletion.)",
                  danger: true,
                  confirmLabel: "Reset history",
                  onConfirm: () => window.reliqToast?.success("Scan history reset. (Mock)"),
                })}
              >Reset history</button>
            </div>

            {/* Clear local prototype data */}
            <div style={{
              display:"flex", alignItems:"center", gap:16,
              padding:"18px", borderTop:"1px solid rgba(239,68,68,0.12)",
            }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>Clear all local prototype data</div>
                <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>
                  Wipes all <span className="mono" style={{fontSize:11}}>reliq_*</span> keys from localStorage. Resets the app to its fresh state. You will be signed out.
                </div>
              </div>
              <button
                className="btn btn-sm"
                style={{ borderColor:"rgba(239,68,68,0.35)", color:"var(--red)", background:"var(--red-bg)" }}
                onClick={clearLocalData}
              >Clear local data</button>
            </div>

            {/* Transfer workspace */}
            <div style={{
              display:"flex", alignItems:"center", gap:16,
              padding:"18px", borderTop:"1px solid rgba(239,68,68,0.12)",
            }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>Transfer workspace ownership</div>
                <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>
                  Hand off the workspace to another admin. You'll be downgraded to admin after the transfer is accepted.
                </div>
              </div>
              <button
                className="btn btn-sm"
                style={{ borderColor:"rgba(239,68,68,0.35)", color:"var(--red)", background:"var(--red-bg)" }}
                onClick={() => window.reliqConfirm?.show({
                  title: "Transfer workspace ownership?",
                  message: "You'll be downgraded to Admin after the transfer is accepted. The new owner will receive an email to confirm. (Mock — no real transfer.)",
                  danger: false,
                  confirmLabel: "Transfer ownership",
                  onConfirm: () => window.reliqToast?.info("Transfer request sent. (Mock)"),
                })}
              >Transfer</button>
            </div>

            {/* Delete account */}
            <div style={{
              display:"flex", alignItems:"center", gap:16,
              padding:"18px", borderTop:"1px solid rgba(239,68,68,0.12)",
            }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>Delete my account</div>
                <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>
                  Clears your account profile and session. Workspace data is separate — transfer ownership first if you are the workspace owner.
                </div>
              </div>
              <button
                className="btn btn-sm"
                style={{ borderColor:"rgba(239,68,68,0.35)", color:"var(--red)", background:"var(--red-bg)" }}
                onClick={deleteAccount}
              >Delete account</button>
            </div>

            {/* Delete workspace — owner only */}
            <div style={{
              display:"flex", alignItems:"center", gap:16,
              padding:"18px", borderTop:"1px solid rgba(239,68,68,0.12)",
            }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:500, display:"flex", alignItems:"center", gap:8 }}>
                  Delete workspace
                  {!isOwner && (
                    <span className="chip" style={{ fontSize:10, color:"var(--fg-3)" }}>
                      <Icon name="lock" size={9} /> Owner only
                    </span>
                  )}
                </div>
                <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>
                  {isOwner
                    ? "Permanently delete this workspace and all its data. This action cannot be undone."
                    : "Only the workspace owner can delete the workspace. Contact your workspace owner."}
                </div>
              </div>
              <button
                className="btn btn-sm"
                style={{
                  borderColor:"rgba(239,68,68,0.35)", color:"var(--red)", background:"var(--red-bg)",
                  opacity: isOwner ? 1 : 0.5, cursor: isOwner ? "pointer" : "not-allowed",
                }}
                onClick={isOwner ? deleteWorkspace : () => window.reliqToast?.error("Only the workspace owner can delete the workspace.")}
              >Delete workspace</button>
            </div>
          </div>
        </div>
      )}
    </AuthLayout>
  );
};

Object.assign(window, { SettingsGeneral });
