// Settings — connectors (primary), workspace, members, SSO, notifications.

const SETTINGS_SECTIONS = [
  { id: 'connectors',    label: 'Connectors',    icon: 'plug',   desc: 'Data sources — databases, SaaS, files, MCP' },
  { id: 'workspace',     label: 'Workspace',     icon: 'gear',   desc: 'Name, locale, fiscal year, language' },
  { id: 'members',       label: 'Members & Roles',icon: 'users', desc: 'Team, roles, access' },
  { id: 'sso',           label: 'SSO & Auth',    icon: 'shield', desc: 'Okta, Azure AD, SAML, MFA' },
  { id: 'whatsapp',      label: 'WhatsApp',      icon: 'whatsapp', desc: 'Pairing, members, group bots' },
  { id: 'notifications', label: 'Notifications', icon: 'mail',   desc: 'Alerts, approval, channels' },
];

const STATUS_PILL = {
  connected: { label: 'Connected', tone: 'var(--ok)',              bg: 'var(--ok-soft)' },
  syncing:   { label: 'Syncing',   tone: 'oklch(0.5 0.16 250)',    bg: 'oklch(0.96 0.04 250)' },
  error:     { label: 'Needs re-auth', tone: 'var(--err)',         bg: 'var(--err-soft)' },
  available: { label: 'Available', tone: 'var(--ink-4)',           bg: 'var(--bg-sunken)' },
};

const ScreenSettings = ({ setRoute, openWizard }) => {
  const [activeSection, setActiveSection] = React.useState('connectors');

  return (
    <div className="nx-page" style={{ padding: '24px 32px 40px', maxWidth: 1080, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em' }}>Settings</h1>
        <div style={{ marginTop: 4, color: 'var(--ink-3)', fontSize: 13 }}>
          Connectors, workspace, members, auth, WhatsApp, dan notifications.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 20 }}>
        {/* Section nav */}
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {SETTINGS_SECTIONS.map(s => (
            <button key={s.id} onClick={() => setActiveSection(s.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px', textAlign: 'left', border: 0, borderRadius: 7,
                background: activeSection === s.id ? 'var(--bg-hover)' : 'transparent',
                color: activeSection === s.id ? 'var(--ink)' : 'var(--ink-3)',
                fontSize: 13, fontWeight: activeSection === s.id ? 550 : 450,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>
              <Icon name={s.icon} size={14} />
              {s.label}
            </button>
          ))}
        </nav>

        <div>
          {activeSection === 'connectors' && <ConnectorsPanel openWizard={openWizard} setRoute={setRoute} />}

          {activeSection === 'workspace' && (
            <div className="nx-card" style={{ padding: 18 }}>
              <SectionTitle title="Workspace" desc="Basic info about your NalarX workspace." />
              <SettingRow label="Workspace name" value="BankCorp" />
              <SettingRow label="Industry vertical" value="Banking & financial services" />
              <SettingRow label="Default language" value="Bahasa Indonesia" />
              <SettingRow label="Currency" value="IDR · Rupiah" />
              <SettingRow label="Fiscal year start" value="January" />
              <SettingRow label="Timezone" value="Asia/Jakarta (GMT+7)" />
            </div>
          )}

          {activeSection === 'members' && (
            <div className="nx-card" style={{ padding: 18 }}>
              <SectionTitle title="Members & Roles" desc="Workspace members and their roles (Admin / Head / Staff)." />
              <SettingRow label="Total members" value="233 active" tag="3 pending" tagKind="warn" />
              <SettingRow label="Admins" value="4" />
              <SettingRow label="Department Heads" value="11" />
              <SettingRow label="Staff" value="218" />
              <div style={{ marginTop: 14, display: 'flex', gap: 8 }}>
                <button className="nx-btn accent sm"><Icon name="plus" size={12} /> Invite member</button>
                <button onClick={() => setRoute && setRoute('people')} className="nx-btn sm">
                  Open People <Icon name="arrow-right" size={12} />
                </button>
              </div>
            </div>
          )}

          {activeSection === 'sso' && (
            <div className="nx-card" style={{ padding: 18 }}>
              <SectionTitle title="SSO & Authentication" desc="Single sign-on provider, MFA policy, dan SCIM provisioning." />
              <SettingRow label="Active provider" value="Okta" tag="Connected" tagKind="ok" />
              <SettingRow label="Auto-provision via SCIM" value="On" />
              <SettingRow label="MFA enforcement" value="Required for admins" />
              <SettingRow label="Session timeout" value="8 hours" />
              <div style={{ marginTop: 14 }}>
                <button onClick={() => setRoute && setRoute('sso')} className="nx-btn sm">
                  <Icon name="gear" size={12} /> Configure providers
                </button>
              </div>
            </div>
          )}

          {activeSection === 'whatsapp' && <WhatsAppPanel />}

          {activeSection === 'notifications' && <NotificationsPanel />}
        </div>
      </div>
    </div>
  );
};

// ── Connectors panel — the real, mandatory one ──
const ConnectorsPanel = ({ openWizard, setRoute }) => {
  const connectors = (window.NX_DATA && window.NX_DATA.CONNECTORS) || [];
  const connected = connectors.filter(c => c.status === 'connected');
  const syncing = connectors.filter(c => c.status === 'syncing');
  const errored = connectors.filter(c => c.status === 'error');

  // Group connected/syncing/error by category (hide the long "available" catalog here)
  const live = connectors.filter(c => c.status !== 'available');
  const cats = [...new Set(live.map(c => c.cat))];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Summary strip */}
      <div className="nx-card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 18 }}>
        <SummaryStat n={connected.length} label="Connected" tone="var(--ok)" />
        <SummaryStat n={syncing.length} label="Syncing" tone="oklch(0.5 0.16 250)" />
        <SummaryStat n={errored.length} label="Needs re-auth" tone="var(--err)" />
        <div style={{ flex: 1 }} />
        <button onClick={openWizard} className="nx-btn accent sm"><Icon name="plus" size={12} /> Add connector</button>
      </div>

      {/* Connected sources grouped by category */}
      {cats.map(cat => (
        <div key={cat} className="nx-card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{
            padding: '10px 16px', borderBottom: '0.5px solid var(--line)',
            fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--ink-4)',
          }}>{cat}</div>
          {live.filter(c => c.cat === cat).map((c, i) => {
            const pill = STATUS_PILL[c.status] || STATUS_PILL.available;
            return (
              <div key={c.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 16px',
                borderTop: i > 0 ? '0.5px solid var(--line)' : 'none',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8, flexShrink: 0,
                  background: c.tone, color: 'white',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 12, fontWeight: 700,
                }}>{c.mono}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{c.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>
                    {c.records ? c.records : '—'}{c.synced ? ' · synced ' + c.synced : ''}
                  </div>
                </div>
                <span className="nx-chip" style={{ height: 20, fontSize: 11, background: pill.bg, color: pill.tone, borderColor: 'transparent' }}>
                  {c.status === 'connected' && <span className="nx-pulse-dot" />}
                  {pill.label}
                </span>
                <button className="nx-btn sm ghost" title="Manage"><Icon name="menu-dots" size={13} /></button>
              </div>
            );
          })}
        </div>
      ))}

      <div style={{ fontSize: 11.5, color: 'var(--ink-4)', padding: '0 4px', lineHeight: 1.5 }}>
        Connectors adalah fondasi NalarX — agent cuma bisa jawab dari data yang tersambung di sini.
        Klik <b>Add connector</b> untuk sambung sumber baru (SaaS / Database / API · MCP).
      </div>
    </div>
  );
};

const SummaryStat = ({ n, label, tone }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
    <span style={{ fontSize: 18, fontWeight: 600, color: tone }}>{n}</span>
    <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>{label}</span>
  </div>
);

// ── WhatsApp panel — channel config (pairing, members, group bots) ──
const WA_GROUPS = [
  { name: 'Finance Leadership', members: 6,  scope: 'Finance agent · read-only', status: 'active' },
  { name: 'Risk War Room',      members: 12, scope: 'Fraud agent · alerts + recall', status: 'active' },
  { name: 'Procurement Daily',  members: 9,  scope: 'Procurement agent · digest', status: 'paused' },
];

const WhatsAppPanel = () => {
  const [approveWa, setApproveWa] = React.useState(true);
  const [voiceWa, setVoiceWa] = React.useState(true);
  const [attachWa, setAttachWa] = React.useState(false);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Pairing */}
      <div className="nx-card" style={{ padding: 18 }}>
        <SectionTitle title="WhatsApp Business" desc="Nomor bot yang dipakai user buat tanya & nerima alert." />
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 11, flexShrink: 0,
            background: 'oklch(0.62 0.17 150)', color: 'white',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="whatsapp" size={24} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>+62 811-1900-220</div>
            <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>Paired Mar 2026 · WhatsApp Business API</div>
          </div>
          <span className="nx-chip" style={{ height: 22, fontSize: 11.5, background: 'var(--ok-soft)', color: 'var(--ok)', borderColor: 'transparent' }}>
            <span className="nx-pulse-dot" /> Connected
          </span>
          <button className="nx-btn sm"><Icon name="refresh" size={12} /> Re-pair (QR)</button>
        </div>
      </div>

      {/* Linked members */}
      <div className="nx-card" style={{ padding: 18 }}>
        <SectionTitle title="Linked members" desc="User yang nomornya ke-link — bisa tanya 1:1 & nerima alert di WA." />
        <SettingRow label="Linked numbers" value="184 of 233 members" tag="49 not linked" tagKind="warn" />
        <SettingRow label="Auto-link via SCIM" value="On — pakai nomor dari Okta profile" />
        <div style={{ marginTop: 14, display: 'flex', gap: 8 }}>
          <button className="nx-btn accent sm"><Icon name="send" size={12} /> Kirim link-invite</button>
          <button className="nx-btn sm">Lihat unlinked</button>
        </div>
      </div>

      {/* Group bots */}
      <div className="nx-card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '14px 18px', borderBottom: '0.5px solid var(--line)', display: 'flex', alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>Group bots</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>Grup WA yang ada Nalar bot — scope agent dibatasi per grup.</div>
          </div>
          <button className="nx-btn accent sm"><Icon name="plus" size={12} /> Add to group</button>
        </div>
        {WA_GROUPS.map((g, i) => (
          <div key={g.name} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '12px 18px',
            borderTop: i > 0 ? '0.5px solid var(--line)' : 'none',
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8, flexShrink: 0,
              background: 'var(--bg-sunken)', color: 'var(--ink-3)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="users" size={15} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{g.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{g.members} members · {g.scope}</div>
            </div>
            <span className="nx-chip" style={{ height: 20, fontSize: 11, background: g.status === 'active' ? 'var(--ok-soft)' : 'var(--bg-sunken)', color: g.status === 'active' ? 'var(--ok)' : 'var(--ink-4)', borderColor: 'transparent' }}>
              {g.status === 'active' ? 'Active' : 'Paused'}
            </span>
            <button className="nx-btn sm ghost" title="Manage"><Icon name="menu-dots" size={13} /></button>
          </div>
        ))}
      </div>

      {/* WA capabilities */}
      <div className="nx-card" style={{ padding: 18 }}>
        <SectionTitle title="What users can do over WhatsApp" desc="Batasin aksi yang boleh lewat WA (di luar dashboard)." />
        <WaToggleRow label="Approve cross-dept request via WA" desc="Head bisa approve/reject langsung dari chat WA" on={approveWa} onToggle={() => setApproveWa(v => !v)} />
        <WaToggleRow label="Voice note query" desc="Transcribe voice note jadi pertanyaan" on={voiceWa} onToggle={() => setVoiceWa(v => !v)} />
        <WaToggleRow label="Terima attachment (PDF/Excel/foto)" desc="User boleh kirim file buat dianalisa" on={attachWa} onToggle={() => setAttachWa(v => !v)} />
      </div>
    </div>
  );
};

const WaToggleRow = ({ label, desc, on, onToggle }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 12,
    padding: '12px 0', borderTop: '0.5px solid var(--line)',
  }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500 }}>{label}</div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{desc}</div>
    </div>
    <button onClick={onToggle}
      style={{
        width: 34, height: 20, borderRadius: 999, border: 0, cursor: 'pointer',
        background: on ? 'var(--accent)' : 'var(--bg-hover)',
        position: 'relative', transition: 'background .15s', flexShrink: 0,
      }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 16 : 2,
        width: 16, height: 16, borderRadius: '50%', background: 'white',
        transition: 'left .15s', boxShadow: '0 1px 2px rgba(0,0,0,.2)',
      }} />
    </button>
  </div>
);

// ── Notifications panel — channel toggles per category ──
const NOTIF_ROWS = [
  { id: 'alerts',     label: 'Live Artifact alerts', desc: 'Watcher trigger, anomaly, scheduled digest' },
  { id: 'approval',   label: 'Cross-dept approval',  desc: 'Request akses data masuk' },
  { id: 'correction', label: 'Correction review',    desc: 'Staff koreksi butuh approval' },
  { id: 'mention',    label: 'Group mention',        desc: '@mention di WA group bot' },
];
const NotificationsPanel = () => {
  const [state, setState] = React.useState({
    alerts:     { dash: true,  wa: true,  email: false },
    approval:   { dash: true,  wa: true,  email: true  },
    correction: { dash: true,  wa: false, email: true  },
    mention:    { dash: false, wa: true,  email: false },
  });
  const toggle = (row, ch) => setState(s => ({ ...s, [row]: { ...s[row], [ch]: !s[row][ch] } }));

  return (
    <div className="nx-card" style={{ padding: 18 }}>
      <SectionTitle title="Notifications" desc="Pilih channel per kategori notifikasi." />
      {/* Header */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 56px 56px 56px', alignItems: 'center', gap: 8, padding: '0 0 8px', fontSize: 11, color: 'var(--ink-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
        <span>Category</span>
        <span style={{ textAlign: 'center' }}>Dash</span>
        <span style={{ textAlign: 'center' }}>WA</span>
        <span style={{ textAlign: 'center' }}>Email</span>
      </div>
      {NOTIF_ROWS.map(r => (
        <div key={r.id} style={{
          display: 'grid', gridTemplateColumns: '1fr 56px 56px 56px', alignItems: 'center', gap: 8,
          padding: '11px 0', borderTop: '0.5px solid var(--line)',
        }}>
          <div>
            <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500 }}>{r.label}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{r.desc}</div>
          </div>
          {['dash', 'wa', 'email'].map(ch => {
            const on = state[r.id][ch];
            return (
              <button key={ch} onClick={() => toggle(r.id, ch)}
                style={{
                  justifySelf: 'center',
                  width: 34, height: 20, borderRadius: 999, border: 0, cursor: 'pointer',
                  background: on ? 'var(--accent)' : 'var(--bg-hover)',
                  position: 'relative', transition: 'background .15s',
                }}>
                <span style={{
                  position: 'absolute', top: 2, left: on ? 16 : 2,
                  width: 16, height: 16, borderRadius: '50%', background: 'white',
                  transition: 'left .15s', boxShadow: '0 1px 2px rgba(0,0,0,.2)',
                }} />
              </button>
            );
          })}
        </div>
      ))}
    </div>
  );
};

const SectionTitle = ({ title, desc }) => (
  <div style={{ marginBottom: 16 }}>
    <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{title}</div>
    <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{desc}</div>
  </div>
);

const SettingRow = ({ label, value, tag, tagKind = 'ok' }) => (
  <div style={{
    display: 'grid', gridTemplateColumns: '180px 1fr auto', alignItems: 'center', gap: 12,
    padding: '11px 0', borderTop: '0.5px solid var(--line)',
  }}>
    <span style={{ fontSize: 12.5, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</span>
    <span style={{ fontSize: 13, color: 'var(--ink)' }}>{value}</span>
    {tag && (
      <span className={`nx-chip ${tagKind}`} style={{ height: 20, fontSize: 11 }}>{tag}</span>
    )}
  </div>
);

window.ScreenSettings = ScreenSettings;
