/* ============================================================
   ZERO — Settings. window.Screens.Settings
   ============================================================ */
(function () {
  const { useState } = React;
  const I = window.Icon;
  const { Card, SectionHead, Toggle, Badge } = window.UI;
  const D = window.DATA;

  function Settings() {
    const [section, setSection] = useState('Integrações');
    const [ints, setInts] = useState(() => D.integrations.map(i => ({ ...i })));
    const [theme, setTheme] = useState('Meia-noite');
    const [prefs, setPrefs] = useState({ autonomy: true, notify: true, weekly: true, approve: false });
    const [revealed, setRevealed] = useState(false);

    const SECTIONS = [
      ['Integrações', 'link'], ['Chaves de API', 'key'], ['Permissões', 'shield'],
      ['Aparência', 'palette'], ['Preferências', 'cog'],
    ];

    return (
      <div className="page" style={{ maxWidth: 1100 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '210px 1fr', gap: 26, alignItems: 'start' }}>
          {/* section nav */}
          <div style={{ position: 'sticky', top: 16, display: 'flex', flexDirection: 'column', gap: 3 }}>
            {SECTIONS.map(([s, ic]) => {
              const Ic = I[ic]; const on = section === s;
              return (
                <button key={s} onClick={() => setSection(s)} className="row gap10"
                  style={{ padding: '9px 12px', borderRadius: 9, cursor: 'pointer', textAlign: 'left', border: 'none',
                    background: on ? 'var(--bg-2)' : 'transparent', color: on ? 'var(--tx-0)' : 'var(--tx-2)', fontSize: 13, fontWeight: on ? 700 : 500 }}>
                  <span style={{ color: on ? 'var(--violet-2)' : 'inherit' }}><Ic w={16} /></span>{s}
                </button>
              );
            })}
          </div>

          {/* content */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {section === 'Integrações' && (
              <Card style={{ padding: 22 }}>
                <SectionHead icon="link" title="Integrações" sub="Conecte as ferramentas que sua equipe de IA opera" />
                <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  {ints.map((it, i) => (
                    <div key={it.name} className="row gap12" style={{ padding: 14, borderRadius: 12, background: 'var(--bg-2)', border: '1px solid var(--line)' }}>
                      <span className="avatar" style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--bg-3)', color: it.hue, border: '1px solid var(--line)', fontSize: 12 }}>{it.glyph}</span>
                      <div className="grow">
                        <div style={{ fontWeight: 700, fontSize: 13.5 }}>{it.name}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>{it.desc}</div>
                      </div>
                      <Toggle on={it.on} onChange={v => setInts(arr => arr.map((x, j) => j === i ? { ...x, on: v } : x))} />
                    </div>
                  ))}
                </div>
              </Card>
            )}

            {section === 'Chaves de API' && (
              <Card style={{ padding: 22 }}>
                <SectionHead icon="key" title="Chaves de API" sub="Chaves fictícias — só frontend, nada é armazenado"
                  action={<button className="btn btn-primary btn-sm"><I.plus w={14} /> Criar chave</button>} />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {[['Produção', 'sk_live_••••••••••••8f2a', 'var(--green)'],['Desenvolvimento', 'sk_test_••••••••••••1c9b', 'var(--teal)'],['Segredo de webhook', 'whsec_••••••••••••44de', 'var(--amber)']].map(([n, k, c]) => (
                    <div key={n} className="row gap12" style={{ padding: 14, borderRadius: 12, background: 'var(--bg-2)', border: '1px solid var(--line)' }}>
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: c }} />
                      <div className="grow">
                        <div style={{ fontWeight: 700, fontSize: 13 }}>{n}</div>
                        <div className="mono" style={{ fontSize: 12, color: 'var(--tx-2)', marginTop: 2 }}>{revealed ? k.replace(/•/g, '0') : k}</div>
                      </div>
                      <button onClick={() => setRevealed(r => !r)} className="btn btn-icon btn-sm"><I.eye w={15} /></button>
                      <button className="btn btn-sm"><I.link w={14} /> Copiar</button>
                    </div>
                  ))}
                </div>
              </Card>
            )}

            {section === 'Permissões' && (
              <Card style={{ padding: 22 }}>
                <SectionHead icon="shield" title="Permissões dos Agentes" sub="O que sua equipe pode fazer sem pedir" />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {[['Subir código para produção', 'Forge', true],['Gastar até R$ 5 mil/dia em anúncios', 'Nova', true],['Reembolsar clientes até R$ 100', 'Echo', true],['Assinar contratos', 'Vega', false],['Alterar preços', 'Atlas', false],['Escalar a infraestrutura', 'Orbit', true]].map(([t, who, def], i) => (
                    <PermRow key={i} title={t} who={who} def={def} />
                  ))}
                </div>
              </Card>
            )}

            {section === 'Aparência' && (
              <Card style={{ padding: 22 }}>
                <SectionHead icon="palette" title="Aparência" sub="Tema e cor de destaque" />
                <div className="grid" style={{ gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginBottom: 20 }}>
                  {[['Meia-noite', 'oklch(0.16 0.013 265)', 'var(--violet)'],['Carbono', 'oklch(0.15 0 0)', 'var(--teal)'],['Aurora', 'oklch(0.17 0.02 285)', 'var(--rose)']].map(([n, bg, ac]) => (
                    <button key={n} onClick={() => setTheme(n)} style={{ padding: 0, borderRadius: 12, overflow: 'hidden', cursor: 'pointer',
                      border: '2px solid ' + (theme === n ? 'var(--violet-2)' : 'var(--line)'), background: 'transparent' }}>
                      <div style={{ height: 64, background: bg, position: 'relative' }}>
                        <span style={{ position: 'absolute', bottom: 10, left: 10, width: 22, height: 22, borderRadius: 6, background: ac }} />
                        <span style={{ position: 'absolute', bottom: 10, left: 38, right: 10, height: 8, borderRadius: 4, background: 'oklch(1 0 0 /.12)' }} />
                      </div>
                      <div className="row between" style={{ padding: '9px 12px' }}>
                        <span style={{ fontSize: 12.5, fontWeight: 600 }}>{n}</span>
                        {theme === n && <span style={{ color: 'var(--violet-2)' }}><I.check w={15} /></span>}
                      </div>
                    </button>
                  ))}
                </div>
                <div style={{ fontSize: 12, color: 'var(--tx-3)' }}>Cor de destaque</div>
                <div className="row gap8" style={{ marginTop: 8 }}>
                  {['var(--violet)','var(--teal)','var(--blue)','var(--green)','var(--rose)','var(--amber)'].map((c, i) => (
                    <span key={i} style={{ width: 28, height: 28, borderRadius: 8, background: c, cursor: 'pointer',
                      border: i === 0 ? '2px solid white' : '2px solid transparent', boxShadow: i===0?'0 0 0 1px var(--bg-0)':'none' }} />
                  ))}
                </div>
              </Card>
            )}

            {section === 'Preferências' && (
              <Card style={{ padding: 22 }}>
                <SectionHead icon="cog" title="Preferências" />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {[['autonomy', 'Modo de autonomia total', 'Agentes agem sem aprovação por tarefa'],
                    ['approve', 'Exigir aprovação para ações de alto impacto', 'Deploys, pagamentos e contratos'],
                    ['notify', 'Notificações push', 'Alertas em tempo real sobre os agentes'],
                    ['weekly', 'Relatório semanal do founder', 'Atlas envia um resumo toda segunda']].map(([k, t, d]) => (
                    <div key={k} className="row between" style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
                      <div><div style={{ fontWeight: 600, fontSize: 13.5 }}>{t}</div><div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>{d}</div></div>
                      <Toggle on={prefs[k]} onChange={v => setPrefs(p => ({ ...p, [k]: v }))} />
                    </div>
                  ))}
                </div>
              </Card>
            )}
          </div>
        </div>
      </div>
    );
  }

  function PermRow({ title, who, def }) {
    const [on, setOn] = useState(def);
    return (
      <div className="row between" style={{ padding: '13px 0', borderBottom: '1px solid var(--line)' }}>
        <div className="row gap10">
          <span style={{ color: on ? 'var(--green)' : 'var(--tx-3)' }}>{on ? <I.checkCircle w={17} /> : <I.shield w={17} />}</span>
          <div><div style={{ fontWeight: 600, fontSize: 13.5 }}>{title}</div>
            <div style={{ fontSize: 11, color: 'var(--tx-2)' }}>Concedido a {who}</div></div>
        </div>
        <Toggle on={on} onChange={setOn} />
      </div>
    );
  }

  window.Screens = window.Screens || {};
  window.Screens.Settings = Settings;
})();
