// Screen 12: Settings Tab — admin only · users / BOMs / integrations / station
const { useState: useStateSet } = React;

function SettingsTab({ user }) {
  const [sub, setSub] = useStateSet("USERS");
  return (
    <div className="flex-1 flex flex-col">
      <div className="px-8 pt-5 pb-3 border-b border-zinc-800 flex gap-1">
        {["USERS", "BOMs", "PARTS & TYPES", "INTEGRATIONS", "STATIONS"].map((i) => {
          const isActive = i === sub;
          return (
            <button key={i} onClick={() => setSub(i)}
              className={`h-10 px-5 rounded-lg font-display text-[15px] tracking-wider transition ${
                isActive ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:bg-zinc-900 hover:text-zinc-200"
              }`}>
              {i}
            </button>
          );
        })}
      </div>
      {sub === "USERS" && <UsersAdmin />}
      {sub === "BOMs" && <BOMsAdmin />}
      {sub === "PARTS & TYPES" && <PartsTypesAdmin />}
      {sub === "INTEGRATIONS" && <IntegrationsAdmin />}
      {sub === "STATIONS" && <StationAdmin />}
    </div>
  );
}

function UsersAdmin() {
  const [showAdd, setShowAdd] = useStateSet(false);
  const [filter, setFilter] = useStateSet("ACTIVE");
  const [drawer, setDrawer] = useStateSet(null);
  const [users, setUsers] = useStateSet(window.USERS || []);
  const [search, setSearch] = useStateSet("");

  async function reloadUsers() {
    try {
      const all = await fetch('/api/users?include_inactive=1').then(r => r.json());
      setUsers(all);
      window.USERS = all;
    } catch {}
  }

  const filtered = users.filter(u => {
    if (filter === "ACTIVE" && !u.active) return false;
    if (search && !u.name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1200px] mx-auto space-y-5">
        <div className="flex items-center gap-3 flex-wrap">
          <input placeholder="Search users…" value={search} onChange={e => setSearch(e.target.value)}
            className="h-12 px-4 bg-zinc-900 border border-zinc-800 rounded-lg text-zinc-100 text-[15px] outline-none focus:border-zinc-600 w-[280px]" />
          <div className="flex gap-1 bg-zinc-900 border border-zinc-800 rounded-lg p-1">
            {["ACTIVE", "ALL"].map((f) => (
              <button key={f} onClick={() => setFilter(f)}
                className={`h-9 px-4 rounded text-[13px] font-display tracking-wider ${
                  filter === f ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:text-zinc-200"
                }`}>{f}</button>
            ))}
          </div>
          <button onClick={() => setShowAdd(true)}
            className="ml-auto h-12 px-5 rounded-lg font-display text-[16px] tracking-wider text-zinc-100 hover:opacity-90"
            style={{ background: window.GPS_RED }}>
            + ADD USER
          </button>
        </div>

        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
          <div className="grid grid-cols-[60px_2fr_1fr_1fr_1fr_1fr] text-[11px] uppercase tracking-wider text-zinc-500 px-4 py-3 border-b border-zinc-800 bg-zinc-950/60">
            <div></div><div>Name</div><div>Role</div><div>Shift</div><div>Status</div><div></div>
          </div>
          <div className="divide-y divide-zinc-800/80">
            {filtered.map((u) => (
              <button key={u.id} onClick={() => setDrawer(u)}
                className="w-full grid grid-cols-[60px_2fr_1fr_1fr_1fr_1fr] items-center px-4 py-3 text-[14px] hover:bg-zinc-800/40 text-left">
                <window.Avatar user={u} size={40} />
                <div className={u.active ? "" : "text-zinc-500 line-through"}>{u.name}</div>
                <div><window.RoleBadge role={u.role} /></div>
                <div className="text-zinc-400">{u.shift}</div>
                <div>{u.active
                  ? <span className="px-2 py-0.5 rounded text-[11px] font-bold tracking-wider uppercase border bg-emerald-500/10 text-emerald-300 border-emerald-500/30">● ACTIVE</span>
                  : <span className="px-2 py-0.5 rounded text-[11px] font-bold tracking-wider uppercase border bg-zinc-800 text-zinc-500 border-zinc-700">INACTIVE</span>
                }</div>
                <div className="flex gap-1 justify-end">
                  <span className="h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-300 text-[12px] uppercase tracking-wider flex items-center">Details →</span>
                </div>
              </button>
            ))}
            {filtered.length === 0 && (
              <div className="px-5 py-8 text-center text-zinc-500">No users found.</div>
            )}
          </div>
        </div>

        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
          <div className="px-5 py-4 border-b border-zinc-800 flex items-center justify-between">
            <div className="font-display text-[22px] tracking-wider text-zinc-300">ACTIVITY LOG</div>
          </div>
          <div className="divide-y divide-zinc-800/80 max-h-[400px] overflow-y-auto">
            {window.ACTIVITY_LOG.map((a, i) => (
              <div key={i} className="grid grid-cols-[140px_1.6fr_180px_2.5fr] items-center px-5 py-2.5 text-[13px]">
                <div className="text-zinc-400 font-mono text-[12px]">{a.time}</div>
                <div className="text-zinc-200">{a.user}</div>
                <div><span className="font-mono text-[11px] text-zinc-400 bg-zinc-800/60 border border-zinc-800 rounded px-2 py-0.5">{a.event}</span></div>
                <div className="text-zinc-400">{a.detail}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {showAdd && <AddUserModal onClose={() => { setShowAdd(false); reloadUsers(); }} />}
      {drawer && <UserDetailDrawer user={drawer} onClose={() => setDrawer(null)} onSaved={() => { setDrawer(null); reloadUsers(); }} />}
    </div>
  );
}

function UserDetailDrawer({ user, onClose, onSaved }) {
  const [tab, setTab] = useStateSet("OVERVIEW");
  const [overlay, setOverlay] = useStateSet(null); // 'confirmDeact' | 'resetPin' | 'edit'
  const [newPin, setNewPin] = useStateSet("");
  const [editData, setEditData] = useStateSet({ name: user.name, role: user.role, shift: user.shift, email: user.email || "", phone: user.phone || "", notes: user.notes || "" });
  const [saving, setSaving] = useStateSet(false);
  const earnedIds = window.BADGES_EARNED?.[user.name] || [];
  const userActivity = (window.ACTIVITY_LOG || []).filter((a) => a.user === user.name);

  async function doResetPin() {
    const pin = String(Math.floor(1000 + Math.random() * 9000));
    setNewPin(pin);
    setSaving(true);
    await fetch(`/api/users/${user.id}`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...user, pin, earned_badges: user.earned_badges }),
    });
    setSaving(false);
    setOverlay('showPin');
  }

  async function doDeactivate() {
    await fetch(`/api/users/${user.id}`, { method: 'DELETE' });
    onSaved();
  }

  async function doReactivate() {
    await fetch(`/api/users/${user.id}`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...user, active: true, earned_badges: user.earned_badges }),
    });
    onSaved();
  }

  async function saveEdit() {
    setSaving(true);
    await fetch(`/api/users/${user.id}`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...user, ...editData, earned_badges: user.earned_badges }),
    });
    setSaving(false);
    onSaved();
  }

  return (
    <div className="fixed inset-0 z-50 bg-zinc-950/80 backdrop-blur-sm flex items-stretch justify-end" onClick={onClose}>
      <div className="w-full max-w-[640px] bg-zinc-900 border-l border-zinc-800 flex flex-col relative"
        style={{ animation: "slideInRight 0.22s ease-out" }}
        onClick={(e) => e.stopPropagation()}>

        <div className="px-7 py-5 border-b border-zinc-800 flex items-start justify-between gap-4">
          <div className="flex items-center gap-4">
            <window.Avatar user={user} size={72} />
            <div>
              <div className="font-display text-[36px] tracking-tight leading-none">{user.name}</div>
              <div className="flex items-center gap-3 mt-2">
                <window.RoleBadge role={user.role} />
                <span className="text-[13px] text-zinc-400">{user.shift} shift</span>
                {user.since && <span className="text-[13px] text-zinc-500">since {user.since}</span>}
              </div>
            </div>
          </div>
          <button onClick={onClose}
            className="h-10 w-10 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-zinc-700 flex items-center justify-center">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        <div className="px-7 pt-3 border-b border-zinc-800 flex gap-1">
          {["OVERVIEW", "ACTIVITY", "NOTES"].map((t) => {
            const active = t === tab;
            return (
              <button key={t} onClick={() => setTab(t)}
                className={`relative h-10 px-3 font-display text-[14px] tracking-wider ${active ? "text-zinc-100" : "text-zinc-500 hover:text-zinc-300"}`}>
                {t}
                {active && <div className="absolute bottom-0 left-2 right-2 h-[2px]" style={{ background: window.GPS_RED }} />}
              </button>
            );
          })}
        </div>

        <div className="flex-1 overflow-y-auto px-7 py-5">
          {tab === "OVERVIEW" && (
            <div className="space-y-4">
              {(user.email || user.phone) && (
                <div className="grid grid-cols-2 gap-3">
                  {user.email && <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-3">
                    <div className="text-[10px] uppercase tracking-wider text-zinc-500">Email</div>
                    <div className="text-[14px] text-zinc-200 mt-0.5 truncate">{user.email}</div>
                  </div>}
                  {user.phone && <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-3">
                    <div className="text-[10px] uppercase tracking-wider text-zinc-500">Phone</div>
                    <div className="text-[14px] text-zinc-200 mt-0.5">{user.phone}</div>
                  </div>}
                </div>
              )}
              {window.ALL_BADGES && (
                <div>
                  <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500 mb-3">Badges · {earnedIds.length} / {window.ALL_BADGES.length}</div>
                  <div className="grid grid-cols-4 gap-2">
                    {window.ALL_BADGES.slice(0, 12).map((b) => {
                      const earned = earnedIds.includes(b.id);
                      return (
                        <div key={b.id}
                          className={`rounded-lg border p-2 text-center ${earned ? "bg-zinc-800/50 border-zinc-700" : "bg-zinc-950 border-zinc-800 opacity-40"}`}>
                          <div className={`text-[28px] ${earned ? "" : "grayscale"}`}>{b.icon}</div>
                          <div className={`font-display text-[11px] tracking-wider mt-1 ${earned ? "text-zinc-300" : "text-zinc-600"}`}>{b.name}</div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          )}
          {tab === "ACTIVITY" && (
            <div className="space-y-2">
              {userActivity.length === 0 && <div className="text-zinc-500 text-[14px]">No activity logged yet.</div>}
              {userActivity.map((a, i) => (
                <div key={i} className="bg-zinc-950 border border-zinc-800 rounded-lg p-3">
                  <div className="flex items-center gap-2 text-[12px]">
                    <span className="font-mono text-zinc-500">{a.time}</span>
                    <span className="font-mono text-[10px] text-zinc-400 bg-zinc-800/60 border border-zinc-800 rounded px-2 py-0.5">{a.event}</span>
                  </div>
                  <div className="text-[14px] text-zinc-200 mt-1">{a.detail}</div>
                </div>
              ))}
            </div>
          )}
          {tab === "NOTES" && (
            <div className="space-y-3">
              <textarea value={editData.notes} onChange={e => setEditData(d => ({...d, notes: e.target.value}))}
                placeholder="Add a note about this user…"
                className="w-full h-[200px] bg-zinc-950 border border-zinc-800 rounded-xl p-4 text-[15px] text-zinc-100 outline-none focus:border-zinc-600 resize-none" />
              <button onClick={saveEdit} disabled={saving}
                className="h-12 px-6 rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700 disabled:opacity-50">
                {saving ? "SAVING…" : "SAVE NOTES"}
              </button>
            </div>
          )}
        </div>

        <div className={`px-7 py-4 border-t border-zinc-800 grid gap-2 ${user.active ? "grid-cols-3" : "grid-cols-2"}`}>
          <button onClick={() => setOverlay('resetPin')}
            className="h-[56px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">
            RESET PIN
          </button>
          <button onClick={() => setOverlay('edit')}
            className="h-[56px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">
            EDIT
          </button>
          {user.active
            ? <button onClick={() => setOverlay('confirmDeact')}
                className="h-[56px] rounded-xl bg-red-500/15 border border-red-500/40 text-red-300 font-display text-[14px] tracking-wider hover:bg-red-500/25">
                DEACTIVATE
              </button>
            : <button onClick={doReactivate}
                className="h-[56px] rounded-xl bg-emerald-500/15 border border-emerald-500/40 text-emerald-300 font-display text-[14px] tracking-wider hover:bg-emerald-500/25">
                REACTIVATE
              </button>
          }
        </div>

        {overlay && (
          <div className="absolute inset-0 bg-zinc-950/85 backdrop-blur-sm flex items-center justify-center p-8 z-10">
            <div className="w-full bg-zinc-900 border border-zinc-800 rounded-2xl p-7">
              {overlay === 'confirmDeact' && <>
                <div className="text-[12px] uppercase tracking-[0.22em] text-red-400">Confirm deactivation</div>
                <div className="font-display text-[28px] tracking-tight mt-1">Deactivate {user.name}?</div>
                <div className="text-[14px] text-zinc-400 mt-3">They won't be able to sign in. History and badges are preserved. You can reactivate anytime.</div>
                <div className="grid grid-cols-2 gap-3 mt-6">
                  <button onClick={() => setOverlay(null)} className="h-[52px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">CANCEL</button>
                  <button onClick={doDeactivate} className="h-[52px] rounded-xl bg-red-500 text-white font-display text-[14px] tracking-wider hover:bg-red-400">DEACTIVATE</button>
                </div>
              </>}
              {overlay === 'resetPin' && <>
                <div className="text-[12px] uppercase tracking-[0.22em] text-amber-400">Reset PIN</div>
                <div className="font-display text-[28px] tracking-tight mt-1">Reset PIN for {user.name}?</div>
                <div className="text-[14px] text-zinc-400 mt-3">A new random 4-digit PIN will be set. Give it to them in person — it won't be shown again after you close this.</div>
                <div className="grid grid-cols-2 gap-3 mt-6">
                  <button onClick={() => setOverlay(null)} className="h-[52px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">CANCEL</button>
                  <button onClick={doResetPin} disabled={saving} className="h-[52px] rounded-xl bg-amber-500 text-zinc-950 font-display text-[14px] tracking-wider hover:bg-amber-400 disabled:opacity-50">GENERATE</button>
                </div>
              </>}
              {overlay === 'showPin' && <>
                <div className="text-[12px] uppercase tracking-[0.22em] text-emerald-400">New PIN set</div>
                <div className="font-display text-[28px] tracking-tight mt-1">Give this PIN to {user.name}</div>
                <div className="bg-zinc-950 border border-zinc-800 rounded-xl p-6 mt-4 text-center">
                  <div className="font-display text-[64px] tabular-nums tracking-[0.3em] text-zinc-100">{newPin}</div>
                </div>
                <button onClick={() => setOverlay(null)} className="w-full h-[52px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700 mt-4">DONE</button>
              </>}
              {overlay === 'edit' && <>
                <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-400">Edit user</div>
                <div className="font-display text-[28px] tracking-tight mt-1 mb-4">{user.name}</div>
                <div className="space-y-3">
                  <div>
                    <div className="text-[11px] uppercase tracking-wider text-zinc-500 mb-1">Name</div>
                    <input value={editData.name} onChange={e => setEditData(d => ({...d, name: e.target.value}))}
                      className="w-full h-10 px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[15px] outline-none focus:border-zinc-600" />
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    {["worker","manager","admin"].map(r => (
                      <button key={r} onClick={() => setEditData(d => ({...d, role: r}))}
                        className={`h-10 rounded-lg font-display text-[13px] tracking-wider uppercase ${editData.role===r ? "bg-zinc-100 text-zinc-950" : "bg-zinc-950 border border-zinc-800 text-zinc-400 hover:bg-zinc-800"}`}>{r}</button>
                    ))}
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    {["Day","Night"].map(s => (
                      <button key={s} onClick={() => setEditData(d => ({...d, shift: s}))}
                        className={`h-10 rounded-lg font-display text-[13px] tracking-wider ${editData.shift===s ? "bg-zinc-100 text-zinc-950" : "bg-zinc-950 border border-zinc-800 text-zinc-400 hover:bg-zinc-800"}`}>{s}</button>
                    ))}
                  </div>
                  <div>
                    <div className="text-[11px] uppercase tracking-wider text-zinc-500 mb-1">Email</div>
                    <input type="email" value={editData.email} onChange={e => setEditData(d => ({...d, email: e.target.value}))}
                      placeholder="name@example.com"
                      className="w-full h-10 px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[15px] outline-none focus:border-zinc-600" />
                  </div>
                  <div>
                    <div className="text-[11px] uppercase tracking-wider text-zinc-500 mb-1">Phone</div>
                    <input type="tel" value={editData.phone} onChange={e => setEditData(d => ({...d, phone: e.target.value}))}
                      placeholder="+1 555 000 0000"
                      className="w-full h-10 px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[15px] outline-none focus:border-zinc-600" />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-3 mt-5">
                  <button onClick={() => setOverlay(null)} className="h-[52px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">CANCEL</button>
                  <button onClick={saveEdit} disabled={saving} className="h-[52px] rounded-xl bg-emerald-500 text-zinc-950 font-display text-[14px] tracking-wider hover:bg-emerald-400 disabled:opacity-50">{saving ? "SAVING…" : "SAVE"}</button>
                </div>
              </>}
            </div>
          </div>
        )}

        <style>{`@keyframes slideInRight { from { transform: translateX(40px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }`}</style>
      </div>
    </div>
  );
}

function SmallStat({ label, value, color = "text-zinc-100" }) {
  return (
    <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-3">
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[28px] tabular-nums leading-none mt-1 ${color}`}>{value}</div>
    </div>
  );
}

function AddUserModal({ onClose }) {
  const [name, setName] = useStateSet("");
  const [role, setRole] = useStateSet("worker");
  const [shift, setShift] = useStateSet("Day");
  const [email, setEmail] = useStateSet("");
  const [phone, setPhone] = useStateSet("");
  const [pin, setPin] = useStateSet("");
  const [pinConfirm, setPinConfirm] = useStateSet("");
  const [saving, setSaving] = useStateSet(false);
  const [err, setErr] = useStateSet("");

  async function create() {
    if (!name.trim()) return setErr("Name is required.");
    if (!pin || pin.length !== 4 || !/^\d{4}$/.test(pin)) return setErr("PIN must be exactly 4 digits.");
    if (pin !== pinConfirm) return setErr("PINs don't match.");
    setSaving(true); setErr("");
    try {
      const res = await fetch('/api/users', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), role, shift, email, phone, pin }),
      });
      if (!res.ok) { const e = await res.json(); setErr(e.error || 'Failed'); setSaving(false); return; }
      onClose();
    } catch { setErr("Network error"); setSaving(false); }
  }

  return (
    <div className="fixed inset-0 z-50 bg-zinc-950/85 backdrop-blur-sm flex items-center justify-center p-8">
      <div className="w-full max-w-[640px] bg-zinc-900 border border-zinc-800 rounded-2xl p-8 overflow-y-auto max-h-[90vh]">
        <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Add user</div>
        <div className="font-display text-[36px] tracking-tight mt-1">New team member</div>

        <div className="mt-6 space-y-4">
          <div>
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Name *</div>
            <input value={name} onChange={e => setName(e.target.value)} placeholder="First Last"
              className="w-full h-[52px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[18px] outline-none focus:border-zinc-600" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Email</div>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="worker@example.com"
                className="w-full h-[44px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[15px] outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Phone</div>
              <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="+1 555 000 0000"
                className="w-full h-[44px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[15px] outline-none focus:border-zinc-600" />
            </div>
          </div>
          <div>
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Role</div>
            <div className="grid grid-cols-3 gap-2">
              {["worker", "manager", "admin"].map((r) => (
                <button key={r} onClick={() => setRole(r)}
                  className={`h-[44px] rounded-lg font-display text-[14px] tracking-wider uppercase transition ${
                    role === r ? "bg-zinc-100 text-zinc-950" : "bg-zinc-950 border border-zinc-800 text-zinc-400 hover:bg-zinc-800"
                  }`}>{r}</button>
              ))}
            </div>
          </div>
          <div>
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Shift</div>
            <div className="grid grid-cols-2 gap-2">
              {["Day", "Night"].map((s) => (
                <button key={s} onClick={() => setShift(s)}
                  className={`h-[44px] rounded-lg font-display text-[14px] tracking-wider uppercase transition ${
                    shift === s ? "bg-zinc-100 text-zinc-950" : "bg-zinc-950 border border-zinc-800 text-zinc-400 hover:bg-zinc-800"
                  }`}>{s}</button>
              ))}
            </div>
          </div>
          <div>
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">PIN * (4 digits)</div>
            <div className="grid grid-cols-2 gap-3">
              <input type="password" inputMode="numeric" maxLength={4} value={pin} onChange={e => setPin(e.target.value.replace(/\D/g,'').slice(0,4))}
                placeholder="••••"
                className="h-[44px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[20px] tracking-[0.5em] font-mono outline-none focus:border-zinc-600 text-center" />
              <input type="password" inputMode="numeric" maxLength={4} value={pinConfirm} onChange={e => setPinConfirm(e.target.value.replace(/\D/g,'').slice(0,4))}
                placeholder="Confirm"
                className="h-[44px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[20px] tracking-[0.5em] font-mono outline-none focus:border-zinc-600 text-center" />
            </div>
          </div>
          {err && <div className="text-red-400 text-[13px]">{err}</div>}
        </div>

        <div className="grid grid-cols-2 gap-3 mt-6">
          <button onClick={onClose}
            className="h-[56px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[16px] tracking-wider hover:bg-zinc-700">
            CANCEL
          </button>
          <button onClick={create} disabled={saving}
            className="h-[56px] rounded-xl bg-emerald-500 text-zinc-950 font-display text-[16px] tracking-wider hover:bg-emerald-400 disabled:opacity-50">
            {saving ? "SAVING…" : "CREATE USER"}
          </button>
        </div>
      </div>
    </div>
  );
}

function BOMsAdmin() {
  const kits = window.INVENTORY.filter((i) => i.type === "kit");
  const [open, setOpen] = useStateSet(kits[0]?.sku);

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-4">
        <div className="flex items-center justify-between">
          <div className="font-display text-[36px] tracking-tight">Bills of Materials</div>
          <button className="h-12 px-5 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">
            IMPORT BOM CSV
          </button>
        </div>
        <div className="space-y-2">
          {kits.map((k) => {
            const isOpen = open === k.sku;
            return (
              <div key={k.sku} className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
                <button onClick={() => setOpen(isOpen ? null : k.sku)}
                  className="w-full flex items-center gap-3 px-5 py-4 hover:bg-zinc-800/50 text-left">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
                    style={{ transform: isOpen ? "rotate(90deg)" : "rotate(0)", transition: "transform 0.15s" }}>
                    <polyline points="9 18 15 12 9 6"/>
                  </svg>
                  <div className="font-mono text-[13px] text-zinc-400">{k.sku}</div>
                  <div className="text-[17px] font-medium">{k.name}</div>
                  <div className="ml-auto text-[12px] text-zinc-500 uppercase tracking-wider">9 components</div>
                </button>
                {isOpen && (
                  <div className="border-t border-zinc-800 divide-y divide-zinc-800/60">
                    {(Array.isArray(window.KIT_STEPS) ? window.KIT_STEPS : (window.KIT_STEPS[k.sku] || [])).map((s) => (
                      <div key={s.sku} className="grid grid-cols-[2fr_3fr_1fr_120px] items-center px-5 py-2.5 text-[14px]">
                        <div className="font-mono text-zinc-300">{s.sku}</div>
                        <div>{s.part}</div>
                        <div className="tabular-nums text-zinc-400">×{s.qty} per unit</div>
                        <div className="flex gap-1 justify-end">
                          <button className="h-8 w-8 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-zinc-700 flex items-center justify-center">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 20h9M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4z"/></svg>
                          </button>
                          <button className="h-8 w-8 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-red-500/20 hover:text-red-300 flex items-center justify-center">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                          </button>
                        </div>
                      </div>
                    ))}
                    <button className="w-full px-5 py-3 text-[14px] text-emerald-400 hover:bg-emerald-500/5 text-left">+ Add component</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function PartsTypesAdmin() {
  const { useState: useSt, useEffect: useEf } = React;
  const [types, setTypes] = useSt([]);
  const [parts, setParts] = useSt([]);
  const [newType, setNewType] = useSt('');
  const [renaming, setRenaming] = useSt(null); // { type, value }
  const [expandedType, setExpandedType] = useSt(null);
  const [changingPart, setChangingPart] = useSt(null); // sku
  const [saving, setSaving] = useSt(false);

  async function load() {
    const [t, p] = await Promise.all([
      fetch('/api/parts/types').then(r => r.json()),
      fetch('/api/parts').then(r => r.json()),
    ]);
    setTypes(t);
    setParts(p);
  }

  useEf(() => { load(); }, []);

  async function addType() {
    const v = newType.trim();
    if (!v) return;
    await fetch('/api/parts/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: v }) });
    setNewType('');
    load();
    window.gpsToast && window.gpsToast(`Type "${v}" added`);
  }

  async function renameType(from, to) {
    if (!to.trim() || to.trim() === from) { setRenaming(null); return; }
    setSaving(true);
    await fetch('/api/parts/retype', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ from, to: to.trim() }) });
    setRenaming(null);
    setSaving(false);
    load();
    window.gpsToast && window.gpsToast(`Renamed "${from}" → "${to.trim()}"`);
  }

  async function changePartType(sku, newT) {
    await fetch(`/api/parts/${sku}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...parts.find(p => p.sku === sku), type: newT }) });
    setChangingPart(null);
    load();
    window.gpsToast && window.gpsToast('Part type updated');
  }

  const typeNames = types.map(t => t.type);

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[900px] mx-auto space-y-6">
        <div className="flex items-center justify-between">
          <div className="font-display text-[36px] tracking-tight">Parts & Types</div>
        </div>

        {/* Add new type */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
          <div className="text-[13px] uppercase tracking-wider text-zinc-500 mb-3">Add New Type</div>
          <div className="flex gap-2">
            <input value={newType} onChange={e => setNewType(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addType()}
              placeholder="e.g. oem, machined, seal-kit…"
              className="flex-1 h-10 px-3 bg-zinc-800 border border-zinc-700 rounded-lg text-[14px] text-zinc-100 outline-none focus:border-zinc-500" />
            <button onClick={addType}
              className="h-10 px-5 rounded-lg font-display text-[14px] tracking-wider text-white"
              style={{ background: window.GPS_RED }}>ADD TYPE</button>
          </div>
        </div>

        {/* Types list */}
        <div className="space-y-2">
          {types.map(({ type, count }) => {
            const isExpanded = expandedType === type;
            const typeParts = parts.filter(p => p.type === type);
            const isRenaming = renaming?.type === type;

            return (
              <div key={type} className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
                <div className="flex items-center gap-3 px-5 py-3">
                  {/* Expand toggle */}
                  <button onClick={() => setExpandedType(isExpanded ? null : type)}
                    className="text-zinc-500 hover:text-zinc-300">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
                      style={{ transform: isExpanded ? 'rotate(90deg)' : 'rotate(0)', transition: 'transform .15s' }}>
                      <polyline points="9 18 15 12 9 6"/>
                    </svg>
                  </button>

                  {/* Type name / rename field */}
                  {isRenaming ? (
                    <input autoFocus value={renaming.value}
                      onChange={e => setRenaming({ ...renaming, value: e.target.value })}
                      onKeyDown={e => { if (e.key === 'Enter') renameType(type, renaming.value); if (e.key === 'Escape') setRenaming(null); }}
                      className="flex-1 h-8 px-2 bg-zinc-800 border border-zinc-600 rounded text-[14px] font-mono outline-none focus:border-zinc-400" />
                  ) : (
                    <span className="flex-1 font-mono text-[15px]">{type}</span>
                  )}

                  <span className="text-[12px] text-zinc-500">{count} part{count !== 1 ? 's' : ''}</span>

                  {isRenaming ? (
                    <div className="flex gap-1">
                      <button onClick={() => renameType(type, renaming.value)} disabled={saving}
                        className="h-8 px-3 rounded bg-emerald-600 text-white text-[12px] font-medium hover:bg-emerald-500">SAVE</button>
                      <button onClick={() => setRenaming(null)}
                        className="h-8 px-3 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 text-[12px] hover:bg-zinc-700">CANCEL</button>
                    </div>
                  ) : (
                    <button onClick={() => setRenaming({ type, value: type })}
                      className="h-8 px-3 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 text-[12px] hover:bg-zinc-700">RENAME</button>
                  )}
                </div>

                {/* Parts under this type */}
                {isExpanded && (
                  <div className="border-t border-zinc-800 divide-y divide-zinc-800/50">
                    {typeParts.length === 0 && (
                      <div className="px-5 py-3 text-[13px] text-zinc-600 italic">No parts with this type yet</div>
                    )}
                    {typeParts.map(p => (
                      <div key={p.sku} className="flex items-center gap-3 px-5 py-2.5">
                        <span className="font-mono text-[12px] text-zinc-400 w-[200px] shrink-0">{p.sku}</span>
                        <span className="flex-1 text-[14px]">{p.name}</span>
                        {changingPart === p.sku ? (
                          <div className="flex gap-1 items-center">
                            <select defaultValue={p.type}
                              onChange={e => changePartType(p.sku, e.target.value)}
                              className="h-8 px-2 bg-zinc-800 border border-zinc-600 rounded text-[13px] text-zinc-100 outline-none">
                              {typeNames.map(t => <option key={t} value={t}>{t}</option>)}
                              <option value="__custom__">+ custom…</option>
                            </select>
                            <button onClick={() => setChangingPart(null)}
                              className="h-8 px-2 rounded bg-zinc-800 border border-zinc-700 text-zinc-400 text-[12px] hover:bg-zinc-700">✕</button>
                          </div>
                        ) : (
                          <button onClick={() => setChangingPart(p.sku)}
                            className="h-7 px-2.5 rounded bg-zinc-800 border border-zinc-700 text-zinc-400 text-[11px] hover:bg-zinc-700 hover:text-zinc-200 font-mono">
                            {p.type}
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function IntegrationsAdmin() {
  const { useState: useStateInt, useEffect: useEffectInt } = React;
  const [loading, setLoading] = useStateInt(true);

  // Shopify
  const [shopifyDomain, setShopifyDomain] = useStateInt("");
  const [shopifyToken, setShopifyToken] = useStateInt("");
  const [shopifyResult, setShopifyResult] = useStateInt(null);
  const [shopifyTesting, setShopifyTesting] = useStateInt(false);
  const [shopifyAppUrl, setShopifyAppUrl] = useStateInt("");
  const [webhookSecret, setWebhookSecret] = useStateInt("");
  const [webhookRegistering, setWebhookRegistering] = useStateInt(false);
  const [webhookResult, setWebhookResult] = useStateInt(null);

  // ShipStation
  const [ssKey, setSsKey] = useStateInt("");
  const [ssSecret, setSsSecret] = useStateInt("");
  const [ssStoreId, setSsStoreId] = useStateInt("");
  const [ssReturnAddr, setSsReturnAddr] = useStateInt("");
  const [ssResult, setSsResult] = useStateInt(null);
  const [ssTesting, setSsTesting] = useStateInt(false);

  // Digest
  const [digestTime, setDigestTime] = useStateInt(window.NOTIFICATION_CONFIG?.adminDigestTime || "08:00");
  const [digestEmail, setDigestEmail] = useStateInt(window.NOTIFICATION_CONFIG?.adminDigestRecipient || "");

  // Inventory check
  const [invCheckDays, setInvCheckDays] = useStateInt("7");
  const [invCheckLastRun, setInvCheckLastRun] = useStateInt("");
  const [invCheckRunning, setInvCheckRunning] = useStateInt(false);
  const [invCheckResult, setInvCheckResult] = useStateInt(null);

  useEffectInt(() => {
    fetch("/api/settings/flat")
      .then(r => r.json())
      .then(s => {
        setShopifyDomain(s.shopify_store_domain || "");
        setShopifyToken(s.shopify_access_token || "");
        setShopifyAppUrl(s.shopify_app_url || "");
        setWebhookSecret(s.shopify_webhook_secret || "");
        setSsKey(s.shipstation_api_key || "");
        setSsSecret(s.shipstation_api_secret || "");
        setSsStoreId(s.shipstation_store_id || "");
        setSsReturnAddr(s.shipstation_return_addr || "");
        setDigestTime(s.admin_digest_time || "08:00");
        setDigestEmail(s.admin_digest_email || "");
        setInvCheckDays(s.inventory_check_interval_days || "7");
        setInvCheckLastRun(s.inventory_check_last_run || "");
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  async function saveSettings(patch) {
    await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch) });
  }

  async function saveShopify() {
    await saveSettings({ shopify_store_domain: shopifyDomain, shopify_access_token: shopifyToken });
    window.gpsToast && window.gpsToast({ message: "Shopify credentials saved", tone: "ok" });
  }

  async function testShopify() {
    await saveShopify();
    setShopifyTesting(true);
    setShopifyResult(null);
    try {
      const r = await fetch("/api/shopify/sync", { method: "POST" });
      const d = await r.json();
      if (r.ok) setShopifyResult({ ok: true, msg: `Connected · ${d.orders_pulled} open orders pulled` });
      else setShopifyResult({ ok: false, msg: d.error || "Connection failed" });
    } catch (e) {
      setShopifyResult({ ok: false, msg: e.message });
    }
    setShopifyTesting(false);
  }

  async function registerWebhook() {
    if (!shopifyAppUrl) return;
    await saveSettings({ shopify_store_domain: shopifyDomain, shopify_access_token: shopifyToken, shopify_app_url: shopifyAppUrl });
    setWebhookRegistering(true);
    setWebhookResult(null);
    try {
      const r = await fetch("/api/shopify/webhook/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ app_url: shopifyAppUrl }),
      });
      const d = await r.json();
      if (r.ok) {
        setWebhookResult({ ok: true, msg: `Registered · ID ${d.webhook?.id} · Listening at ${d.webhook_url}` });
      } else {
        setWebhookResult({ ok: false, msg: d.error || "Registration failed" });
      }
    } catch (e) {
      setWebhookResult({ ok: false, msg: e.message });
    }
    setWebhookRegistering(false);
  }

  async function saveShipStation() {
    await saveSettings({
      shipstation_api_key: ssKey, shipstation_api_secret: ssSecret,
      shipstation_store_id: ssStoreId, shipstation_return_addr: ssReturnAddr,
    });
    window.gpsToast && window.gpsToast({ message: "ShipStation credentials saved", tone: "ok" });
  }

  async function testShipStation() {
    await saveShipStation();
    setSsTesting(true);
    setSsResult(null);
    try {
      const r = await fetch("/api/shipstation/test", { method: "POST" });
      const d = await r.json();
      if (r.ok) setSsResult({ ok: true, msg: `Connected · ${d.carriers?.length || 0} carriers available` });
      else setSsResult({ ok: false, msg: d.error || "Connection failed" });
    } catch (e) {
      setSsResult({ ok: false, msg: e.message });
    }
    setSsTesting(false);
  }

  async function saveDigest() {
    await saveSettings({ admin_digest_time: digestTime, admin_digest_email: digestEmail });
    if (window.NOTIFICATION_CONFIG) {
      window.NOTIFICATION_CONFIG.adminDigestTime = digestTime;
      window.NOTIFICATION_CONFIG.adminDigestRecipient = digestEmail;
    }
    window.gpsToast && window.gpsToast({ message: "Digest schedule saved", tone: "ok" });
  }

  async function saveInvCheckSchedule() {
    await saveSettings({ inventory_check_interval_days: invCheckDays });
    window.gpsToast && window.gpsToast({ message: "Inventory check schedule saved", tone: "ok" });
  }

  async function runInvCheckNow() {
    setInvCheckRunning(true);
    setInvCheckResult(null);
    try {
      const r = await fetch("/api/inventory/check", { method: "POST" });
      const d = await r.json();
      setInvCheckLastRun(d.checked_at || new Date().toISOString());
      setInvCheckResult({ ok: true, low: d.low_stock || [], msg: d.low_stock?.length > 0 ? `${d.low_stock.length} item(s) below par` : "All items at or above par" });
    } catch (e) {
      setInvCheckResult({ ok: false, msg: e.message });
    }
    setInvCheckRunning(false);
  }

  if (loading) return <div className="flex-1 flex items-center justify-center text-zinc-500">Loading…</div>;

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[900px] mx-auto space-y-4">
        <div className="font-display text-[36px] tracking-tight mb-3">Integrations</div>

        {/* Shopify */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-6 space-y-4">
          <div className="flex items-center gap-3">
            <div className={`h-3 w-3 rounded-full ${shopifyDomain && shopifyToken ? (shopifyResult?.ok === false ? "bg-red-500" : "bg-emerald-500") : "bg-zinc-600"}`} />
            <div className="font-display text-[22px] tracking-wider">SHOPIFY</div>
            {shopifyDomain && <span className="font-mono text-[13px] text-zinc-400">{shopifyDomain}</span>}
          </div>
          <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-4 text-[13px] text-zinc-400 space-y-1 leading-relaxed">
            <div className="text-zinc-300 font-semibold mb-2">How to get your credentials:</div>
            <div>1. Shopify Admin → <span className="text-zinc-200">Settings → Apps and sales channels → Develop apps</span></div>
            <div>2. Click <span className="text-zinc-200">Create an app</span> → name it "GPS boxd"</div>
            <div>3. Go to <span className="text-zinc-200">Configuration → Admin API scopes</span> → enable <span className="font-mono text-zinc-300">read_orders, write_orders, read_inventory, write_inventory</span></div>
            <div>4. Click <span className="text-zinc-200">Install app</span> → copy the <span className="font-mono text-zinc-300">Admin API access token</span> (shown once — save it)</div>
            <div>5. Your store domain is your Shopify URL without <span className="font-mono text-zinc-300">https://</span> — e.g. <span className="font-mono text-zinc-300">yourstore.myshopify.com</span></div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">Store domain</div>
              <input value={shopifyDomain} onChange={e => setShopifyDomain(e.target.value)}
                placeholder="yourstore.myshopify.com"
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">Access token</div>
              <input value={shopifyToken} onChange={e => setShopifyToken(e.target.value)}
                type="password" placeholder="shpat_…"
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
            </div>
          </div>
          {shopifyResult && (
            <div className={`text-[13px] px-3 py-2 rounded-lg border font-mono ${shopifyResult.ok ? "text-emerald-300 bg-emerald-500/10 border-emerald-500/30" : "text-red-300 bg-red-500/10 border-red-500/30"}`}>
              {shopifyResult.ok ? "✓ " : "✗ "}{shopifyResult.msg}
            </div>
          )}
          <div className="flex gap-2 justify-end">
            <button onClick={saveShopify}
              className="h-10 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[13px] font-display tracking-wider hover:bg-zinc-700">
              SAVE
            </button>
            <button onClick={testShopify} disabled={shopifyTesting || !shopifyDomain || !shopifyToken}
              className="h-10 px-5 rounded-lg bg-emerald-500 text-zinc-950 text-[13px] font-display tracking-wider hover:bg-emerald-400 disabled:opacity-40 disabled:cursor-not-allowed">
              {shopifyTesting ? "TESTING…" : "TEST CONNECTION"}
            </button>
          </div>
          <div className="border-t border-zinc-800 pt-4 space-y-3">
            <div className="text-[13px] font-semibold text-zinc-300 uppercase tracking-wider">Webhook</div>
            <div className="text-[12px] text-zinc-500">GPS boxd app URL (must be publicly accessible — e.g. your Railway deploy URL). Shopify will POST paid orders to this address automatically.</div>
            <div className="flex gap-2 items-end">
              <div className="flex-1">
                <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">App URL</div>
                <input value={shopifyAppUrl} onChange={e => setShopifyAppUrl(e.target.value)}
                  placeholder="https://your-app.railway.app"
                  className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
              </div>
              <button onClick={registerWebhook} disabled={webhookRegistering || !shopifyAppUrl || !shopifyDomain || !shopifyToken}
                className="h-[48px] px-5 rounded-lg bg-blue-500 text-white text-[13px] font-display tracking-wider hover:bg-blue-400 disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap">
                {webhookRegistering ? "REGISTERING…" : "REGISTER WEBHOOK"}
              </button>
            </div>
            {webhookResult && (
              <div className={`text-[13px] px-3 py-2 rounded-lg border font-mono ${webhookResult.ok ? "text-emerald-300 bg-emerald-500/10 border-emerald-500/30" : "text-red-300 bg-red-500/10 border-red-500/30"}`}>
                {webhookResult.ok ? "✓ " : "✗ "}{webhookResult.msg}
              </div>
            )}
            {webhookSecret && (
              <div className="flex items-center gap-2">
                <div className="text-[12px] uppercase tracking-wider text-zinc-400">Webhook secret</div>
                <div className="font-mono text-[12px] text-zinc-500 bg-zinc-950 border border-zinc-800 rounded px-2 py-1 flex-1 truncate">{webhookSecret}</div>
              </div>
            )}
          </div>
        </div>

        {/* ShipStation */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-6 space-y-4">
          <div className="flex items-center gap-3">
            <div className={`h-3 w-3 rounded-full ${ssKey && ssSecret ? (ssResult?.ok === false ? "bg-red-500" : "bg-emerald-500") : "bg-zinc-600"}`} />
            <div className="font-display text-[22px] tracking-wider">SHIPSTATION</div>
          </div>
          <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-4 text-[13px] text-zinc-400 space-y-1 leading-relaxed">
            <div className="text-zinc-300 font-semibold mb-2">How to get your credentials:</div>
            <div>1. ShipStation → <span className="text-zinc-200">Account Settings (gear icon) → API Settings</span></div>
            <div>2. Click <span className="text-zinc-200">Generate API Keys</span> → copy both the key and secret now (secret won't show again)</div>
            <div>3. Store ID is optional — find it in ShipStation under <span className="text-zinc-200">Account Settings → Stores</span> if you need to filter by store</div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">API key</div>
              <input value={ssKey} onChange={e => setSsKey(e.target.value)}
                placeholder="API key"
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">API secret</div>
              <input value={ssSecret} onChange={e => setSsSecret(e.target.value)}
                type="password" placeholder="API secret"
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">Store ID <span className="normal-case text-zinc-600">(optional)</span></div>
              <input value={ssStoreId} onChange={e => setSsStoreId(e.target.value)}
                placeholder="12345"
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-1">Return address <span className="normal-case text-zinc-600">(optional)</span></div>
              <input value={ssReturnAddr} onChange={e => setSsReturnAddr(e.target.value)}
                placeholder="123 Main St, City, NC 28000"
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] font-mono outline-none focus:border-zinc-600" />
            </div>
          </div>
          {ssResult && (
            <div className={`text-[13px] px-3 py-2 rounded-lg border font-mono ${ssResult.ok ? "text-emerald-300 bg-emerald-500/10 border-emerald-500/30" : "text-red-300 bg-red-500/10 border-red-500/30"}`}>
              {ssResult.ok ? "✓ " : "✗ "}{ssResult.msg}
            </div>
          )}
          <div className="flex gap-2 justify-end">
            <button onClick={saveShipStation}
              className="h-10 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[13px] font-display tracking-wider hover:bg-zinc-700">
              SAVE
            </button>
            <button onClick={testShipStation} disabled={ssTesting || !ssKey || !ssSecret}
              className="h-10 px-5 rounded-lg bg-emerald-500 text-zinc-950 text-[13px] font-display tracking-wider hover:bg-emerald-400 disabled:opacity-40 disabled:cursor-not-allowed">
              {ssTesting ? "TESTING…" : "TEST CONNECTION"}
            </button>
          </div>
        </div>

        {/* Daily admin digest */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-amber-500/15 border border-amber-500/30 flex items-center justify-center text-amber-300 text-[18px]">📧</div>
            <div className="flex-1">
              <div className="font-display text-[22px] tracking-wider">DAILY ADMIN DIGEST</div>
              <div className="text-[13px] text-zinc-400 mt-0.5">PO requests batch into one daily email instead of pinging admin per request.</div>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3 mt-5">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Send time</div>
              <input type="time" value={digestTime} onChange={e => setDigestTime(e.target.value)}
                className="w-full h-[52px] px-4 bg-zinc-950 border border-zinc-800 rounded-lg text-[16px] font-mono outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Recipient email</div>
              <input type="email" value={digestEmail} onChange={e => setDigestEmail(e.target.value)}
                className="w-full h-[52px] px-4 bg-zinc-950 border border-zinc-800 rounded-lg text-[15px] font-mono outline-none focus:border-zinc-600" />
            </div>
          </div>
          <div className="flex justify-end mt-3">
            <button onClick={saveDigest}
              className="h-10 px-5 rounded-lg bg-emerald-500 text-zinc-950 text-[13px] font-display tracking-wider hover:bg-emerald-400">
              SAVE
            </button>
          </div>
        </div>

        {/* Inventory Check */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5 space-y-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-blue-500/15 border border-blue-500/30 flex items-center justify-center text-blue-300 text-[18px]">📦</div>
            <div className="flex-1">
              <div className="font-display text-[22px] tracking-wider">INVENTORY CHECK</div>
              <div className="text-[13px] text-zinc-400 mt-0.5">Automatically flags items below par level on a schedule.</div>
            </div>
          </div>
          <div className="flex items-end gap-3">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Check every</div>
              <select value={invCheckDays} onChange={e => setInvCheckDays(e.target.value)}
                className="h-[52px] px-4 bg-zinc-950 border border-zinc-800 rounded-lg text-[15px] outline-none focus:border-zinc-600">
                <option value="1">1 day</option>
                <option value="3">3 days</option>
                <option value="7">1 week</option>
                <option value="14">2 weeks</option>
                <option value="30">1 month</option>
              </select>
            </div>
            <button onClick={saveInvCheckSchedule}
              className="h-[52px] px-5 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[13px] font-display tracking-wider hover:bg-zinc-700">
              SAVE
            </button>
            <button onClick={runInvCheckNow} disabled={invCheckRunning}
              className="h-[52px] px-5 rounded-lg bg-blue-500 text-white text-[13px] font-display tracking-wider hover:bg-blue-400 disabled:opacity-40">
              {invCheckRunning ? "CHECKING…" : "RUN NOW"}
            </button>
          </div>
          {invCheckLastRun && (
            <div className="text-[12px] text-zinc-500">Last run: {new Date(invCheckLastRun).toLocaleString()}</div>
          )}
          {invCheckResult && (
            <div className={`text-[13px] px-3 py-2 rounded-lg border font-mono ${invCheckResult.ok ? (invCheckResult.low?.length > 0 ? "text-amber-300 bg-amber-500/10 border-amber-500/30" : "text-emerald-300 bg-emerald-500/10 border-emerald-500/30") : "text-red-300 bg-red-500/10 border-red-500/30"}`}>
              {invCheckResult.ok ? (invCheckResult.low?.length > 0 ? "⚠ " : "✓ ") : "✗ "}{invCheckResult.msg}
              {invCheckResult.low?.length > 0 && (
                <div className="mt-2 space-y-0.5">
                  {invCheckResult.low.map(i => (
                    <div key={i.sku} className="text-[12px]">{i.sku} — {i.qty} on hand / {i.par} par</div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

      </div>
    </div>
  );
}

function StationAdmin() {
  const [stations, setStations] = useStateSet(window.STATIONS || []);
  const [editingId, setEditingId] = useStateSet(null);
  const [editName, setEditName] = useStateSet("");
  const [addingName, setAddingName] = useStateSet("");
  const [timeout, setTimeoutVal] = useStateSet(5);
  const [confirmThreshold, setConfirmThreshold] = useStateSet(10);
  const [confirmDelete, setConfirmDelete] = useStateSet(null);

  function commitEdits(next) {
    setStations(next);
    if (window.STATIONS) {
      window.STATIONS.length = 0;
      next.forEach((s) => window.STATIONS.push(s));
      const active = next.find((s) => s.active) || next[0];
      if (active && window.STATION) {
        window.STATION.name = active.name;
        window.STATION.id = active.id;
      }
    }
  }

  function startEdit(s) { setEditingId(s.id); setEditName(s.name); }
  function saveEdit(id) {
    if (!editName.trim()) { setEditingId(null); return; }
    const next = stations.map((s) => s.id === id ? { ...s, name: editName.trim() } : s);
    commitEdits(next);
    setEditingId(null);
    window.gpsToast && window.gpsToast({ message: `Station renamed to "${editName.trim()}"`, tone: "ok" });
  }
  function addStation() {
    if (!addingName.trim()) return;
    const id = `st-${Date.now().toString(36)}`;
    const next = [...stations, { id, name: addingName.trim(), active: false }];
    commitEdits(next);
    setAddingName("");
    window.gpsToast && window.gpsToast({
      message: `Added "${addingName.trim()}" · pin a terminal to assign it`,
      tone: "ok",
      undo: () => commitEdits(stations),
    });
  }
  function removeStation(id) {
    const station = stations.find((s) => s.id === id);
    const next = stations.filter((s) => s.id !== id);
    // ensure at least one active
    if (next.length && !next.some((s) => s.active)) next[0].active = true;
    commitEdits(next);
    setConfirmDelete(null);
    window.gpsToast && window.gpsToast({
      message: `Removed "${station.name}"`,
      tone: "warn",
      undo: () => commitEdits(stations),
    });
  }
  function makeActive(id) {
    const next = stations.map((s) => ({ ...s, active: s.id === id, terminal: s.id === id ? "this terminal" : undefined }));
    commitEdits(next);
    window.gpsToast && window.gpsToast({ message: `Pinned to this terminal`, tone: "ok" });
  }

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[820px] mx-auto space-y-6">
        <div className="font-display text-[36px] tracking-tight">Stations</div>

        {/* Station list */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
          <div className="px-5 py-4 border-b border-zinc-800 flex items-center justify-between">
            <div>
              <div className="font-display text-[22px] tracking-wider text-zinc-300">STATIONS · {stations.length}</div>
              <div className="text-[12px] text-zinc-500 mt-0.5">A station is one bay + table the floor app runs on. Each terminal is pinned to one.</div>
            </div>
          </div>
          <div className="divide-y divide-zinc-800/80">
            {stations.map((s) => {
              const isEditing = editingId === s.id;
              return (
                <div key={s.id} className="px-5 py-3 flex items-center gap-3">
                  <div className={`h-2.5 w-2.5 rounded-full ${s.active ? "bg-emerald-500" : "bg-zinc-700"}`} />
                  {isEditing ? (
                    <>
                      <input value={editName} autoFocus
                        onChange={(e) => setEditName(e.target.value)}
                        onKeyDown={(e) => { if (e.key === "Enter") saveEdit(s.id); if (e.key === "Escape") setEditingId(null); }}
                        className="flex-1 h-[44px] px-3 bg-zinc-950 border-2 border-zinc-700 rounded-lg text-[16px] outline-none focus:border-zinc-500" />
                      <button onClick={() => saveEdit(s.id)}
                        className="h-[44px] px-4 rounded-lg bg-emerald-500 text-zinc-950 text-[13px] font-display tracking-wider hover:bg-emerald-400">SAVE</button>
                      <button onClick={() => setEditingId(null)}
                        className="h-[44px] px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-300 text-[13px] uppercase tracking-wider hover:bg-zinc-700">Cancel</button>
                    </>
                  ) : (
                    <>
                      <div className="flex-1 flex items-center gap-2 min-w-0">
                        <div className="font-mono text-[12px] text-zinc-500">{s.id}</div>
                        <div className="text-[17px] truncate">{s.name}</div>
                        {s.active && (
                          <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider border bg-emerald-500/10 text-emerald-300 border-emerald-500/30">
                            ● this terminal
                          </span>
                        )}
                      </div>
                      {!s.active && (
                        <button onClick={() => makeActive(s.id)}
                          className="h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-300 text-[12px] uppercase tracking-wider hover:bg-zinc-700">
                          Pin here
                        </button>
                      )}
                      <button onClick={() => startEdit(s)}
                        className="h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-300 text-[12px] uppercase tracking-wider hover:bg-zinc-700">
                        Rename
                      </button>
                      <button onClick={() => setConfirmDelete(s)}
                        disabled={stations.length === 1}
                        className="h-9 w-9 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-400 hover:bg-red-500/20 hover:text-red-300 disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center"
                        title={stations.length === 1 ? "Can't delete last station" : "Remove"}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                      </button>
                    </>
                  )}
                </div>
              );
            })}
            {/* Add row */}
            <div className="px-5 py-3 flex items-center gap-3 bg-zinc-950/40">
              <div className="h-2.5 w-2.5 rounded-full border border-zinc-700" />
              <input value={addingName}
                onChange={(e) => setAddingName(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") addStation(); }}
                placeholder="Bay 2 · Table 1 …"
                className="flex-1 h-[44px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[15px] outline-none focus:border-zinc-600" />
              <button onClick={addStation} disabled={!addingName.trim()}
                className="h-[44px] px-5 rounded-lg font-display text-[14px] tracking-wider text-zinc-100 hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed"
                style={{ background: window.GPS_RED }}>
                + ADD
              </button>
            </div>
          </div>
        </div>

        {/* Station-wide settings */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-6 space-y-5">
          <div>
            <div className="font-display text-[20px] tracking-wider text-zinc-300">DEFAULTS</div>
            <div className="text-[12px] text-zinc-500">Applied to every station unless overridden.</div>
          </div>
          <div>
            <div className="flex items-center justify-between mb-2">
              <div className="text-[12px] uppercase tracking-wider text-zinc-400">Inactivity timeout</div>
              <div className="font-display text-[20px] tabular-nums">{timeout} min</div>
            </div>
            <input type="range" min="1" max="30" value={timeout} onChange={(e) => setTimeoutVal(parseInt(e.target.value))}
              className="w-full accent-zinc-100" />
          </div>
          <div>
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Qty confirm threshold</div>
            <div className="flex items-center gap-3">
              <input type="number" value={confirmThreshold} onChange={(e) => setConfirmThreshold(parseInt(e.target.value))}
                className="h-[60px] w-[160px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[18px] tabular-nums outline-none focus:border-zinc-600" />
              <span className="text-[14px] text-zinc-500">Show qty input when step qty ≥ this</span>
            </div>
          </div>
          <button onClick={() => window.gpsToast && window.gpsToast({ message: "Defaults saved across all stations", tone: "ok" })}
            className="h-[60px] w-full rounded-xl bg-emerald-500 text-zinc-950 font-display text-[18px] tracking-wider hover:bg-emerald-400">
            SAVE DEFAULTS
          </button>
        </div>
      </div>

      {confirmDelete && (
        <div className="fixed inset-0 z-50 bg-zinc-950/85 backdrop-blur-sm flex items-center justify-center p-8 text-zinc-100">
          <div className="w-full max-w-[520px] bg-zinc-900 border border-zinc-800 rounded-2xl p-7">
            <div className="text-[12px] uppercase tracking-[0.22em] text-red-400">Confirm removal</div>
            <div className="font-display text-[30px] tracking-tight mt-1">Remove "{confirmDelete.name}"?</div>
            <div className="text-[14px] text-zinc-400 mt-3">
              Sessions in flight at this station will keep running. New work can't be started there until you re-add it.
            </div>
            <div className="grid grid-cols-2 gap-3 mt-6">
              <button onClick={() => setConfirmDelete(null)}
                className="h-[56px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[14px] tracking-wider hover:bg-zinc-700">CANCEL</button>
              <button onClick={() => removeStation(confirmDelete.id)}
                className="h-[56px] rounded-xl bg-red-500 text-white font-display text-[14px] tracking-wider hover:bg-red-400">REMOVE</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.SettingsTab = SettingsTab;
