// src/screen-supporting.jsx — §8 Doctor, Catálogo, Ajustes (lighter polish than the main 3).

// ─────────────────────────────────────────────────────────────
// CATALOG
// ─────────────────────────────────────────────────────────────
function CatalogScreen() {
  const { state, pullRulesets, pushToast } = useAxStore();
  const { navigate } = useHashRoute();
  const installed  = state.rulesets.filter((r) => r.installed);
  const available  = state.rulesets.filter((r) => !r.installed);

  const onPull = () => {
    const n = pullRulesets();
    if (n > 0) pushToast({ kind: 'success', title: 'Catálogo actualizado', message: `Piixi ahora reconoce ${n} formatos más.` });
    else pushToast({ kind: 'info', message: 'Tu catálogo ya está al día.' });
  };

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        eyebrow="Catálogo · UDEE"
        title="Reglas de extracción"
        subtitle="Cada regla le enseña a Piixi a leer un formato específico de una aseguradora. El catálogo se descarga del repo público; nada se sube."
        actions={<AxButton variant="primary" icon="refresh" onClick={onPull}>Buscar reglas nuevas</AxButton>}
      />
      <div style={{ flex: 1, padding: '24px 32px 48px', maxWidth: 1200, display: 'flex', flexDirection: 'column', gap: 22 }}>
        <RulesetSection title="Instaladas" count={installed.length} items={installed} state="installed"/>
        {available.length > 0 ? <RulesetSection title="Disponibles para instalar" count={available.length} items={available} state="available" onPull={onPull}/> : null}
      </div>
    </div>
  );
}

function RulesetSection({ title, count, items, state, onPull }) {
  const groups = useMemo(() => {
    const out = {};
    for (const r of items) {
      out[r.carrier] = out[r.carrier] || [];
      out[r.carrier].push(r);
    }
    return out;
  }, [items]);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <h2 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>
          {title} <span className="ax-mono" style={{ color: 'var(--ax-fg-faint)', marginLeft: 6 }}>{count}</span>
        </h2>
      </div>
      <div className="ax-card">
        {Object.entries(groups).map(([carrierId, list], gi) => {
          const c = AdmixData.carrierById(carrierId);
          return (
            <div key={carrierId} style={{ borderTop: gi > 0 ? '1px solid var(--ax-border)' : 'none' }}>
              <div style={{ padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--ax-bg-1)' }}>
                <AxCarrierAvatar id={carrierId} size={18}/>
                <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>{c.name}</span>
                <span className="ax-mono" style={{ fontSize: 11, color: 'var(--ax-fg-faint)', marginLeft: 4 }}>· {list.length}</span>
              </div>
              {list.map((r) => (
                <div key={r.id} style={{
                  padding: '10px 16px', display: 'grid', gridTemplateColumns: '24px 1fr 90px 140px 110px auto', gap: 14,
                  alignItems: 'center', borderTop: '1px solid var(--ax-border)', fontSize: 13,
                }}>
                  <AxIcon name="tag" size={14} style={{ color: 'var(--ax-fg-muted)' }}/>
                  <div>
                    <div style={{ color: 'var(--ax-fg-strong)' }}>{r.producto}</div>
                    <div className="ax-mono" style={{ fontSize: 10, color: 'var(--ax-fg-faint)' }}>{r.id}</div>
                  </div>
                  <AxRamoTag code={r.ramo}/>
                  <span style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>{AdmixData.formatDateES(r.updatedAt)}</span>
                  <span className="ax-mono" style={{ fontSize: 11, color: 'var(--ax-fg-muted)' }}>v{r.version}</span>
                  {state === 'installed' ? (
                    <span style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
                      <AxPill tone="neutral">{r.matches} pólizas</AxPill>
                      <AxPill tone="accent" dot>activa</AxPill>
                    </span>
                  ) : (
                    <span style={{ display: 'flex', justifyContent: 'flex-end' }}>
                      <AxButton size="sm" variant="secondary" onClick={onPull}>Instalar</AxButton>
                    </span>
                  )}
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AJUSTES (covers settings + doctor)
// ─────────────────────────────────────────────────────────────
function SettingsScreen() {
  const { match } = useHashRoute();
  if (match('/ajustes/doctor')) return <DoctorScreen/>;
  return <SettingsHome/>;
}

function SettingsHome() {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const cuenta = { id: 'cuenta', label: 'Cuenta y agencia', icon: 'user',
    items: [
      { label: 'Tu nombre', value: state.user.name },
      { label: 'Correo',    value: state.user.email },
      { label: 'Agencia',   value: state.user.orgName },
      { label: 'Idioma',    value: 'Español (México)' },
    ] };
  const catalogo = { id: 'catalogo', label: 'Catálogo (UDEE)', icon: 'tag',
    items: [
      { label: 'Auto-update',                 value: 'Activado',    pill: { tone: 'accent', label: 'on' } },
      { label: 'Enviar muestras al catálogo', value: 'Desactivado', pill: { tone: 'ghost',  label: 'off' } },
    ] };
  const privacidad = { id: 'privacidad', label: 'Privacidad y datos', icon: 'shield',
    items: [
      { label: 'Modo local',         value: 'Forzado', pill: { tone: 'accent', label: 'On' } },
      { label: 'Encriptación local', value: 'AES-256, llave en keychain' },
      { label: 'Telemetría anónima', value: 'Desactivada', pill: { tone: 'ghost', label: 'off' } },
    ] };
  const avanzado = { id: 'avanzado', label: 'Avanzado', icon: 'settings',
    items: [
      { label: 'Base de datos', value: '~/.piixi/piixi.db · 4.2 MB' },
      { label: 'Versión',       value: 'piixi v1.0.0 (build 4e2c)' },
      { label: 'Diagnóstico',   value: 'Todos los chequeos pasan', linkTo: '/ajustes/doctor' },
    ] };
  return (
    <div style={{ flex: 1, overflow: 'auto' }}>
      <AxPageHeader eyebrow="Configuración" title="Ajustes" subtitle="Tu instalación de Piixi corre solamente en este equipo. Estos valores no se sincronizan."/>
      <div style={{ padding: '24px 32px 48px', maxWidth: 900, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <SettingsGroupCard group={cuenta} navigate={navigate}/>
        <ConnectorsCard/>
        <SettingsGroupCard group={catalogo} navigate={navigate}/>
        <SettingsGroupCard group={privacidad} navigate={navigate}/>
        <SettingsGroupCard group={avanzado} navigate={navigate}/>
        <DangerZone/>
      </div>
    </div>
  );
}

// Tarjeta genérica de ajustes: encabezado + filas (label / value / pill / link).
function SettingsGroupCard({ group: g, navigate }) {
  return (
    <div className="ax-card">
      <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <AxIcon name={g.icon} size={15} style={{ color: 'var(--ax-fg-muted)' }}/>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>{g.label}</h3>
      </div>
      <div>
        {g.items.map((it, i) => (
          <button key={i}
            onClick={() => it.linkTo && navigate(it.linkTo)}
            style={{
              appearance: 'none', background: 'transparent', border: 0,
              width: '100%', textAlign: 'left', padding: '12px 18px',
              borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
              display: 'grid', gridTemplateColumns: '180px 1fr auto', gap: 14, alignItems: 'center',
              color: 'inherit', cursor: 'default', fontSize: 13,
            }}
            onMouseEnter={(e) => { if (it.linkTo) e.currentTarget.style.background = 'var(--ax-bg-3)'; }}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
          >
            <span style={{ color: 'var(--ax-fg-muted)' }}>{it.label}</span>
            <span style={{ color: 'var(--ax-fg-strong)' }}>{it.value}</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {it.pill ? <AxPill tone={it.pill.tone} dot={it.pill.tone === 'accent'}>{it.pill.label}</AxPill> : null}
              {it.linkTo ? <AxIcon name="chevron-right" size={12} style={{ color: 'var(--ax-fg-faint)' }}/> : null}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}

// CONECTORES — de dónde Piixi LEE pólizas y por dónde ENVÍA avisos. Reemplaza la vieja
// "Fuentes de pólizas" (que solo mostraba una carpeta). Cada conector maneja N
// carpetas/cuentas. Mockup: estado + acción Conectar/Gestionar (cableado real luego).
const CONNECTORS = [
  { id: 'gdrive',   name: 'Google Drive', icon: 'drive', kind: 'Fuente de pólizas', status: 'connected', detail: '2 carpetas conectadas' },
  { id: 'onedrive', name: 'OneDrive',     icon: 'cloud', kind: 'Fuente de pólizas', status: 'off' },
  { id: 'gmail',    name: 'Gmail',        icon: 'mail',  kind: 'Correo',            status: 'off' },
  { id: 'whatsapp', name: 'WhatsApp',     icon: 'phone', kind: 'Mensajería',        status: 'off' },
  { id: 'telegram', name: 'Telegram',     icon: 'bell',  kind: 'Mensajería',        status: 'off' },
];

// Glyphs de marca: simple-icons (CC0, single-path → respeta la regla monocromática del
// design system) en color de marca. OneDrive no está en simple-icons (política de
// Microsoft) → nube en azul MS como aproximación. viewBox 0 0 24 24, fill = color marca.
const CONNECTOR_ICONS = {
  gdrive:   { color: '#4285F4', path: 'M12.01 1.485c-2.082 0-3.754.02-3.743.047.01.02 1.708 3.001 3.774 6.62l3.76 6.574h3.76c2.081 0 3.753-.02 3.742-.047-.005-.02-1.708-3.001-3.775-6.62l-3.76-6.574zm-4.76 1.73a789.828 789.861 0 0 0-3.63 6.319L0 15.868l1.89 3.298 1.885 3.297 3.62-6.335 3.618-6.33-1.88-3.287C8.1 4.704 7.255 3.22 7.25 3.214zm2.259 12.653-.203.348c-.114.198-.96 1.672-1.88 3.287a423.93 423.948 0 0 1-1.698 2.97c-.01.026 3.24.042 7.222.042h7.244l1.796-3.157c.992-1.734 1.85-3.23 1.906-3.323l.104-.167h-7.249z' },
  onedrive: { color: '#0078D4', path: 'M17 18a4 4 0 0 0 1-7.8A6 6 0 0 0 6 9.5 4 4 0 0 0 7 18z' },
  gmail:    { color: '#EA4335', path: 'M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z' },
  whatsapp: { color: '#25D366', path: 'M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z' },
  telegram: { color: '#26A5E4', path: 'M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z' },
};

function ConnectorIcon({ id, size = 17 }) {
  const ic = CONNECTOR_ICONS[id];
  if (!ic) return <AxIcon name="cloud" size={size}/>;
  return <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block' }}><path d={ic.path} fill={ic.color}/></svg>;
}

function ConnectorsCard() {
  return (
    <div className="ax-card">
      <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <AxIcon name="cloud" size={15} style={{ color: 'var(--ax-fg-muted)' }}/>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>Conectores</h3>
        <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ax-fg-faint)' }}>De aquí Piixi lee pólizas y envía avisos. Nada sale sin tu permiso.</span>
      </div>
      <div>
        {CONNECTORS.map((c, i) => {
          const on = c.status === 'connected';
          return (
            <div key={c.id} style={{
              padding: '12px 18px', borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
              display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <span style={{
                width: 30, height: 30, borderRadius: 7, flexShrink: 0,
                background: 'var(--ax-bg-3)', border: '1px solid var(--ax-border-strong)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}><ConnectorIcon id={c.id} size={17}/></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)' }}>{c.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ax-fg-faint)' }}>{on && c.detail ? c.detail : c.kind}</div>
              </div>
              {on ? <AxPill tone="accent" dot>Conectado</AxPill> : <AxPill tone="ghost">Sin conectar</AxPill>}
              <AxButton size="sm" variant={on ? 'tertiary' : 'secondary'}>{on ? 'Gestionar' : 'Conectar'}</AxButton>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ZONA DE PELIGRO — borrado de datos in-app (estilo "borrar repo" de GitHub)
// Dos niveles: borrar datos de trabajo · restablecer de fábrica. El modal exige
// ESCRIBIR una palabra para confirmar (anti-accidente). Mockup: simula con un toast;
// el cableado real (detener motor → borrar userData → reiniciar) va en la app.
// ─────────────────────────────────────────────────────────────
const DANGER_ACTIONS = [
  {
    id: 'datos',
    titulo: 'Borrar datos de trabajo',
    desc: 'Elimina tus pólizas, clientes, contactos, importaciones y actividades. Conserva tu configuración, el asistente y las conexiones.',
    cta: 'Borrar datos',
    palabra: 'BORRAR',
    okToast: { kind: 'success', title: 'Datos borrados', message: 'Piixi se reinició con tu cartera vacía. Tu configuración se conservó.' },
  },
  {
    id: 'fabrica',
    titulo: 'Restablecer de fábrica',
    desc: 'Borra TODO: datos, configuración, asistente, conexiones, registros y llaves. Piixi queda como recién instalado.',
    cta: 'Restablecer Piixi',
    palabra: 'RESTABLECER',
    okToast: { kind: 'success', title: 'Piixi restablecido', message: 'Quedó como una instalación nueva.' },
  },
];

const axDangerBtn = {
  appearance: 'none', flexShrink: 0,
  background: 'transparent', color: 'var(--ax-danger)',
  border: '1px solid var(--ax-danger)', borderRadius: 6,
  padding: '7px 14px', fontSize: 13, fontWeight: 500,
  cursor: 'default', fontFamily: 'var(--font-body)',
};

function DangerZone() {
  const { pushToast } = useAxStore();
  const [openId, setOpenId] = useState(null);
  const action = DANGER_ACTIONS.find((a) => a.id === openId) || null;
  return (
    <div style={{ border: '1px solid var(--ax-danger)', borderRadius: 10, overflow: 'hidden' }}>
      <div style={{
        padding: '14px 18px', borderBottom: '1px solid var(--ax-danger)',
        background: 'var(--ax-danger-soft)', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <AxIcon name="alert" size={15} style={{ color: 'var(--ax-danger)' }}/>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, color: 'var(--ax-danger)' }}>Zona de peligro</h3>
      </div>
      <div style={{ background: 'var(--ax-bg-2)' }}>
        {DANGER_ACTIONS.map((a, i) => (
          <div key={a.id} style={{
            padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 16,
            borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
          }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ax-fg-strong)', marginBottom: 3 }}>{a.titulo}</div>
              <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', lineHeight: 1.5 }}>{a.desc}</div>
            </div>
            <button style={axDangerBtn} onClick={() => setOpenId(a.id)}
              onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--ax-danger)'; e.currentTarget.style.color = '#fff'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ax-danger)'; }}
            >{a.cta}</button>
          </div>
        ))}
      </div>
      <DangerModal action={action} onClose={() => setOpenId(null)} onConfirm={() => { pushToast(action.okToast); setOpenId(null); }}/>
    </div>
  );
}

function DangerModal({ action, onClose, onConfirm }) {
  const [typed, setTyped] = useState('');
  useEffect(() => { setTyped(''); }, [action]);
  if (!action) return null;
  const armed = typed.trim().toUpperCase() === action.palabra;
  return (
    <AxModal
      open={!!action}
      onClose={onClose}
      title={action.titulo}
      width={460}
      footer={
        <React.Fragment>
          <AxButton variant="secondary" onClick={onClose}>Cancelar</AxButton>
          <button
            disabled={!armed}
            onClick={armed ? onConfirm : undefined}
            style={{
              appearance: 'none',
              background: armed ? 'var(--ax-danger)' : 'var(--ax-bg-3)',
              color: armed ? '#fff' : 'var(--ax-fg-faint)',
              border: '1px solid ' + (armed ? 'var(--ax-danger)' : 'var(--ax-border-strong)'),
              borderRadius: 6, padding: '8px 16px', fontSize: 13, fontWeight: 600,
              cursor: 'default', fontFamily: 'var(--font-body)', opacity: armed ? 1 : 0.7,
            }}
          >{action.cta}</button>
        </React.Fragment>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{
          display: 'flex', gap: 10, alignItems: 'flex-start',
          background: 'var(--ax-danger-soft)', border: '1px solid var(--ax-danger)',
          borderRadius: 8, padding: '10px 12px',
        }}>
          <AxIcon name="alert" size={15} style={{ color: 'var(--ax-danger)', flexShrink: 0, marginTop: 1 }}/>
          <div style={{ fontSize: 12.5, color: 'var(--ax-fg)', lineHeight: 1.5 }}>
            {action.desc} <strong style={{ color: 'var(--ax-fg-strong)' }}>Esta acción no se puede deshacer.</strong>
          </div>
        </div>
        <AxField label={<span>Escribe <span className="ax-mono" style={{ color: 'var(--ax-danger)' }}>{action.palabra}</span> para confirmar</span>}>
          <AxInput
            value={typed}
            onChange={(e) => setTyped(e.target.value)}
            placeholder={action.palabra}
            autoFocus
            style={{ fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}
          />
        </AxField>
      </div>
    </AxModal>
  );
}

// ─────────────────────────────────────────────────────────────
// DOCTOR (§8)
// ─────────────────────────────────────────────────────────────
function DoctorScreen() {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const [last, setLast] = useState(new Date('2026-05-18T22:31:00'));
  const [running, setRunning] = useState(false);
  const checks = useMemo(() => [
    { id: 'sqlite',        label: 'Base SQLite',                     state: 'pass', detail: '~/.piixi/piixi.db · escritura OK · ' + state.policies.length + ' pólizas' },
    { id: 'udee',          label: 'Catálogo UDEE alcanzable',        state: 'pass', detail: 'Último pull: hace 6 días · 17 reglas activas' },
    { id: 'rulesets',      label: 'Reglas instaladas',                state: 'pass', detail: state.rulesets.filter((r) => r.installed).length + ' rulesets · ningún conflicto de versión' },
    { id: 'filesystem',    label: 'Permisos de filesystem',           state: 'pass', detail: 'Acceso a ~/Pólizas, ~/Drive · sin restricciones' },
    { id: 'drive',         label: 'Conexión a Google Drive',          state: 'warn', detail: 'No configurada. Si quieres conectarla, ve a Ajustes → Fuentes.' },
    { id: 'compliance',    label: 'Workflows de cumplimiento',        state: 'pass', detail: '4 reglas activas (renovación, validación RFC, vigencia, etc.)' },
    { id: 'audit',         label: 'Log de auditoría',                 state: 'pass', detail: 'Retención: 90 días · escribiendo a ~/.piixi/audit.log' },
    { id: 'encryption',    label: 'Encriptación local',               state: 'pass', detail: 'AES-256 · llave maestra en macOS Keychain' },
  ], [state]);

  const runAll = () => {
    setRunning(true);
    setTimeout(() => { setLast(new Date()); setRunning(false); }, 1100);
  };

  const summary = checks.reduce((s, c) => { s[c.state] = (s[c.state] || 0) + 1; return s; }, {});

  return (
    <div style={{ flex: 1, overflow: 'auto' }}>
      <AxPageHeader
        breadcrumb={<AxCrumb items={[{ label: 'Ajustes', to: '/ajustes' }, { label: 'Diagnóstico' }]}/>}
        eyebrow="piixi doctor"
        title="Diagnóstico"
        subtitle={`Última verificación: ${last.toLocaleString('es-MX', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })}`}
        actions={<AxButton variant="primary" icon="refresh" onClick={runAll} loading={running}>{running ? 'Verificando…' : 'Volver a verificar todo'}</AxButton>}
      />

      <div style={{ padding: '24px 32px 48px', maxWidth: 900 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 22 }}>
          <DoctorStat tone="accent" label="Pasan" v={summary.pass || 0}/>
          <DoctorStat tone="warm"   label="Advertencias" v={summary.warn || 0}/>
          <DoctorStat tone="danger" label="Fallas" v={summary.fail || 0}/>
        </div>

        <div className="ax-card">
          {checks.map((c, i) => (
            <DoctorRow key={c.id} c={c} top={i > 0} navigate={navigate}/>
          ))}
        </div>
      </div>
    </div>
  );
}

function DoctorStat({ tone, label, v }) {
  const colors = {
    accent: 'var(--ax-accent)',
    warm:   'var(--ax-warm)',
    danger: 'var(--ax-danger)',
  };
  return (
    <div className="ax-card" style={{ padding: 16 }}>
      <AxEyebrow style={{ color: colors[tone] }}>{label}</AxEyebrow>
      <div className="ax-mono" style={{ marginTop: 8, fontSize: 32, fontWeight: 700, color: colors[tone] }}>{v}</div>
    </div>
  );
}

function DoctorRow({ c, top, navigate }) {
  const [open, setOpen] = useState(false);
  const stateConfig = {
    pass: { color: 'var(--ax-accent)', label: 'OK',    icon: 'check' },
    warn: { color: 'var(--ax-warm)',   label: 'Aviso', icon: 'alert' },
    fail: { color: 'var(--ax-danger)', label: 'Falla', icon: 'x' },
  }[c.state];
  return (
    <div style={{ borderTop: top ? '1px solid var(--ax-border)' : 'none' }}>
      <button
        onClick={() => setOpen((v) => !v)}
        style={{
          appearance: 'none', background: 'transparent', border: 0,
          width: '100%', padding: '12px 16px',
          display: 'grid', gridTemplateColumns: '20px 24px 1fr 100px 24px', gap: 12, alignItems: 'center',
          color: 'inherit', cursor: 'default', textAlign: 'left',
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
        onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
      >
        <AxIcon name="chevron-right" size={11} style={{ color: 'var(--ax-fg-faint)', transform: open ? 'rotate(90deg)' : 'none', transition: 'transform 150ms' }}/>
        <span style={{
          width: 22, height: 22, borderRadius: 4,
          background: stateConfig.color + '22',
          border: '1px solid ' + stateConfig.color + '44',
          color: stateConfig.color,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}><AxIcon name={stateConfig.icon} size={12}/></span>
        <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)' }}>{c.label}</div>
        <span className="ax-mono" style={{ fontSize: 10, color: stateConfig.color, letterSpacing: '0.12em', textTransform: 'uppercase' }}>{stateConfig.label}</span>
        <span/>
      </button>
      {open ? (
        <div style={{ padding: '0 16px 14px 56px', fontSize: 12, color: 'var(--ax-fg-muted)' }}>
          {c.detail}
          {c.state === 'warn' && c.id === 'drive' ? (
            <div style={{ marginTop: 8 }}>
              <AxButton size="sm" variant="secondary" onClick={() => navigate('/ajustes')}>Ir a Ajustes</AxButton>
            </div>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { CatalogScreen, SettingsScreen });
