// Cranodato — Ajustes screen
const AjustesScreen = () => {
  const [tab, setTab] = React.useState('cuenta');
  const [saved, setSaved] = React.useState(false);
  const [empresa, setEmpresa] = React.useState('Distribuidora Norte S.A.');
  const [cuit, setCuit] = React.useState('30-71234567-0');
  const [email, setEmail] = React.useState('admin@distribuidoranorte.com');
  const [emailNoti, setEmailNoti] = React.useState(true);
  const [emailError, setEmailError] = React.useState(true);
  const [emailSemanal, setEmailSemanal] = React.useState(false);
  const [confianza, setConfianza] = React.useState('alta');

  const guardar = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const tabs = [
    { id: 'cuenta',      label: 'Cuenta',         icon: 'user' },
    { id: 'notificaciones', label: 'Notificaciones', icon: 'bell' },
    { id: 'procesamiento',  label: 'Procesamiento', icon: 'zap' },
    { id: 'seguridad',   label: 'Seguridad',       icon: 'shield' },
    { id: 'facturacion', label: 'Facturación',     icon: 'credit-card' },
  ];

  const Toggle = ({ value, onChange, label, desc }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 0', borderBottom: '1px solid #F1F5F9' }}>
      <div>
        <div style={{ fontSize: 14, fontWeight: 500, color: '#0F172A', marginBottom: 2 }}>{label}</div>
        {desc && <div style={{ fontSize: 12, color: '#94A3B8' }}>{desc}</div>}
      </div>
      <div
        onClick={() => onChange(!value)}
        style={{
          width: 42, height: 24, borderRadius: 9999, cursor: 'pointer',
          background: value ? '#059669' : '#E2E8F0',
          position: 'relative', transition: 'background 200ms', flexShrink: 0,
        }}
      >
        <div style={{
          width: 18, height: 18, borderRadius: '50%', background: 'white',
          position: 'absolute', top: 3, left: value ? 21 : 3,
          transition: 'left 200ms cubic-bezier(0.16,1,0.3,1)',
          boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
        }} />
      </div>
    </div>
  );

  const Field = ({ label, value, onChange, type = 'text', mono, hint }) => (
    <div style={{ marginBottom: 18 }}>
      <label style={{ display: 'block', fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#64748B', marginBottom: 6 }}>{label}</label>
      <input
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        style={{
          width: '100%', maxWidth: 400, fontFamily: mono ? "'DM Mono',monospace" : "'DM Sans',sans-serif",
          fontSize: 14, padding: '9px 12px', border: '1px solid #E2E8F0', borderRadius: 7,
          background: 'white', color: '#0F172A', outline: 'none', transition: 'border-color 150ms, box-shadow 150ms',
        }}
        onFocus={e => { e.target.style.borderColor = '#059669'; e.target.style.boxShadow = '0 0 0 3px rgba(5,150,105,0.12)'; }}
        onBlur={e => { e.target.style.borderColor = '#E2E8F0'; e.target.style.boxShadow = 'none'; }}
      />
      {hint && <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 4 }}>{hint}</div>}
    </div>
  );

  const CardSection = ({ title, desc, children }) => (
    <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, marginBottom: 20, overflow: 'hidden' }}>
      <div style={{ padding: '18px 24px', borderBottom: '1px solid #F1F5F9' }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A' }}>{title}</div>
        {desc && <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 2 }}>{desc}</div>}
      </div>
      <div style={{ padding: '20px 24px' }}>{children}</div>
    </div>
  );

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <Topbar title="Ajustes" />
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* Sidebar de tabs */}
        <div style={{ width: 200, background: 'white', borderRight: '1px solid #E2E8F0', padding: '16px 12px', flexShrink: 0 }}>
          {tabs.map(t => (
            <div key={t.id} onClick={() => setTab(t.id)} style={{
              display: 'flex', alignItems: 'center', gap: 9,
              padding: '9px 12px', borderRadius: 6, cursor: 'pointer', marginBottom: 2,
              background: tab === t.id ? '#ECFDF5' : 'transparent',
              color: tab === t.id ? '#047857' : '#475569',
              fontWeight: tab === t.id ? 600 : 400, fontSize: 14,
              transition: 'background 120ms, color 120ms',
            }}
            onMouseEnter={e => { if (tab !== t.id) e.currentTarget.style.background = '#F8FAFC'; }}
            onMouseLeave={e => { if (tab !== t.id) e.currentTarget.style.background = 'transparent'; }}>
              <i data-lucide={t.icon} style={{ width: 16, height: 16, flexShrink: 0 }}></i>
              {t.label}
            </div>
          ))}
        </div>

        {/* Contenido */}
        <div style={{ flex: 1, overflowY: 'auto', padding: 28 }}>

          {tab === 'cuenta' && (
            <>
              <CardSection title="Datos de la empresa" desc="Esta información aparece en los reportes y exportaciones.">
                <Field label="Nombre de la empresa" value={empresa} onChange={setEmpresa} />
                <Field label="CUIT" value={cuit} onChange={setCuit} mono hint="Formato: XX-XXXXXXXX-X" />
                <Field label="Email de contacto" value={email} onChange={setEmail} type="email" />
              </CardSection>
              <CardSection title="Zona horaria" desc="Usada para fechas en reportes y notificaciones.">
                <select style={{ fontFamily: "'DM Sans',sans-serif", fontSize: 14, padding: '9px 12px', border: '1px solid #E2E8F0', borderRadius: 7, background: 'white', color: '#0F172A', outline: 'none', width: '100%', maxWidth: 300 }}>
                  <option>América/Buenos_Aires (UTC-3)</option>
                  <option>América/Cordoba (UTC-3)</option>
                </select>
              </CardSection>
            </>
          )}

          {tab === 'notificaciones' && (
            <CardSection title="Notificaciones por email" desc="Elegí qué eventos querés recibir en tu casilla.">
              <Toggle value={emailNoti} onChange={setEmailNoti} label="Factura procesada correctamente" desc="Recibís un email por cada factura exitosa" />
              <Toggle value={emailError} onChange={setEmailError} label="Error o revisión requerida" desc="Alertas inmediatas cuando hay un problema" />
              <Toggle value={emailSemanal} onChange={setEmailSemanal} label="Resumen semanal" desc="Estadísticas de la semana cada lunes a las 9:00" />
            </CardSection>
          )}

          {tab === 'procesamiento' && (
            <CardSection title="Parámetros de extracción" desc="Controlá cómo la IA procesa tus facturas.">
              <div style={{ marginBottom: 18 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#64748B', marginBottom: 10 }}>Umbral de confianza mínimo</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  {['alta','media','baja'].map(v => (
                    <button key={v} onClick={() => setConfianza(v)} style={{
                      fontFamily: "'DM Sans',sans-serif", fontSize: 13, fontWeight: 500,
                      padding: '8px 18px', borderRadius: 7, cursor: 'pointer',
                      border: `1.5px solid ${confianza === v ? '#059669' : '#E2E8F0'}`,
                      background: confianza === v ? '#ECFDF5' : 'white',
                      color: confianza === v ? '#047857' : '#64748B',
                      transition: 'all 150ms', textTransform: 'capitalize',
                    }}>{v}</button>
                  ))}
                </div>
                <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 6 }}>
                  Facturas con confianza menor se marcan como "Revisar" en lugar de procesarse automáticamente.
                </div>
              </div>
              <Toggle value={true} onChange={() => {}} label="Validar CUIT contra AFIP" desc="Verifica que el CUIT exista y esté activo" />
              <Toggle value={false} onChange={() => {}} label="Aceptar facturas manuscritas" desc="Mayor tiempo de procesamiento. Requiere foto de alta calidad." />
            </CardSection>
          )}

          {tab === 'seguridad' && (
            <CardSection title="Seguridad de la cuenta">
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: '#0F172A', marginBottom: 4 }}>Contraseña</div>
                <div style={{ fontSize: 13, color: '#64748B', marginBottom: 12 }}>Última modificación: hace 30 días</div>
                <Btn variant="secondary" size="sm">Cambiar contraseña</Btn>
              </div>
              <hr style={{ border: 'none', borderTop: '1px solid #F1F5F9', margin: '16px 0' }} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, color: '#0F172A', marginBottom: 4 }}>Autenticación en dos pasos</div>
                <div style={{ fontSize: 13, color: '#94A3B8', marginBottom: 12 }}>Protegé tu cuenta con un segundo factor.</div>
                <Btn size="sm">Activar 2FA</Btn>
              </div>
              <hr style={{ border: 'none', borderTop: '1px solid #F1F5F9', margin: '16px 0' }} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, color: '#DC2626', marginBottom: 4 }}>Zona de peligro</div>
                <div style={{ fontSize: 13, color: '#94A3B8', marginBottom: 12 }}>Eliminar la cuenta borra todos tus datos permanentemente.</div>
                <Btn variant="danger" size="sm">Eliminar cuenta</Btn>
              </div>
            </CardSection>
          )}

          {tab === 'facturacion' && (
            <>
              <CardSection title="Plan actual">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 18, fontWeight: 700, color: '#0F172A', marginBottom: 4 }}>Plan Pro</div>
                    <div style={{ fontSize: 13, color: '#64748B' }}>500 facturas/mes · USD $29/mes · Próximo cobro: 30/05/2025</div>
                  </div>
                  <Btn variant="secondary" size="sm">Cambiar plan</Btn>
                </div>
              </CardSection>
              <CardSection title="Uso del mes">
                <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'space-between', fontSize: 13, color: '#64748B' }}>
                  <span>Facturas procesadas</span>
                  <span style={{ fontFamily: "'DM Mono',monospace", color: '#0F172A' }}>48 / 500</span>
                </div>
                <div style={{ height: 6, background: '#F1F5F9', borderRadius: 9999, overflow: 'hidden' }}>
                  <div style={{ width: '9.6%', height: '100%', background: '#059669', borderRadius: 9999 }} />
                </div>
                <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 6 }}>452 facturas restantes este mes</div>
              </CardSection>
            </>
          )}

          {/* Guardar */}
          {['cuenta','notificaciones','procesamiento'].includes(tab) && (
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <Btn onClick={guardar}>Guardar cambios</Btn>
              {saved && (
                <span style={{ fontSize: 13, color: '#059669', display: 'flex', alignItems: 'center', gap: 5 }}>
                  <i data-lucide="check" style={{ width: 15, height: 15 }}></i>
                  Guardado
                </span>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AjustesScreen });
