/* ============================================
   SETTINGS — shared layout + Profile / Preferences / Admin
   ============================================ */

const SettingsRow = ({ label, help, children }) => (
  <div className="settings-row">
    <div className="settings-row-label">
      {label}
      {help && <span className="help">{help}</span>}
    </div>
    <div className="settings-row-control">{children}</div>
  </div>
);

const SettingsSection = ({ title, sub, children }) => (
  <div className="settings-section">
    <h2>{title}</h2>
    {sub && <p className="sub">{sub}</p>}
    {children}
  </div>
);

/* ============================================
   PROFILE SETTINGS
   ============================================ */
const ProfileView = ({ currentUser, onUpdateUser }) => {
  const [form, setForm] = React.useState({
    name: currentUser.name,
    short: currentUser.short,
    email: currentUser.email,
    phone: currentUser.phone || '',
    role: currentUser.role,
    department: currentUser.department || 'Digital Marketing',
    bio: currentUser.bio || '',
    timezone: currentUser.timezone || 'Asia/Bangkok (UTC+7)',
    language: currentUser.language || 'th',
    color: currentUser.color,
    twoFA: currentUser.twoFA || false,
  });
  const [saved, setSaved] = React.useState(false);

  const set = (patch) => { setForm(f => ({ ...f, ...patch })); setSaved(false); };

  const save = () => {
    onUpdateUser({ ...currentUser, ...form });
    setSaved(true);
    setTimeout(() => setSaved(false), 2400);
  };

  const COLOR_OPTIONS = ['#6D49F2','#EC4899','#F59E0B','#10B981','#3B82F6','#F97316','#06B6D4','#84CC16','#8B5CF6','#14B8A6','#D946EF','#F43F5E'];

  return (
    <div className="settings">
      <div className="settings-header">
        <Avatar user={{ ...currentUser, color: form.color, name: form.name }} size="xl" />
        <div style={{ flex: 1 }}>
          <h1>Profile</h1>
          <p>Manage your personal information and how others see you.</p>
        </div>
        {saved && (
          <span style={{ fontSize: 12, color: 'var(--c-emerald)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="check" size={14} stroke={3} /> Saved
          </span>
        )}
        <Btn kind="primary" icon="check" onClick={save}>Save changes</Btn>
      </div>

      <SettingsSection title="Photo & identity" sub="What people see on cards, mentions, and comments.">
        <SettingsRow label="Avatar color" help="Auto-generated initials use this color">
          <div className="avatar-picker">
            {COLOR_OPTIONS.map(c => (
              <button
                key={c}
                className={`avatar-picker-swatch${form.color === c ? ' active' : ''}`}
                style={{ background: c }}
                onClick={() => set({ color: c })}
                title={c}
              />
            ))}
          </div>
        </SettingsRow>
        <SettingsRow label="Upload photo" help="JPG or PNG, max 2MB">
          <button className="btn btn-secondary">
            <Icon name="image" size={13} /> Upload
          </button>
          <span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>No photo uploaded — using initials</span>
        </SettingsRow>
        <SettingsRow label="Full name">
          <input type="text" value={form.name} onChange={(e) => set({ name: e.target.value })} />
        </SettingsRow>
        <SettingsRow label="Display name" help="Used in @mentions and comments">
          <input type="text" value={form.short} onChange={(e) => set({ short: e.target.value })} />
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Work info" sub="Visible to your teammates.">
        <SettingsRow label="Job title">
          <input type="text" value={form.role} onChange={(e) => set({ role: e.target.value })} />
        </SettingsRow>
        <SettingsRow label="Department">
          <select value={form.department} onChange={(e) => set({ department: e.target.value })}>
            <option>Digital Marketing</option>
            <option>Design</option>
            <option>Engineering</option>
            <option>Product</option>
            <option>Operations</option>
          </select>
        </SettingsRow>
        <SettingsRow label="About" help="A short bio shown on your team profile">
          <textarea
            rows={3}
            value={form.bio}
            onChange={(e) => set({ bio: e.target.value })}
            placeholder="e.g. UI Designer · loves dark mode and coffee ☕"
          />
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Contact" sub="How teammates and the system reach you.">
        <SettingsRow label="Email">
          <input type="email" value={form.email} onChange={(e) => set({ email: e.target.value })} />
        </SettingsRow>
        <SettingsRow label="Phone">
          <input type="tel" value={form.phone} onChange={(e) => set({ phone: e.target.value })} placeholder="e.g. 081-234-5678" />
        </SettingsRow>
        <SettingsRow label="Time zone">
          <select value={form.timezone} onChange={(e) => set({ timezone: e.target.value })}>
            <option>Asia/Bangkok (UTC+7)</option>
            <option>Asia/Tokyo (UTC+9)</option>
            <option>Asia/Singapore (UTC+8)</option>
            <option>Europe/London (UTC+0)</option>
            <option>America/New_York (UTC-5)</option>
          </select>
        </SettingsRow>
        <SettingsRow label="Language">
          <select value={form.language} onChange={(e) => set({ language: e.target.value })}>
            <option value="th">ไทย (Thai)</option>
            <option value="en">English</option>
          </select>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Security" sub="Protect your account.">
        <SettingsRow label="Password" help="Last changed 3 months ago">
          <Btn kind="secondary" icon="settings">Change password</Btn>
        </SettingsRow>
        <SettingsRow label="Two-factor authentication" help="Require a code in addition to your password">
          <Toggle checked={form.twoFA} onChange={(v) => set({ twoFA: v })} />
          <span style={{ fontSize: 12.5, color: form.twoFA ? 'var(--c-emerald)' : 'var(--text-muted)' }}>
            {form.twoFA ? 'Enabled' : 'Disabled'}
          </span>
        </SettingsRow>
        <SettingsRow label="Active sessions" help="Devices currently signed in">
          <div style={{ fontSize: 13 }}>
            <div>This device · MacBook Pro · Bangkok</div>
            <button className="btn btn-ghost" style={{ marginTop: 4, padding: '4px 8px', fontSize: 12 }}>Sign out other sessions</button>
          </div>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Connected accounts" sub="Link external services for richer integrations.">
        {[
          { name: 'Google Workspace', icon: 'externalLink', connected: true, sub: 'Calendar sync · Drive attachments' },
          { name: 'Slack', icon: 'message', connected: false, sub: 'Get notifications in DM' },
          { name: 'Figma', icon: 'image', connected: false, sub: 'Embed design files' },
        ].map(svc => (
          <div key={svc.name} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '12px 0',
            borderTop: '1px solid var(--border)',
          }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', color: 'var(--text-muted)' }}>
              <Icon name={svc.icon} size={16} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 13.5 }}>{svc.name}</div>
              <div style={{ fontSize: 12, color: 'var(--text-subtle)' }}>{svc.sub}</div>
            </div>
            {svc.connected ? (
              <>
                <span style={{ fontSize: 11.5, color: 'var(--c-emerald)', fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--c-emerald)' }} />
                  Connected
                </span>
                <Btn kind="ghost">Disconnect</Btn>
              </>
            ) : (
              <Btn kind="secondary">Connect</Btn>
            )}
          </div>
        ))}
      </SettingsSection>

      <SettingsSection title="Danger zone">
        <SettingsRow label="Delete account" help="Permanently remove your account and data. This cannot be undone.">
          <Btn kind="danger" icon="trash">Delete account</Btn>
        </SettingsRow>
      </SettingsSection>
    </div>
  );
};

/* ============================================
   PREFERENCES
   ============================================ */
const PreferencesView = ({ tw, setTweak, prefs, onUpdatePrefs }) => {
  const [saved, setSaved] = React.useState(false);
  const setPref = (k, v) => { onUpdatePrefs({ ...prefs, [k]: v }); setSaved(true); setTimeout(() => setSaved(false), 1500); };

  return (
    <div className="settings">
      <div className="settings-header">
        <span style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--brand-50)', color: 'var(--brand-600)', display: 'grid', placeItems: 'center' }}>
          <Icon name="settings" size={20} />
        </span>
        <div style={{ flex: 1 }}>
          <h1>Preferences</h1>
          <p>Customize how Tasker looks and behaves for you.</p>
        </div>
        {saved && (
          <span style={{ fontSize: 12, color: 'var(--c-emerald)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="check" size={14} stroke={3} /> Saved automatically
          </span>
        )}
      </div>

      <SettingsSection title="Appearance" sub="Make Tasker your own.">
        <SettingsRow label="Theme">
          <div style={{ display: 'flex', gap: 6 }}>
            {[
              { v: 'light', label: 'Light', icon: 'sun' },
              { v: 'dark',  label: 'Dark',  icon: 'moon' },
              { v: 'system',label: 'System',icon: 'settings' },
            ].map(opt => (
              <button
                key={opt.v}
                onClick={() => setTweak('theme', opt.v === 'system' ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : opt.v)}
                style={{
                  padding: '8px 14px',
                  borderRadius: 8,
                  background: tw.theme === opt.v || (opt.v !== 'system' && tw.theme === opt.v) ? 'var(--brand-50)' : 'var(--surface-2)',
                  color: tw.theme === opt.v ? 'var(--brand-600)' : 'var(--text)',
                  border: '1.5px solid ' + (tw.theme === opt.v ? 'var(--brand-400)' : 'transparent'),
                  fontSize: 13, fontWeight: 600,
                  cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}
              >
                <Icon name={opt.icon} size={14} /> {opt.label}
              </button>
            ))}
          </div>
        </SettingsRow>
        <SettingsRow label="Brand color" help="Used for buttons, links, and accents">
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { name: 'Violet', palette: ['#F3F0FF','#E5DEFF','#A990FF','#8B6CFF','#6D49F2','#5B36DC'] },
              { name: 'Rose',   palette: ['#FFF1F2','#FFE4E6','#FB7185','#F43F5E','#E11D48','#BE123C'] },
              { name: 'Cyan',   palette: ['#ECFEFF','#CFFAFE','#67E8F9','#22D3EE','#06B6D4','#0891B2'] },
              { name: 'Amber',  palette: ['#FEF3C7','#FDE68A','#FCD34D','#FBBF24','#F59E0B','#D97706'] },
              { name: 'Green',  palette: ['#DCFCE7','#BBF7D0','#86EFAC','#4ADE80','#22C55E','#16A34A'] },
            ].map(opt => {
              const active = tw.brand[4] === opt.palette[4];
              return (
                <button
                  key={opt.name}
                  onClick={() => setTweak('brand', opt.palette)}
                  style={{
                    padding: '6px 10px 6px 6px',
                    borderRadius: 8,
                    background: active ? 'var(--surface-2)' : 'transparent',
                    border: '1.5px solid ' + (active ? 'var(--border-strong)' : 'transparent'),
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    cursor: 'pointer', fontSize: 12.5, fontWeight: 600,
                  }}
                  title={opt.name}
                >
                  <span style={{ width: 20, height: 20, borderRadius: '50%', background: opt.palette[4] }} />
                  {opt.name}
                </button>
              );
            })}
          </div>
        </SettingsRow>
        <SettingsRow label="Density" help="Affects card padding and row heights">
          <select value={prefs.density} onChange={(e) => setPref('density', e.target.value)}>
            <option value="compact">Compact</option>
            <option value="regular">Regular</option>
            <option value="comfy">Comfortable</option>
          </select>
        </SettingsRow>
        <SettingsRow label="Sidebar" help="Start with sidebar collapsed">
          <Toggle checked={prefs.sidebarCollapsedDefault} onChange={(v) => setPref('sidebarCollapsedDefault', v)} />
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Defaults" sub="What you see when you open Tasker.">
        <SettingsRow label="Landing view">
          <select value={prefs.defaultView} onChange={(e) => setPref('defaultView', e.target.value)}>
            <option value="kanban">Board (Kanban)</option>
            <option value="list">List</option>
            <option value="calendar">Calendar</option>
            <option value="dashboard">Dashboard</option>
            <option value="inbox">Inbox</option>
          </select>
        </SettingsRow>
        <SettingsRow label="Landing scope">
          <select value={prefs.defaultScope} onChange={(e) => setPref('defaultScope', e.target.value)}>
            <option value="all">All tasks</option>
            <option value="mine">My tasks only</option>
          </select>
        </SettingsRow>
        <SettingsRow label="List group by">
          <select value={prefs.defaultGroupBy} onChange={(e) => setPref('defaultGroupBy', e.target.value)}>
            <option value="status">Status</option>
            <option value="priority">Priority</option>
            <option value="project">Project</option>
          </select>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Date & time" sub="How dates display across the app.">
        <SettingsRow label="Date format">
          <select value={prefs.dateFormat} onChange={(e) => setPref('dateFormat', e.target.value)}>
            <option value="short">Short — May 19, 2026</option>
            <option value="iso">ISO — 2026-05-19</option>
            <option value="thai">Thai — 19 พ.ค. 2569</option>
          </select>
        </SettingsRow>
        <SettingsRow label="First day of week">
          <select value={prefs.firstDayOfWeek} onChange={(e) => setPref('firstDayOfWeek', e.target.value)}>
            <option value="sun">Sunday</option>
            <option value="mon">Monday</option>
          </select>
        </SettingsRow>
        <SettingsRow label="Time format">
          <select value={prefs.timeFormat} onChange={(e) => setPref('timeFormat', e.target.value)}>
            <option value="12">12-hour (3:30 PM)</option>
            <option value="24">24-hour (15:30)</option>
          </select>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title="Notifications" sub="Choose what to be notified about, and where.">
        <NotifTable prefs={prefs} setPref={setPref} />
        <div style={{ marginTop: 14, padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 8, fontSize: 12.5, color: 'var(--text-muted)' }}>
          <Icon name="bell" size={13} style={{ marginRight: 6, verticalAlign: 'text-bottom' }} />
          Quiet hours: <b style={{ color: 'var(--text)' }}>22:00 — 07:00</b> · No emails during these hours
        </div>
      </SettingsSection>

      <SettingsSection title="Keyboard shortcuts">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px 24px' }}>
          {[
            ['Open search', ['⌘', 'K']],
            ['Create new task', ['C']],
            ['Toggle theme', ['⌘', '⇧', 'D']],
            ['Go to Board', ['G', 'B']],
            ['Go to List', ['G', 'L']],
            ['Go to Calendar', ['G', 'C']],
            ['Go to My Tasks', ['G', 'M']],
            ['Go to Inbox', ['G', 'I']],
            ['Close panel / modal', ['Esc']],
            ['Send comment', ['⌘', 'Enter']],
          ].map(([label, keys], i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', fontSize: 13 }}>
              <span style={{ flex: 1, color: 'var(--text-muted)' }}>{label}</span>
              <span style={{ display: 'inline-flex', gap: 3 }}>
                {keys.map((k, j) => <span key={j} className="kbd-key">{k}</span>)}
              </span>
            </div>
          ))}
        </div>
      </SettingsSection>
    </div>
  );
};

const NotifTable = ({ prefs, setPref }) => {
  const types = [
    { k: 'assigned',   label: 'Assigned to me',           help: 'A task is assigned to you' },
    { k: 'mentioned',  label: 'Mentioned in a comment',   help: 'Someone @mentions you' },
    { k: 'comment',    label: 'Comments on my tasks',     help: 'Replies on tasks where you are assignee/PIC' },
    { k: 'dueSoon',    label: 'Due soon',                 help: 'Task is due in 24 hours' },
    { k: 'overdue',    label: 'Overdue',                  help: 'Task is past its due date' },
    { k: 'statusChange', label: 'Status changes',         help: 'Status changes on tasks I follow' },
    { k: 'weeklyDigest', label: 'Weekly digest',          help: 'Summary email every Monday morning' },
  ];
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr 80px 80px 80px',
        padding: '10px 16px',
        background: 'var(--surface-2)',
        fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
        letterSpacing: '0.05em', color: 'var(--text-subtle)',
      }}>
        <span>Notify me about</span>
        <span style={{ textAlign: 'center' }}>In-app</span>
        <span style={{ textAlign: 'center' }}>Email</span>
        <span style={{ textAlign: 'center' }}>Push</span>
      </div>
      {types.map(t => {
        const n = prefs.notif[t.k] || { app: false, email: false, push: false };
        const setCh = (ch, v) => setPref('notif', { ...prefs.notif, [t.k]: { ...n, [ch]: v } });
        return (
          <div
            key={t.k}
            style={{
              display: 'grid',
              gridTemplateColumns: '1fr 80px 80px 80px',
              padding: '12px 16px',
              borderTop: '1px solid var(--border)',
              alignItems: 'center',
            }}
          >
            <div>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{t.label}</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-subtle)', marginTop: 1 }}>{t.help}</div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Toggle checked={n.app} onChange={(v) => setCh('app', v)} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Toggle checked={n.email} onChange={(v) => setCh('email', v)} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Toggle checked={n.push} onChange={(v) => setCh('push', v)} />
            </div>
          </div>
        );
      })}
    </div>
  );
};

/* ============================================
   ADMIN — workspace + user management
   ============================================ */
const AdminView = ({ users, currentUser, onInvite, onUpdateUser, onRemove }) => {
  const [tab, setTab] = React.useState('members');
  const [search, setSearch] = React.useState('');
  const [showInvite, setShowInvite] = React.useState(false);

  const tabs = [
    { id: 'members',     label: 'Members',     count: users.length },
    { id: 'invitations', label: 'Invitations', count: 2 },
    { id: 'roles',       label: 'Roles & permissions' },
    { id: 'workspace',   label: 'Workspace' },
    { id: 'audit',       label: 'Audit log' },
  ];

  const filtered = users.filter(u =>
    !search ||
    u.name.toLowerCase().includes(search.toLowerCase()) ||
    u.email.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="settings">
      <div className="settings-header">
        <span style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(244,63,94,.14)', color: 'var(--c-rose)', display: 'grid', placeItems: 'center' }}>
          <Icon name="settings" size={20} />
        </span>
        <div style={{ flex: 1 }}>
          <h1>Admin</h1>
          <p>Manage your workspace, members, and roles.</p>
        </div>
        <Btn kind="primary" icon="plus" onClick={() => setShowInvite(true)}>Invite member</Btn>
      </div>

      <div className="tabs">
        {tabs.map(t => (
          <button key={t.id} className={`tab${tab === t.id ? ' active' : ''}`} onClick={() => setTab(t.id)}>
            {t.label}
            {t.count != null && <span className="count">{t.count}</span>}
          </button>
        ))}
      </div>

      {tab === 'members' && (
        <div className="settings-section" style={{ padding: 0 }}>
          <div style={{ padding: '16px 20px', display: 'flex', gap: 10, alignItems: 'center', borderBottom: '1px solid var(--border)' }}>
            <div className="tb-search" style={{ width: 280 }}>
              <Icon name="search" size={14} />
              <input placeholder="Search by name or email…" value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <select className="filter-chip">
              <option>All roles</option>
              <option>Admin</option>
              <option>Manager</option>
              <option>Member</option>
              <option>Guest</option>
            </select>
            <span style={{ marginLeft: 'auto', fontSize: 12.5, color: 'var(--text-muted)' }}>
              {filtered.length} member{filtered.length !== 1 ? 's' : ''}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 200px 130px 130px 40px',
            padding: '10px 20px',
            background: 'var(--surface-2)',
            fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
            letterSpacing: '0.05em', color: 'var(--text-subtle)',
          }}>
            <span>Member</span>
            <span>Role / Title</span>
            <span>Access</span>
            <span>Last active</span>
            <span></span>
          </div>
          {filtered.map(u => (
            <div key={u.id} style={{
              display: 'grid',
              gridTemplateColumns: '1fr 200px 130px 130px 40px',
              padding: '12px 20px',
              borderTop: '1px solid var(--border)',
              alignItems: 'center',
              fontSize: 13,
              gap: 12,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                <Avatar user={u} size="md" />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {u.name}
                    {u.id === currentUser.id && (
                      <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--brand-600)', marginLeft: 6, padding: '1px 6px', background: 'var(--brand-50)', borderRadius: 99, letterSpacing: '0.04em', textTransform: 'uppercase' }}>You</span>
                    )}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-subtle)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.email}</div>
                </div>
              </div>
              <span style={{ color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.role}</span>
              <span>
                <select
                  value={u.access || 'Member'}
                  onChange={(e) => onUpdateUser({ ...u, access: e.target.value })}
                  className={`role-badge role-${u.access || 'Member'}`}
                  style={{ border: 'none', cursor: 'pointer', appearance: 'none', paddingRight: 16 }}
                >
                  <option value="Admin">Admin</option>
                  <option value="Manager">Manager</option>
                  <option value="Member">Member</option>
                  <option value="Guest">Guest</option>
                </select>
              </span>
              <span style={{ color: 'var(--text-muted)', fontSize: 12.5 }}>{u.lastActive || 'Just now'}</span>
              <button className="icon-btn" title="More" disabled={u.id === currentUser.id}>
                <Icon name="more" size={14} />
              </button>
            </div>
          ))}
        </div>
      )}

      {tab === 'invitations' && (
        <div className="settings-section">
          <h2>Pending invitations</h2>
          <p className="sub">People who have been invited but haven't accepted yet.</p>
          {[
            { email: 'natthapong.k@dtgo.com',  role: 'Member',  sent: '2 days ago', inviter: 'Jiranuch C.' },
            { email: 'somchai.t@dtgo.com',     role: 'Manager', sent: '5 days ago', inviter: 'Jiranuch C.' },
          ].map((inv, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 0',
              borderTop: i > 0 ? '1px solid var(--border)' : 'none',
            }}>
              <span style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--surface-2)', color: 'var(--text-muted)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13 }}>
                {inv.email[0].toUpperCase()}
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 13.5 }}>{inv.email}</div>
                <div style={{ fontSize: 11.5, color: 'var(--text-subtle)' }}>
                  Invited by {inv.inviter} · {inv.sent}
                </div>
              </div>
              <span className={`role-badge role-${inv.role}`}>{inv.role}</span>
              <Btn kind="ghost">Resend</Btn>
              <Btn kind="ghost">Revoke</Btn>
            </div>
          ))}
        </div>
      )}

      {tab === 'roles' && (
        <div className="settings-section">
          <h2>Roles & permissions</h2>
          <p className="sub">Define what each access level can do in this workspace.</p>
          {[
            { name: 'Admin',   color: 'var(--c-rose)',    perms: ['Manage members & roles', 'Manage workspace settings', 'Manage all projects & tasks', 'View audit log', 'Manage billing'] },
            { name: 'Manager', color: 'var(--brand-600)', perms: ['Create & manage projects', 'Manage tasks in their projects', 'Assign work to members', 'Cannot manage members'] },
            { name: 'Member',  color: 'var(--text-muted)',perms: ['Create & edit own tasks', 'Comment on any task', 'View all team tasks', 'Cannot create projects'] },
            { name: 'Guest',   color: '#B45309',          perms: ['View specific projects only', 'Comment on assigned tasks', 'Cannot create tasks', 'Cannot see other projects'] },
          ].map(r => (
            <div key={r.name} style={{
              padding: '14px 0',
              borderTop: '1px solid var(--border)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <span className={`role-badge role-${r.name}`}>{r.name}</span>
                <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
                  {users.filter(u => (u.access || 'Member') === r.name).length} member{users.filter(u => (u.access || 'Member') === r.name).length !== 1 ? 's' : ''}
                </span>
              </div>
              <ul style={{ margin: 0, paddingLeft: 0, listStyle: 'none', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                {r.perms.map(p => (
                  <li key={p} style={{ fontSize: 13, color: 'var(--text-muted)', display: 'flex', gap: 8, alignItems: 'center' }}>
                    <Icon name="check" size={13} stroke={3} style={{ color: 'var(--c-emerald)', flexShrink: 0 }} />
                    {p}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      )}

      {tab === 'workspace' && (
        <>
          <SettingsSection title="Workspace details">
            <SettingsRow label="Workspace name">
              <input type="text" defaultValue="DTGO · Tasker" />
            </SettingsRow>
            <SettingsRow label="Workspace URL" help="Used for shared links">
              <input type="text" defaultValue="tasker.dtgo.com" />
            </SettingsRow>
            <SettingsRow label="Logo">
              <button className="btn btn-secondary"><Icon name="image" size={13} /> Upload logo</button>
            </SettingsRow>
            <SettingsRow label="Primary domain" help="Auto-invite users from this domain">
              <input type="text" defaultValue="dtgo.com" />
            </SettingsRow>
          </SettingsSection>
          <SettingsSection title="Billing" sub="Manage your subscription and invoices.">
            <SettingsRow label="Current plan">
              <div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>Business · ฿390/user/month</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>10 active members · Renews May 31, 2026</div>
              </div>
              <Btn kind="secondary" style={{ marginLeft: 'auto' }}>Manage plan</Btn>
            </SettingsRow>
            <SettingsRow label="Payment method">
              <span style={{ fontSize: 13 }}>Visa •••• 4242 · expires 09/27</span>
              <Btn kind="ghost">Update</Btn>
            </SettingsRow>
            <SettingsRow label="Invoices">
              <Btn kind="secondary" icon="download">Download invoices</Btn>
            </SettingsRow>
          </SettingsSection>
          <SettingsSection title="Danger zone">
            <SettingsRow label="Delete workspace" help="Permanently delete this workspace and all its data.">
              <Btn kind="danger" icon="trash">Delete workspace</Btn>
            </SettingsRow>
          </SettingsSection>
        </>
      )}

      {tab === 'audit' && (
        <div className="settings-section">
          <h2>Audit log</h2>
          <p className="sub">Recent admin actions in this workspace.</p>
          {[
            { actor: 'u3', verb: 'invited',  target: 'natthapong.k@dtgo.com',     time: '2 days ago' },
            { actor: 'u3', verb: 'changed role of', target: 'Khanit Thainiyom → Manager', time: '4 days ago' },
            { actor: 'u3', verb: 'created project', target: 'Whizdom Connect',     time: '1 week ago' },
            { actor: 'u3', verb: 'updated workspace name', target: 'DTGO → DTGO · Tasker', time: '2 weeks ago' },
            { actor: 'u3', verb: 'removed member', target: 'somsri.p@dtgo.com',     time: '3 weeks ago' },
          ].map((log, i) => {
            const u = getUser(log.actor);
            return (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 0',
                borderTop: i > 0 ? '1px solid var(--border)' : 'none',
                fontSize: 13,
              }}>
                <Avatar user={u} size="sm" />
                <span style={{ flex: 1 }}>
                  <b>{u?.short}</b> {log.verb} <span style={{ color: 'var(--text-muted)' }}>{log.target}</span>
                </span>
                <span style={{ fontSize: 11.5, color: 'var(--text-subtle)' }}>{log.time}</span>
              </div>
            );
          })}
        </div>
      )}

      {/* INVITE MODAL */}
      <Modal
        open={showInvite}
        onClose={() => setShowInvite(false)}
        title="Invite member"
        footer={<>
          <Btn kind="ghost" onClick={() => setShowInvite(false)}>Cancel</Btn>
          <Btn kind="primary" icon="send" onClick={() => { onInvite(); setShowInvite(false); }}>Send invitations</Btn>
        </>}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="fg">
            <label className="fl">Email addresses</label>
            <textarea
              className="fta"
              placeholder="email@dtgo.com, another@dtgo.com&#10;Separate with commas or new lines"
              rows={3}
            />
          </div>
          <div className="fg">
            <label className="fl">Role</label>
            <select className="fs" defaultValue="Member">
              <option value="Admin">Admin — full control</option>
              <option value="Manager">Manager — manage projects</option>
              <option value="Member">Member — standard access</option>
              <option value="Guest">Guest — view specific projects only</option>
            </select>
          </div>
          <div className="fg">
            <label className="fl">Add to projects (optional)</label>
            <select className="fs">
              <option value="">Don't add to any project yet</option>
              {PROJECTS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>
          <div className="fg">
            <label className="fl">Personal message (optional)</label>
            <textarea className="fta" placeholder="Welcome to the team! 👋" rows={2} />
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { ProfileView, PreferencesView, AdminView, SettingsRow, SettingsSection });
