/* Settings — Profile, 2FA, Push, Members, Integrations, API, Billing */

function SettingsView({ tweaks, setTweak }) {
  const [section, setSection] = React.useState('profile');

  const nav = [
    { key: 'profile',      label: 'Profile',           glyph: '◉', group: 'Account' },
    { key: 'preferences',  label: 'Preferences',       glyph: '⚙', group: 'Account' },
    { key: '2fa',          label: '2FA & sessions',    glyph: '⌬', group: 'Account' },
    { key: 'push',         label: 'Notifications',     glyph: '🔔', group: 'Account' },
    { key: 'members',      label: 'Members & roles',   glyph: '◍', group: 'Workspace' },
    { key: 'spaces',       label: 'Spaces & statuses', glyph: '▤', group: 'Workspace' },
    { key: 'templates',    label: 'Task templates',    glyph: '✚', group: 'Workspace' },
    { key: 'api',          label: 'API & webhooks',    glyph: '⌗', group: 'Workspace' },
  ];

  return (
    <div style={{ flex: 1, display: 'flex', background: 'rgb(var(--bg))', overflow: 'hidden' }}>
      {/* Sub-nav */}
      <nav style={{
        width: 230, flexShrink: 0,
        padding: '24px 14px',
        borderRight: '1px solid rgb(var(--rule))',
        overflowY: 'auto',
      }}>
        <p style={{ margin: '0 0 4px', padding: '0 10px', fontSize: 11, fontWeight: 700, color: 'rgb(var(--accent))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>Settings</p>
        {['Account', 'Workspace'].map(group => (
          <div key={group} style={{ marginTop: 14 }}>
            <p style={{ margin: '0 0 6px', padding: '0 10px', fontSize: 10.5, fontWeight: 600, color: 'rgb(var(--muted))', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{group}</p>
            {nav.filter(n => n.group === group).map(n => (
              <button key={n.key} onClick={() => setSection(n.key)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                width: '100%', padding: '7px 10px',
                marginBottom: 2, borderRadius: 8,
                fontSize: 13, fontWeight: section === n.key ? 600 : 500,
                color: section === n.key ? 'rgb(var(--accent-2))' : 'rgb(var(--ink-2))',
                background: section === n.key ? 'rgb(var(--accent-soft))' : 'transparent',
              }}
                onMouseEnter={e => { if (section !== n.key) e.currentTarget.style.background = 'rgb(var(--paper-2))'; }}
                onMouseLeave={e => { if (section !== n.key) e.currentTarget.style.background = 'transparent'; }}>
                <span style={{ width: 16, textAlign: 'center', fontSize: 13, color: section === n.key ? 'rgb(var(--accent))' : 'rgb(var(--muted))' }}>{n.glyph}</span>
                <span style={{ flex: 1, textAlign: 'left' }}>{n.label}</span>
              </button>
            ))}
          </div>
        ))}
      </nav>

      {/* Pane */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ maxWidth: 760, padding: '32px 36px 60px' }}>
          {section === 'profile'      && <ProfileSection />}
          {section === 'preferences'  && <PreferencesSection tweaks={tweaks} setTweak={setTweak} />}
          {section === '2fa'          && <TwoFactorSection />}
          {section === 'push'         && <PushSection />}
          {section === 'members'      && <MembersSection />}
          {section === 'spaces'       && <SpacesSection />}
          {section === 'templates'    && <TemplatesSection />}
          {section === 'integrations' && <IntegrationsSection />}
          {section === 'api'          && <ApiSection />}
          {section === 'billing'      && <BillingSection />}
        </div>
      </div>
    </div>
  );
}

function Head({ eyebrow, title, sub }) {
  return (
    <header style={{ marginBottom: 24 }}>
      <p style={{ margin: 0, fontSize: 12, fontWeight: 600, color: 'rgb(var(--accent))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{eyebrow}</p>
      <h1 style={{ margin: '4px 0 0', fontSize: 26, fontWeight: 700, letterSpacing: '-0.025em' }}>{title}</h1>
      {sub && <p style={{ margin: '6px 0 0', fontSize: 13.5, color: 'rgb(var(--muted))', lineHeight: 1.55, maxWidth: 540 }}>{sub}</p>}
    </header>
  );
}

function Card({ title, sub, children, actions }) {
  return (
    <section style={{
      background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
      borderRadius: 14, padding: 22, marginBottom: 16, boxShadow: 'var(--sh-sm)',
    }}>
      {(title || sub || actions) && (
        <header style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 14 }}>
          <div style={{ flex: 1 }}>
            {title && <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em' }}>{title}</h3>}
            {sub && <p style={{ margin: '3px 0 0', fontSize: 12.5, color: 'rgb(var(--muted))' }}>{sub}</p>}
          </div>
          {actions}
        </header>
      )}
      {children}
    </section>
  );
}

function Field({ label, hint, children, span = 12 }) {
  return (
    <div style={{ gridColumn: `span ${span}` }}>
      <p style={{ margin: '0 0 6px', fontSize: 11.5, fontWeight: 600, color: 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</p>
      {children}
      {hint && <p style={{ margin: '5px 0 0', fontSize: 11.5, color: 'rgb(var(--muted))' }}>{hint}</p>}
    </div>
  );
}

function Row({ children, style }) {
  return <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 14, ...style }}>{children}</div>;
}

/* Sections ───────────────────────────────────────────────── */
function ProfileSection() {
  return (
    <>
      <Head eyebrow="Account" title="Profile" sub="The basics about you. Shown on your tasks, comments, and the team workload reports." />
      <Card title="Personal details">
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 16 }}>
          <Avatar user={userById(1)} size={72} />
          <div>
            <button className="btn btn-secondary" style={{ fontSize: 12 }}>Change photo</button>
            <p style={{ margin: '8px 0 0', fontSize: 11.5, color: 'rgb(var(--muted))' }}>JPG or PNG, up to 2 MB</p>
          </div>
        </div>
        <Row>
          <Field label="Full name" span={6}><input defaultValue="Alex Harley" style={inp} /></Field>
          <Field label="Display name" span={6}><input defaultValue="Alex" style={inp} /></Field>
          <Field label="Email" span={6}><input defaultValue="billing@harleymindcare.com" style={inp} /></Field>
          <Field label="Phone" span={6}><input defaultValue="+44 20 7946 0123" style={inp} /></Field>
          <Field label="Role" span={6}>
            <select style={inp} defaultValue="lead">
              <option value="lead">Lead clinician</option>
              <option value="clinician">Clinician</option>
              <option value="admin">Administrator</option>
            </select>
          </Field>
          <Field label="Time zone" span={6}>
            <select style={inp} defaultValue="london"><option>Europe/London (GMT+1)</option><option>UTC</option></select>
          </Field>
        </Row>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 18 }}>
          <button className="btn btn-secondary" style={{ fontSize: 12.5 }}>Cancel</button>
          <button className="btn btn-accent" style={{ fontSize: 12.5 }}>Save changes</button>
        </div>
      </Card>

      <Card title="Danger zone" sub="Deactivate your account or transfer ownership of the workspace.">
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary" style={{ fontSize: 12 }}>Export my data</button>
          <button style={{ ...inp, width: 'auto', fontSize: 12, fontWeight: 600, padding: '7px 14px', background: 'rgb(var(--brick-soft))', color: 'rgb(var(--brick))', border: '1px solid rgb(var(--brick) / 0.3)', cursor: 'pointer' }}>Deactivate account</button>
        </div>
      </Card>
    </>
  );
}

function PreferencesSection({ tweaks, setTweak }) {
  return (
    <>
      <Head eyebrow="Account" title="Preferences" sub="Theme, density, and view defaults. These are the same controls as the toolbar Tweaks panel — kept here for completeness." />
      <Card title="Appearance">
        <Row>
          <Field label="Theme" span={6}>
            <select style={inp} value={tweaks?.theme || 'light'} onChange={e => setTweak?.('theme', e.target.value)}>
              <option value="light">Light</option><option value="dark">Dark</option><option value="auto">Auto (match OS)</option>
            </select>
          </Field>
          <Field label="Density" span={6}>
            <select style={inp} value={tweaks?.density || 'cozy'} onChange={e => setTweak?.('density', e.target.value)}>
              <option value="compact">Compact</option><option value="cozy">Cozy</option><option value="spacious">Spacious</option>
            </select>
          </Field>
          <Field label="Accent colour" span={12}>
            <div style={{ display: 'flex', gap: 8 }}>
              {[['indigo','#6366F1'],['emerald','#10B981'],['coral','#F97316'],['violet','#8B5CF6'],['rose','#F43F5E']].map(([k, c]) => (
                <button key={k} onClick={() => setTweak?.('accent', k)} style={{
                  flex: 1, height: 48, borderRadius: 10, background: c,
                  border: '2px solid ' + ((tweaks?.accent || 'indigo') === k ? 'rgb(var(--ink))' : 'transparent'),
                  position: 'relative',
                }}>{(tweaks?.accent || 'indigo') === k && <span style={{ color: 'white', fontSize: 18 }}>✓</span>}</button>
              ))}
            </div>
          </Field>
        </Row>
      </Card>

      <Card title="Defaults">
        <Row>
          <Field label="Default view mode" span={6}>
            <select style={inp} value={tweaks?.defaultViewMode || 'list'} onChange={e => setTweak?.('defaultViewMode', e.target.value)}>
              <option value="list">List</option><option value="board">Board</option><option value="calendar">Calendar</option>
              <option value="timeline">Timeline</option><option value="cards">Cards</option><option value="agenda">Agenda</option><option value="focus">Focus</option>
            </select>
          </Field>
          <Field label="Landing view" span={6}>
            <select style={inp} defaultValue="my-day">
              <option value="my-day">My Day</option><option value="my-tasks">My Tasks</option><option value="dashboards">Dashboards</option>
            </select>
          </Field>
        </Row>
      </Card>
    </>
  );
}

function TwoFactorSection() {
  return (
    <>
      <Head eyebrow="Account" title="Two-factor & sessions" sub="Add a second factor to your sign-in. We use TOTP (Google Authenticator, 1Password, etc.). Strongly recommended for clinical accounts." />
      <Card title="TOTP authenticator" sub="Currently enabled" actions={
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'rgb(var(--forest))', background: 'rgb(var(--forest-soft))', padding: '3px 10px', borderRadius: 999 }}>
          <span style={{ width: 6, height: 6, background: 'rgb(var(--forest))', borderRadius: '50%' }} /> Active
        </span>
      }>
        <p style={{ fontSize: 13, color: 'rgb(var(--ink-2))', margin: '0 0 14px' }}>
          Enabled on <strong>3 May 2026</strong>. Reset codes used: <strong>0 / 8</strong>.
        </p>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary" style={{ fontSize: 12 }}>Regenerate recovery codes</button>
          <button className="btn btn-secondary" style={{ fontSize: 12, color: 'rgb(var(--brick))' }}>Disable 2FA</button>
        </div>
      </Card>

      <Card title="Active sessions" sub="Sign out remotely if anything looks unfamiliar.">
        <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
          {[
            { device: 'Mac · Chrome 126', loc: 'London, UK', ip: '82.12.4.118', when: 'Now',           current: true },
            { device: 'iPhone 15 · Safari', loc: 'London, UK', ip: '82.12.4.118', when: '2 hours ago', current: false },
            { device: 'iPad · Safari',     loc: 'Brighton, UK', ip: '82.12.7.62', when: 'Yesterday',    current: false },
          ].map((s, i) => (
            <li key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderTop: i === 0 ? 'none' : '1px solid rgb(var(--rule) / 0.7)' }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: 'rgb(var(--paper-2))', color: 'rgb(var(--muted))',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 16,
              }}>{s.device.includes('iPhone') ? '◙' : s.device.includes('iPad') ? '⊟' : '◰'}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{s.device}{s.current && <span style={{ marginLeft: 8, fontSize: 10, fontWeight: 700, color: 'rgb(var(--forest))', padding: '1px 7px', background: 'rgb(var(--forest-soft))', borderRadius: 999, letterSpacing: '0.04em', textTransform: 'uppercase' }}>This device</span>}</div>
                <div style={{ fontSize: 11.5, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{s.loc} · {s.ip} · {s.when}</div>
              </div>
              {!s.current && <button className="btn btn-secondary" style={{ fontSize: 11.5, padding: '4px 10px', color: 'rgb(var(--brick))' }}>Sign out</button>}
            </li>
          ))}
        </ul>
      </Card>
    </>
  );
}

function PushSection() {
  return (
    <>
      <Head eyebrow="Account" title="Notifications" sub="Choose how and when Taskhub reaches out — in-app, on this device, or via email digest." />
      <Card title="This device · Web push">
        <NotificationToggleRow label="Enable push notifications" hint="Permission granted on Chrome · Mac" defaultOn />
        <NotificationToggleRow label="Mentions & replies" hint="When someone @-mentions you or replies in a thread" defaultOn />
        <NotificationToggleRow label="Assignments" hint="When a task is assigned to you" defaultOn />
        <NotificationToggleRow label="Status changes on watched tasks" defaultOn={false} />
        <NotificationToggleRow label="Comments on watched tasks" defaultOn={false} />
        <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary" style={{ fontSize: 12 }}>Send a test notification</button>
          <button className="btn btn-secondary" style={{ fontSize: 12, color: 'rgb(var(--brick))' }}>Disable on all devices</button>
        </div>
      </Card>

      <Card title="Email digest">
        <Row>
          <Field label="Frequency" span={6}>
            <select style={inp} defaultValue="daily"><option value="off">Off</option><option value="daily">Daily · 07:30</option><option value="weekly">Weekly · Monday 07:30</option></select>
          </Field>
          <Field label="Include" span={6}>
            <select style={inp} defaultValue="all"><option value="all">Everything</option><option value="mentions">Mentions only</option><option value="assigned">Assigned to me</option></select>
          </Field>
        </Row>
        <p style={{ margin: '12px 0 0', fontSize: 11.5, color: 'rgb(var(--muted))' }}>Last sent: <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>18 May 2026 · 07:30</span></p>
      </Card>
    </>
  );
}
function NotificationToggleRow({ label, hint, defaultOn = true }) {
  const [on, setOn] = React.useState(defaultOn);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 0', borderTop: '1px solid rgb(var(--rule) / 0.6)' }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500 }}>{label}</div>
        {hint && <div style={{ fontSize: 11.5, color: 'rgb(var(--muted))', marginTop: 2 }}>{hint}</div>}
      </div>
      <button onClick={() => setOn(o => !o)} aria-pressed={on} style={{
        position: 'relative', width: 36, height: 20, borderRadius: 999,
        background: on ? 'rgb(var(--accent))' : 'rgb(var(--rule-2))',
        transition: 'background .14s',
      }}>
        <span style={{
          position: 'absolute', top: 2, left: on ? 18 : 2,
          width: 16, height: 16, borderRadius: '50%', background: 'white',
          transition: 'left .14s', boxShadow: '0 1px 2px rgba(0,0,0,0.2)',
        }} />
      </button>
    </div>
  );
}

function MembersSection() {
  const roles = [
    { user: userById(1), role: 'Owner',         joined: '2024-08-12' },
    { user: userById(2), role: 'Admin',         joined: '2024-09-01' },
    { user: userById(3), role: 'Coordinator',   joined: '2024-09-12' },
    { user: userById(4), role: 'Member',        joined: '2025-01-04' },
    { user: userById(5), role: 'Member',        joined: '2025-03-22' },
    { user: userById(6), role: 'Member',        joined: '2025-09-18' },
  ];
  return (
    <>
      <Head eyebrow="Workspace" title="Members & roles" sub="Who can see what. Roles control permissions across the whole workspace; per-space access is managed in each space's settings." />
      <Card title={`${roles.length} members`} actions={<button className="btn btn-accent" style={{ fontSize: 12.5 }}>+ Invite member</button>}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid rgb(var(--rule))' }}>
              <th style={mth}>Member</th>
              <th style={mth}>Role</th>
              <th style={mth}>Joined</th>
              <th style={mth}>Status</th>
              <th style={{ ...mth, textAlign: 'right' }}></th>
            </tr>
          </thead>
          <tbody>
            {roles.map((r, i) => (
              <tr key={r.user.id} style={{ borderBottom: i === roles.length - 1 ? 'none' : '1px solid rgb(var(--rule) / 0.6)' }}>
                <td style={mtd}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <Avatar user={r.user} size={28} />
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{r.user.name}</div>
                      <div style={{ fontSize: 11.5, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{r.user.name.toLowerCase().replace(' ', '.')}@harleymindcare.com</div>
                    </div>
                  </div>
                </td>
                <td style={mtd}>
                  <select defaultValue={r.role} style={{ fontSize: 12, padding: '4px 8px' }}>
                    <option>Owner</option><option>Admin</option><option>Coordinator</option><option>Member</option><option>Guest</option>
                  </select>
                </td>
                <td style={mtd}><span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11.5, color: 'rgb(var(--muted))' }}>{r.joined}</span></td>
                <td style={mtd}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 600, color: 'rgb(var(--forest))', background: 'rgb(var(--forest-soft))', padding: '2px 9px', borderRadius: 999 }}>
                    <span style={{ width: 5, height: 5, background: 'rgb(var(--forest))', borderRadius: '50%' }} /> Active
                  </span>
                </td>
                <td style={{ ...mtd, textAlign: 'right' }}>
                  {r.role !== 'Owner' && <button className="btn-ghost" style={{ fontSize: 11.5 }}>Remove</button>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}
const mth = { textAlign: 'left', padding: '10px 14px 10px 0', fontSize: 10.5, fontWeight: 600, color: 'rgb(var(--muted))', letterSpacing: '0.05em', textTransform: 'uppercase' };
const mtd = { padding: '12px 14px 12px 0', verticalAlign: 'middle' };

function SpacesSection() {
  return (
    <>
      <Head eyebrow="Workspace" title="Spaces & statuses" sub="Spaces hold tasks, statuses, custom fields, and webhooks. Drag to reorder. Each space can have its own SLA and visibility." />
      <Card title="Spaces" actions={<button className="btn btn-accent" style={{ fontSize: 12.5 }}>+ New space</button>}>
        <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
          {D.spaces.map((s, i) => (
            <li key={s.id} style={{
              display: 'grid', gridTemplateColumns: '20px 1fr 80px 70px 100px auto',
              gap: 12, alignItems: 'center',
              padding: '12px 0', borderTop: i === 0 ? 'none' : '1px solid rgb(var(--rule) / 0.7)',
            }}>
              <span style={{ width: 14, height: 14, background: s.colour, borderRadius: 3 }} />
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{s.name}</div>
                <div style={{ fontSize: 11.5, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{s.prefix}</div>
              </div>
              <span style={{ fontSize: 11.5, color: 'rgb(var(--muted))' }}>{D.tasks.filter(t => t.spaceId === s.id).length} tasks</span>
              <span style={{ fontSize: 11.5, color: 'rgb(var(--muted))' }}>{s.sla ? `SLA ${s.sla}d` : 'no SLA'}</span>
              <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 9px', borderRadius: 999, background: s.visibility === 'private' ? 'rgb(var(--paper-2))' : 'rgb(var(--accent-soft))', color: s.visibility === 'private' ? 'rgb(var(--muted))' : 'rgb(var(--accent-2))' }}>{s.visibility}</span>
              <button className="btn btn-secondary" style={{ fontSize: 11.5, padding: '4px 10px' }}>Configure</button>
            </li>
          ))}
        </ul>
      </Card>

      <Card title="Global statuses" sub="Used by every space unless that space overrides them.">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {D.statuses.map(s => (
            <div key={s.id} style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '6px 12px', background: 'rgb(var(--paper-2))', borderRadius: 999, fontSize: 12.5, fontWeight: 600,
            }}>
              <span className="pip" style={{ background: s.colour }} />
              <span style={{ color: 'rgb(var(--ink))' }}>{s.title}</span>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgb(var(--muted))' }}>·</span>
              <span style={{ fontSize: 11, color: 'rgb(var(--muted))' }}>{D.tasks.filter(t => t.statusId === s.id).length}</span>
            </div>
          ))}
          <button className="btn btn-secondary" style={{ fontSize: 12, padding: '6px 12px', borderRadius: 999 }}>+ Add</button>
        </div>
      </Card>
    </>
  );
}

function TemplatesSection() {
  const [templates, setTemplates] = React.useState(() => getTaskTemplates());
  const [editing, setEditing] = React.useState(null);
  const [creating, setCreating] = React.useState(false);

  React.useEffect(() => {
    const h = () => setTemplates(getTaskTemplates());
    window.addEventListener('taskhub-templates-changed', h);
    return () => window.removeEventListener('taskhub-templates-changed', h);
  }, []);

  const commit = (next) => { saveTaskTemplates(next); setTemplates(next); };
  const removeTpl = (id) => commit(templates.filter(t => t.id !== id));
  const saveTpl = (tpl) => {
    const idx = templates.findIndex(t => t.id === tpl.id);
    if (idx === -1) commit([...templates, tpl]);
    else            commit(templates.map((t, i) => i === idx ? tpl : t));
    setEditing(null); setCreating(false);
  };
  const resetAll = () => commit(window.TASK_TEMPLATES);
  const newDefaults = () => ({
    id: 'tpl-' + Math.random().toString(36).slice(2, 8),
    name: '', desc: '', glyph: '◇', tint: '#6366F1',
    spaceId: 1, type: 'task', priority: 'medium',
    titlePlaceholder: '', tags: [], checklist: [], estimateMins: 0,
    reminderDaysBefore: null,
  });

  return (
    <>
      <Head eyebrow="Workspace" title="Task templates" sub="Reusable starting points for common clinical workflows. Pre-fill space, priority, tags, and a checklist so the team starts every recurring task the same way." />
      <Card title={`${templates.length} templates`}
        actions={<span style={{ display: 'inline-flex', gap: 8 }}>
          <button onClick={resetAll} className="btn btn-secondary" style={{ fontSize: 11.5 }}>Reset to defaults</button>
          <button onClick={() => setCreating(true)} className="btn btn-accent" style={{ fontSize: 12 }}>+ New template</button>
        </span>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {templates.map(t => (
            <div key={t.id} style={{
              display: 'grid', gridTemplateColumns: '40px 1fr auto auto',
              gap: 12, alignItems: 'center', padding: '10px 12px',
              background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 10,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: t.tint + '14', color: t.tint,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 15, fontWeight: 700,
              }}>{t.glyph}</div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: 'rgb(var(--ink))' }}>{t.name}</div>
                <div style={{ fontSize: 11.5, color: 'rgb(var(--muted))', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.desc}</div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 3, fontSize: 11, color: 'rgb(var(--muted))' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                    <span style={{ width: 6, height: 6, background: spaceById(t.spaceId)?.colour, borderRadius: 2 }} />
                    {spaceById(t.spaceId)?.name}
                  </span>
                  <span>·</span><PriorityDot p={t.priority} /><span>{t.priority}</span>
                  <span>·</span><span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{t.checklist.length} steps</span>
                  {t.estimateMins > 0 && <><span>·</span><span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{fmtMins(t.estimateMins)}</span></>}
                </div>
              </div>
              <button onClick={() => setEditing(t)} className="btn btn-secondary" style={{ fontSize: 11.5 }}>Edit</button>
              <button onClick={() => removeTpl(t.id)} className="btn btn-secondary" style={{ fontSize: 11.5, color: 'rgb(var(--brick))' }}>Delete</button>
            </div>
          ))}
          {templates.length === 0 && (
            <div style={{ padding: 32, textAlign: 'center', color: 'rgb(var(--muted))', border: '1.5px dashed rgb(var(--rule-2))', borderRadius: 10 }}>
              No templates yet — click "+ New template" to create one.
            </div>
          )}
        </div>
      </Card>

      {(editing || creating) && (
        <TemplateForm
          template={editing || newDefaults()}
          onSave={saveTpl}
          onClose={() => { setEditing(null); setCreating(false); }}
        />
      )}
    </>
  );
}

function TemplateForm({ template, onSave, onClose }) {
  const [t, setT] = React.useState(template);
  const set = (k, v) => setT(p => ({ ...p, [k]: v }));
  const submit = (e) => { e?.preventDefault(); if (!t.name.trim()) return; onSave({ ...t, checklist: t.checklist.filter(s => s.trim()) }); };
  const glyphs = ['◇', '➜', '✓', '£', '⚠', '⌬', '☰', '✦', '◐', '◉', '★', '☀'];
  const tints = ['#6366F1', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#3B82F6', '#64748B'];

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.45)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 230, padding: 28,
    }}>
      <form onClick={e => e.stopPropagation()} onSubmit={submit} className="fadein shadow-pop" style={{
        background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
        borderRadius: 14, width: 600, maxHeight: '88vh', overflowY: 'auto',
      }}>
        <div style={{ padding: '16px 22px', borderBottom: '1px solid rgb(var(--rule))' }}>
          <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>{template.name ? 'Edit template' : 'New template'}</h3>
          <p style={{ margin: '3px 0 0', fontSize: 12, color: 'rgb(var(--muted))' }}>Set the defaults for tasks created from this template.</p>
        </div>
        <div style={{ padding: '18px 22px' }}>
          <Row>
            <Field label="Name" span={8}><input value={t.name} onChange={e => set('name', e.target.value)} placeholder="e.g. New referral intake" style={inp} autoFocus /></Field>
            <Field label="Estimate (mins)" span={4}><input type="number" min="0" value={t.estimateMins || 0} onChange={e => set('estimateMins', parseInt(e.target.value, 10) || 0)} style={inp} /></Field>
            <Field label="Reminder (days before due)" span={4} hint="When a task is created from this template, a reminder is auto-set this many days before the due date.">
              <input type="number" min="0" max="365" value={t.reminderDaysBefore ?? ''} onChange={e => set('reminderDaysBefore', e.target.value === '' ? null : (parseInt(e.target.value, 10) || 0))} placeholder="e.g. 7" style={inp} />
            </Field>
            <Field label="Description" span={12}><input value={t.desc} onChange={e => set('desc', e.target.value)} placeholder="One-line summary" style={inp} /></Field>
            <Field label="Title placeholder" span={12}><input value={t.titlePlaceholder} onChange={e => set('titlePlaceholder', e.target.value)} placeholder="e.g. Triage referral — [patient name]" style={inp} /></Field>
            <Field label="Space" span={6}>
              <select value={t.spaceId} onChange={e => set('spaceId', parseInt(e.target.value, 10))} style={inp}>
                {D.spaces.map(sp => <option key={sp.id} value={sp.id}>{sp.name}</option>)}
              </select>
            </Field>
            <Field label="Priority" span={3}>
              <select value={t.priority} onChange={e => set('priority', e.target.value)} style={inp}>
                <option value="urgent">Urgent</option><option value="high">High</option><option value="medium">Medium</option><option value="low">Low</option>
              </select>
            </Field>
            <Field label="Type" span={3}>
              <select value={t.type} onChange={e => set('type', e.target.value)} style={inp}>
                <option value="task">Task</option><option value="referral">Referral</option><option value="incident">Incident</option>
                <option value="audit">Audit</option><option value="admin">Admin</option>
              </select>
            </Field>
            <Field label="Icon" span={6}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                {glyphs.map(g => (
                  <button type="button" key={g} onClick={() => set('glyph', g)} style={{
                    width: 30, height: 30, borderRadius: 7,
                    background: t.glyph === g ? 'rgb(var(--accent))' : 'rgb(var(--paper-2))',
                    color: t.glyph === g ? 'white' : 'rgb(var(--ink))', fontSize: 13, fontWeight: 700,
                  }}>{g}</button>
                ))}
              </div>
            </Field>
            <Field label="Tint" span={6}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                {tints.map(c => (
                  <button type="button" key={c} onClick={() => set('tint', c)} style={{
                    width: 30, height: 30, borderRadius: 7, background: c,
                    border: '2px solid ' + (t.tint === c ? 'rgb(var(--ink))' : 'transparent'),
                  }} />
                ))}
              </div>
            </Field>
            <Field label="Checklist steps" span={12}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {t.checklist.map((step, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 16, height: 16, borderRadius: 5, border: '1.5px solid rgb(var(--rule-2))', flexShrink: 0 }} />
                    <input value={step} onChange={e => set('checklist', t.checklist.map((s, j) => j === i ? e.target.value : s))} placeholder="Step description" style={{ ...inp, flex: 1 }} />
                    <button type="button" onClick={() => set('checklist', t.checklist.filter((_, j) => j !== i))} style={{ width: 26, height: 26, borderRadius: 6, color: 'rgb(var(--muted))', fontSize: 13 }}>×</button>
                  </div>
                ))}
                <button type="button" onClick={() => set('checklist', [...t.checklist, ''])} className="btn btn-secondary" style={{ fontSize: 11.5, alignSelf: 'flex-start', marginTop: 4 }}>+ Add step</button>
              </div>
            </Field>
          </Row>
        </div>
        <div style={{ padding: '12px 22px', borderTop: '1px solid rgb(var(--rule))', background: 'rgb(var(--bg))', display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button type="button" onClick={onClose} className="btn btn-secondary" style={{ fontSize: 12.5 }}>Cancel</button>
          <button type="submit" className="btn btn-accent" style={{ fontSize: 12.5 }} disabled={!t.name.trim()}>Save template</button>
        </div>
      </form>
    </div>
  );
}

function IntegrationsSection() {
  const items = [
    { name: 'Email-Hub',              status: 'connected', desc: 'Microsoft 365 mail client · "Send to Taskhub" button',          glyph: '✉', tint: 'rgb(var(--accent))' },
    { name: 'Microsoft 365 Calendar', status: 'available', desc: 'Two-way sync with Outlook calendar via Graph',                  glyph: '▦', tint: 'rgb(var(--navy))' },
    { name: 'Google Workspace SSO',   status: 'available', desc: 'Sign in with your Google Workspace account',                    glyph: 'G', tint: 'rgb(var(--brick))' },
    { name: 'Slack',                  status: 'available', desc: 'Mention notifications and daily digest in a channel',           glyph: '#', tint: 'rgb(var(--berry))' },
    { name: 'Teams',                  status: 'available', desc: 'Same as Slack — to a channel in Microsoft Teams',               glyph: 'T', tint: 'rgb(var(--navy))' },
    { name: 'Stripe',                 status: 'connected', desc: 'Self-pay invoicing and reconciliation',                          glyph: '£', tint: 'rgb(var(--warm))' },
    { name: 'Google Calendar',        status: 'available', desc: 'Sync events bi-directionally',                                  glyph: '▦', tint: 'rgb(var(--forest))' },
    { name: 'GitHub Issues',          status: 'available', desc: 'Link tasks to issues for engineering work',                     glyph: '◇', tint: 'rgb(var(--muted))' },
  ];
  return (
    <>
      <Head eyebrow="Workspace" title="Integrations" sub="Connect Taskhub to the rest of your stack. Most integrations are scoped per-workspace and can be revoked at any time." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
        {items.map(it => (
          <div key={it.name} style={{
            background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
            borderRadius: 12, padding: 16, boxShadow: 'var(--sh-sm)',
            display: 'flex', alignItems: 'flex-start', gap: 12,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 10,
              background: it.tint + '14', color: it.tint,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 16, fontWeight: 700, flexShrink: 0,
            }}>{it.glyph}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
                <span style={{ fontSize: 14, fontWeight: 700 }}>{it.name}</span>
                {it.status === 'connected' && <span style={{ fontSize: 10, fontWeight: 700, color: 'rgb(var(--forest))', background: 'rgb(var(--forest-soft))', padding: '1px 7px', borderRadius: 999, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Connected</span>}
              </div>
              <p style={{ margin: 0, fontSize: 12, color: 'rgb(var(--muted))' }}>{it.desc}</p>
              <button className={it.status === 'connected' ? 'btn btn-secondary' : 'btn btn-accent'} style={{ fontSize: 11.5, padding: '4px 12px', marginTop: 10 }}>
                {it.status === 'connected' ? 'Manage' : 'Connect'}
              </button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

function ApiSection() {
  return (
    <>
      <Head eyebrow="Workspace" title="API & webhooks" sub="Bring tasks in from email-hub, push out to your own systems, or build custom flows. Token authentication, HMAC signatures, full audit log." />
      <Card title="Ingest token" sub="POST /api/ingest/task · creates a task from an external system" actions={<button className="btn btn-secondary" style={{ fontSize: 11.5 }}>Rotate</button>}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '10px 14px',
          background: 'rgb(var(--paper-2))', borderRadius: 10,
          fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
        }}>
          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>thx_4f9c1b8e2a3d6f0e7b1c·····················88de</span>
          <button className="btn btn-secondary" style={{ fontSize: 11, padding: '3px 8px' }}>Copy</button>
        </div>
      </Card>
      <Card title="Outgoing webhooks" actions={<button className="btn btn-accent" style={{ fontSize: 12 }}>+ New webhook</button>}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid rgb(var(--rule))' }}>
              <th style={mth}>Label</th><th style={mth}>URL</th><th style={mth}>Events</th><th style={mth}>Status</th><th style={mth}></th>
            </tr>
          </thead>
          <tbody>
            {[
              { l: 'Customer ledger', u: 'https://ledger.harleymindcare.com/hooks/taskhub', e: 'task.created, task.updated, task.archived', s: 'active' },
              { l: 'Analytics relay',  u: 'https://stream.posthog.com/i/E2F8...',            e: 'task.created, task.archived',                  s: 'active' },
              { l: 'Slack failsafe',   u: 'https://hooks.slack.com/services/T0···/B0···',     e: 'task.created',                                 s: 'paused' },
            ].map((w, i) => (
              <tr key={i} style={{ borderBottom: i === 2 ? 'none' : '1px solid rgb(var(--rule) / 0.6)' }}>
                <td style={mtd}><strong>{w.l}</strong></td>
                <td style={{ ...mtd, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'rgb(var(--muted))', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 240 }}>{w.u}</td>
                <td style={{ ...mtd, fontSize: 11, color: 'rgb(var(--muted))' }}>{w.e}</td>
                <td style={mtd}>
                  <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 9px', borderRadius: 999,
                    background: w.s === 'active' ? 'rgb(var(--forest-soft))' : 'rgb(var(--paper-2))',
                    color: w.s === 'active' ? 'rgb(var(--forest))' : 'rgb(var(--muted))' }}>{w.s}</span>
                </td>
                <td style={{ ...mtd, textAlign: 'right' }}><button className="btn-ghost" style={{ fontSize: 11 }}>Edit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}

function BillingSection() {
  return (
    <>
      <Head eyebrow="Workspace" title="Billing & plan" sub="Your workspace plan, members, and invoices." />
      <Card title="Current plan" actions={<button className="btn btn-accent" style={{ fontSize: 12 }}>Manage plan</button>}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <div style={{
            width: 64, height: 64, borderRadius: 14,
            background: 'linear-gradient(135deg, rgb(var(--accent)), rgb(var(--berry)))',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: 'white', fontSize: 26, fontWeight: 700,
          }}>P</div>
          <div style={{ flex: 1 }}>
            <h3 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>Practice · annual</h3>
            <p style={{ margin: '3px 0 0', fontSize: 13, color: 'rgb(var(--muted))' }}>6 of 10 seats used · renews 18 Aug 2026</p>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="num" style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em' }}>£1,188</div>
            <div style={{ fontSize: 11.5, color: 'rgb(var(--muted))' }}>annual · £99/user</div>
          </div>
        </div>
      </Card>

      <Card title="Payment method">
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            padding: '8px 14px', borderRadius: 8,
            background: 'rgb(var(--paper-2))', fontFamily: 'JetBrains Mono, monospace', fontSize: 13,
          }}>**** **** **** 4242</div>
          <span style={{ fontSize: 13, color: 'rgb(var(--muted))' }}>Visa · expires 12/27</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-secondary" style={{ fontSize: 12 }}>Update</button>
        </div>
      </Card>

      <Card title="Recent invoices">
        <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
          {[
            { d: '2025-08-18', a: '£1,188.00', n: 'Practice — annual',  status: 'paid' },
            { d: '2024-08-18', a: '£990.00',   n: 'Practice — annual',  status: 'paid' },
            { d: '2023-08-18', a: '£828.00',   n: 'Practice — annual',  status: 'paid' },
          ].map((inv, i) => (
            <li key={i} style={{
              display: 'grid', gridTemplateColumns: '90px 1fr auto 80px 70px',
              gap: 12, alignItems: 'center',
              padding: '10px 0', borderTop: i === 0 ? 'none' : '1px solid rgb(var(--rule) / 0.6)',
            }}>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11.5, color: 'rgb(var(--muted))' }}>{inv.d}</span>
              <span style={{ fontSize: 13 }}>{inv.n}</span>
              <span className="num" style={{ fontSize: 13, fontWeight: 600 }}>{inv.a}</span>
              <span style={{ fontSize: 11, fontWeight: 600, color: 'rgb(var(--forest))', background: 'rgb(var(--forest-soft))', padding: '2px 9px', borderRadius: 999, textAlign: 'center', justifySelf: 'start' }}>{inv.status}</span>
              <button className="btn-ghost" style={{ fontSize: 11.5 }}>PDF</button>
            </li>
          ))}
        </ul>
      </Card>
    </>
  );
}

const inp = { width: '100%', fontSize: 13, padding: '8px 12px' };

window.SettingsView = SettingsView;
