/* Settings screen with tabbed admin */
const SettingsScreen = () => {
  const tabs = [
    { id: 'general',    name: 'General',                icon: 'settings' },
    { id: 'privacy',    name: 'Privacy & Anonymity',    icon: 'shield' },
    { id: 'scales',     name: 'Rating Scales',          icon: 'chart_bar' },
    { id: 'notify',     name: 'Notification Templates', icon: 'bell' },
    { id: 'roles',      name: 'Roles & Permissions',    icon: 'users' },
    { id: 'integrations', name: 'Integrations',         icon: 'layers' },
    { id: 'locale',     name: 'Localization',           icon: 'globe' },
    { id: 'audit',      name: 'Audit Logs',             icon: 'eye' },
  ];

  const [active, setActive] = React.useState('privacy');

  return (
    <div className="fade-in">
      <div className="page-header">
        <div>
          <h1>Settings</h1>
          <div className="subtitle">Configure how Pulse360 works for your organization.</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 24, alignItems: 'start' }}>
        <div className="card" style={{ padding: 8, position: 'sticky', top: 84 }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setActive(t.id)} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              width: '100%', padding: '9px 12px', borderRadius: 8,
              background: active === t.id ? 'var(--primary-50)' : 'transparent',
              color: active === t.id ? 'var(--primary-700)' : 'var(--ink-700)',
              fontSize: 13, fontWeight: active === t.id ? 700 : 500,
              cursor: 'pointer', textAlign: 'left'
            }}>
              <Icon name={t.icon} size={15}/>
              {t.name}
            </button>
          ))}
        </div>

        <div>
          {active === 'privacy' && <PrivacySettings/>}
          {active === 'roles' && <RolesSettings/>}
          {active === 'notify' && <NotificationsSettings/>}
          {active === 'scales' && <ScalesSettings/>}
          {active === 'general' && <GeneralSettings/>}
          {active === 'integrations' && <IntegrationsSettings/>}
          {active === 'locale' && <LocaleSettings/>}
          {active === 'audit' && <AuditSettings/>}
        </div>
      </div>
    </div>
  );
};

const SettingRow = ({ title, desc, control }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '16px 0', borderBottom: '1px solid var(--border)' }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink-900)' }}>{title}</div>
      {desc && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 4, lineHeight: 1.5, maxWidth: 540 }}>{desc}</div>}
    </div>
    <div>{control}</div>
  </div>
);

const PrivacySettings = () => {
  const [s, setS] = React.useState({
    anon: true, hideComments: false, mask: true, separate: true,
  });
  const [threshold, setThreshold] = React.useState(4);
  const toggle = (k) => setS(p => ({ ...p, [k]: !p[k] }));

  return (
    <>
      <div className="card" style={{ marginBottom: 20 }}>
        <div className="card-header">
          <div>
            <h3>Privacy & Anonymity</h3>
            <div className="desc">Rules that govern how identity and response data are stored, shown and protected.</div>
          </div>
          <Badge kind="active"><Icon name="shield" size={11}/> Enforced org-wide</Badge>
        </div>
        <div className="card-body" style={{ paddingTop: 0 }}>
          <SettingRow
            title="Enable anonymous feedback by default"
            desc="When on, individual responses are stored separately from rater identity and never shown directly in reports."
            control={<div className={`switch ${s.anon ? 'on' : ''}`} onClick={() => toggle('anon')}></div>}
          />
          <SettingRow
            title="Minimum rater threshold per group"
            desc="Rater groups with fewer responses than this number will be excluded from individual & team reports. This is the strongest anonymity protection."
            control={(
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 220 }}>
                <input type="range" min="2" max="10" value={threshold} onChange={e => setThreshold(+e.target.value)} style={{ flex: 1 }}/>
                <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--primary-600)', minWidth: 36, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>{threshold}</div>
              </div>
            )}
          />
          <SettingRow
            title="Hide individual comments in reports"
            desc="When on, only theme summaries are shown. Verbatim comments stay encrypted and accessible to HR Admin only."
            control={<div className={`switch ${s.hideComments ? 'on' : ''}`} onClick={() => toggle('hideComments')}></div>}
          />
          <SettingRow
            title="Mask identity-revealing comments"
            desc="Auto-detects names, team references and specific incidents in open comments. Flagged comments require HR review before publishing."
            control={<div className={`switch ${s.mask ? 'on' : ''}`} onClick={() => toggle('mask')}></div>}
          />
          <SettingRow
            title="Separate identity data from response data"
            desc="Responses are stored in a write-only collection. Rater identity ↔ response mapping requires a privileged key, audited on every read."
            control={<div className={`switch ${s.separate ? 'on' : ''}`} onClick={() => toggle('separate')}></div>}
          />
          <SettingRow
            title="Data retention period"
            desc="How long raw response data is retained. After this period, only aggregated outcomes remain."
            control={(
              <select className="select" style={{ width: 180 }}>
                <option>12 months</option>
                <option>24 months</option>
                <option selected>36 months</option>
                <option>60 months</option>
              </select>
            )}
          />
        </div>
      </div>

      <div className="alert alert-info">
        <Icon name="info" size={16}/>
        <div>
          <div className="alert-title">These settings cannot be changed mid-cycle.</div>
          <div className="alert-body">To preserve the integrity of the rater contract, anonymity rules are locked at cycle launch. Changes apply to all new cycles.</div>
        </div>
      </div>
    </>
  );
};

const RolesSettings = () => {
  const roles = [
    { name: 'HR Admin',          users: 4,  desc: 'Full administrative access — can launch cycles, view all data, manage settings.', tint: 'tint-indigo', perms: ['Cycles', 'Templates', 'Reports', 'Settings', 'Audit'] },
    { name: 'HR Business Partner', users: 12, desc: 'Departmental scope — manage cycles & reports for their assigned business units.', tint: 'tint-violet', perms: ['Cycles', 'Templates', 'Reports'] },
    { name: 'Manager',           users: 142, desc: 'Sees their team\'s aggregated results once anonymity threshold is met.', tint: 'tint-sky', perms: ['Team Results', 'My Evaluations'] },
    { name: 'Employee',          users: 1126, desc: 'Completes assigned surveys and views their own individual report.', tint: 'tint-mint', perms: ['My Evaluations', 'Own Report'] },
    { name: 'Executive Viewer',  users: 8,  desc: 'Org-wide dashboards & department analytics in read-only mode.', tint: 'tint-amber', perms: ['Dashboard', 'Department Analytics'] },
    { name: 'System Admin',      users: 2,  desc: 'Integrations, SSO, audit logs. No access to response data.', tint: 'tint-slate', perms: ['Integrations', 'Audit', 'Settings'] },
  ];

  return (
    <div className="card">
      <div className="card-header">
        <div>
          <h3>Roles & Permissions</h3>
          <div className="desc">Pulse360 ships with 6 roles. Custom roles can be created for complex org structures.</div>
        </div>
        <button className="btn btn-sm btn-primary"><Icon name="plus" size={13}/> New Role</button>
      </div>
      <div style={{ padding: '0 4px 8px' }}>
        {roles.map((r, i) => (
          <div key={r.name} style={{ display: 'flex', gap: 14, padding: 16, borderBottom: i < roles.length - 1 ? '1px solid var(--border)' : 'none', alignItems: 'flex-start' }}>
            <div className={`stat-icon ${r.tint}`} style={{ width: 38, height: 38, marginBottom: 0, flexShrink: 0 }}>
              <Icon name="users" size={16}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink-900)' }}>{r.name}</div>
                <Badge kind="soft">{r.users} users</Badge>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 4 }}>{r.desc}</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                {r.perms.map(p => (
                  <span key={p} className="badge badge-soft" style={{ fontSize: 10.5 }}><span className="dot" style={{ background: 'var(--primary-500)' }}></span>{p}</span>
                ))}
              </div>
            </div>
            <button className="btn btn-sm btn-secondary"><Icon name="edit" size={13}/> Edit</button>
          </div>
        ))}
      </div>
    </div>
  );
};

const NotificationsSettings = () => {
  const tmpls = [
    { name: 'Evaluation launch invitation', desc: 'Sent when a new cycle goes live and raters are invited.', channels: ['Email', 'Teams'], updated: 'May 02, 2026' },
    { name: 'Reminder notification',        desc: 'Sent 7 and 14 days into the cycle to raters with pending evaluations.', channels: ['Email', 'Teams', 'Slack'], updated: 'Apr 28, 2026' },
    { name: 'Overdue notification',         desc: 'Sent after the cycle close date for incomplete evaluations.', channels: ['Email'], updated: 'Apr 12, 2026' },
    { name: 'Cycle closed notification',    desc: 'Confirms a cycle has closed and indicates next steps.', channels: ['Email', 'Teams'], updated: 'May 04, 2026' },
    { name: 'Report available notification', desc: 'Tells employees and managers when their report is ready.', channels: ['Email'], updated: 'May 10, 2026' },
  ];

  return (
    <div className="card">
      <div className="card-header">
        <div>
          <h3>Notification Templates</h3>
          <div className="desc">Customize every email and chat message Pulse360 sends. Supports merge fields and multi-language variants.</div>
        </div>
        <button className="btn btn-sm btn-primary"><Icon name="plus" size={13}/> New template</button>
      </div>
      <div style={{ padding: 4 }}>
        {tmpls.map((t, i) => (
          <div key={t.name} style={{ display: 'flex', gap: 14, padding: 16, borderBottom: i < tmpls.length - 1 ? '1px solid var(--border)' : 'none', alignItems: 'flex-start' }}>
            <div className="stat-icon tint-violet" style={{ width: 38, height: 38, marginBottom: 0, flexShrink: 0 }}>
              <Icon name="message" size={15}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink-900)' }}>{t.name}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 4 }}>{t.desc}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 8, fontSize: 11, color: 'var(--ink-500)' }}>
                <span>Channels:</span>
                {t.channels.map(c => <span key={c} className="badge badge-soft" style={{ fontSize: 10 }}><span className="dot"></span>{c}</span>)}
                <span style={{ marginLeft: 'auto' }}>Updated {t.updated}</span>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn btn-icon btn-sm btn-ghost"><Icon name="eye" size={13}/></button>
              <button className="btn btn-icon btn-sm btn-ghost"><Icon name="edit" size={13}/></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

const ScalesSettings = () => (
  <div className="card">
    <div className="card-header">
      <div>
        <h3>Rating Scales</h3>
        <div className="desc">Configure the response scales available to question authors.</div>
      </div>
      <button className="btn btn-sm btn-primary"><Icon name="plus" size={13}/> New scale</button>
    </div>
    <div className="card-body" style={{ paddingTop: 0 }}>
      {[
        { name: '5-point Demonstration scale', items: ['Never Demonstrates','Rarely Demonstrates','Sometimes Demonstrates','Usually Demonstrates','Consistently Demonstrates'], hasNA: true },
        { name: '5-point Agreement scale', items: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'], hasNA: true },
        { name: '0–10 NPS', items: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'], hasNA: false },
        { name: 'Yes / No', items: ['No', 'Yes'], hasNA: true },
      ].map((sc, i) => (
        <div key={sc.name} style={{ padding: '16px 0', borderBottom: i < 3 ? '1px solid var(--border)' : 'none' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink-900)' }}>{sc.name}</div>
            <div style={{ display: 'flex', gap: 6 }}>
              {sc.hasNA && <Badge kind="info">N/A enabled</Badge>}
              <button className="btn btn-icon btn-sm btn-ghost"><Icon name="edit" size={13}/></button>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {sc.items.map((it, j) => (
              <span key={j} style={{ padding: '6px 10px', borderRadius: 8, background: 'var(--surface-alt)', border: '1px solid var(--border)', fontSize: 11.5, fontWeight: 500, color: 'var(--ink-700)' }}>
                <b style={{ marginRight: 6, color: 'var(--primary-600)' }}>{j + 1}</b>{it}
              </span>
            ))}
          </div>
        </div>
      ))}
    </div>
  </div>
);

const GeneralSettings = () => (
  <div className="card">
    <div className="card-header"><div><h3>General Settings</h3><div className="desc">Workspace-level defaults.</div></div></div>
    <div className="card-body" style={{ paddingTop: 0 }}>
      <SettingRow title="Organization name" desc="Shown in invitation emails and reports." control={<input className="input" defaultValue="Acme Corp." style={{ width: 240 }}/>}/>
      <SettingRow title="Cycle prefix" desc="Used to auto-generate cycle IDs." control={<input className="input" defaultValue="C-2026-" style={{ width: 160 }}/>}/>
      <SettingRow title="Default cycle window" desc="How long a new cycle stays open by default." control={<select className="select" style={{ width: 160 }}><option>14 days</option><option selected>21 days</option><option>28 days</option></select>}/>
      <SettingRow title="Working week" control={<select className="select" style={{ width: 200 }}><option selected>Monday – Friday</option><option>Sunday – Thursday</option></select>}/>
    </div>
  </div>
);

const IntegrationsSettings = () => {
  const items = [
    { name: 'Microsoft Teams',  status: 'Connected',  desc: 'Send notifications and surveys in Teams chats.', tint: 'tint-sky', icon: 'message' },
    { name: 'Slack',            status: 'Connected',  desc: 'Reminders and report links delivered in Slack.', tint: 'tint-violet', icon: 'message' },
    { name: 'SAP SuccessFactors', status: 'Connected', desc: 'Sync employees, departments and managers nightly.', tint: 'tint-indigo', icon: 'users' },
    { name: 'BambooHR',         status: 'Available',  desc: 'Bi-directional employee sync.', tint: 'tint-mint', icon: 'users' },
    { name: 'Workday',          status: 'Available',  desc: 'Pull employee data and push talent insights.', tint: 'tint-amber', icon: 'layers' },
    { name: 'Okta SSO',         status: 'Connected',  desc: 'SAML 2.0 sign-on for all employees.', tint: 'tint-slate', icon: 'shield' },
  ];
  return (
    <div className="grid grid-2">
      {items.map(it => (
        <div key={it.name} className="card" style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div className={`stat-icon ${it.tint}`} style={{ width: 40, height: 40, marginBottom: 0, flexShrink: 0 }}><Icon name={it.icon} size={18}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink-900)' }}>{it.name}</div>
                <Badge kind={it.status === 'Connected' ? 'active' : 'soft'}>{it.status}</Badge>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 4 }}>{it.desc}</div>
              <button className="btn btn-sm btn-secondary" style={{ marginTop: 12 }}>{it.status === 'Connected' ? 'Configure' : 'Connect'}</button>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

const LocaleSettings = () => (
  <div className="card">
    <div className="card-header"><div><h3>Localization</h3><div className="desc">Language and regional settings.</div></div></div>
    <div className="card-body" style={{ paddingTop: 0 }}>
      <SettingRow title="Workspace languages" desc="Languages enabled for survey templates and notifications."
        control={<div style={{ display: 'flex', gap: 6 }}><Badge kind="active">EN</Badge><Badge kind="active">TR</Badge><Badge kind="soft">+ Add language</Badge></div>}/>
      <SettingRow title="Default fallback language" control={<select className="select" style={{ width: 200 }}><option>English (EN)</option><option>Türkçe (TR)</option></select>}/>
      <SettingRow title="Date format" control={<select className="select" style={{ width: 200 }}><option>May 14, 2026</option><option>14.05.2026</option><option>2026-05-14</option></select>}/>
      <SettingRow title="Timezone" control={<select className="select" style={{ width: 240 }}><option>Europe/Istanbul (GMT+3)</option><option>Europe/London</option><option>America/New_York</option></select>}/>
    </div>
  </div>
);

const AuditSettings = () => {
  const logs = [
    { who: 'Defne Aydın',  action: 'Modified anonymity threshold from 3 → 4',     when: 'May 14, 2026 · 10:42', ip: '10.0.4.21', tint: 'tint-amber' },
    { who: 'System',       action: 'Auto-flagged anonymity risk on PMO/Digital',  when: 'May 14, 2026 · 09:18', ip: '–',         tint: 'tint-rose' },
    { who: 'Ergin Korkmaz',action: 'Published template Engineering Team Review',  when: 'May 13, 2026 · 17:04', ip: '10.0.4.88', tint: 'tint-violet' },
    { who: 'Selin Yıldız', action: 'Closed cycle Sales Org Upward Feedback',      when: 'May 13, 2026 · 14:22', ip: '10.0.4.12', tint: 'tint-emerald' },
    { who: 'HR Ops',       action: 'Sent reminders to 184 raters (Engineering)',  when: 'May 12, 2026 · 09:00', ip: '–',         tint: 'tint-sky' },
    { who: 'Defne Aydın',  action: 'Created cycle Q2 2026 Leadership 360',        when: 'May 02, 2026 · 11:12', ip: '10.0.4.21', tint: 'tint-indigo' },
  ];
  return (
    <div className="card">
      <div className="card-header">
        <div>
          <h3>Audit Logs</h3>
          <div className="desc">Tamper-evident log of every administrative action.</div>
        </div>
        <button className="btn btn-sm btn-secondary"><Icon name="download" size={13}/> Export</button>
      </div>
      <table className="table">
        <thead><tr><th>Actor</th><th>Action</th><th>When</th><th>IP</th></tr></thead>
        <tbody>
          {logs.map((l, i) => (
            <tr key={i}>
              <td>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div className={`stat-icon ${l.tint}`} style={{ width: 28, height: 28, marginBottom: 0, borderRadius: 7 }}>
                    <Icon name="user" size={13}/>
                  </div>
                  <span className="cell-emph">{l.who}</span>
                </div>
              </td>
              <td>{l.action}</td>
              <td style={{ color: 'var(--ink-500)', fontFamily: 'var(--font-mono)', fontSize: 11.5 }}>{l.when}</td>
              <td style={{ color: 'var(--ink-500)', fontFamily: 'var(--font-mono)', fontSize: 11.5 }}>{l.ip}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

window.SettingsScreen = SettingsScreen;
