// admin-cert-config.jsx — Configuración del certificado
const { useState: useCCState, useRef: useCCRef, useEffect: useCCEffect } = React;

// ── Valores por defecto ──────────────────────────────────────────────────────
var CC_DEFAULT = {
  logoPrincipal:         '',
  logoSecundario:        '',
  logoSecundarioEnabled: false,
  nombreInstitucion:     'ASSYST',
  textoAval:             '',
  nombreFirmante:        'Firma Representante Legal',
  cargoFirmante:         'ASSYST · SG-SST',
  nombreCurso:           'Diseño, Implementación y Automatización\ncon Inteligencia Artificial del\nSistema de Gestión en Seguridad y Salud en el Trabajo (SG-SST)',
  modalidad:             'Virtual',
  pais:                  'República de Colombia',
  imagenFirma:           '',
};

function getCertConfig() {
  try {
    var raw = localStorage.getItem('sst_cert_config');
    if (!raw) return Object.assign({}, CC_DEFAULT);
    return Object.assign({}, CC_DEFAULT, JSON.parse(raw));
  } catch (e) { return Object.assign({}, CC_DEFAULT); }
}

function saveCertConfig(cfg) {
  try {
    localStorage.setItem('sst_cert_config', JSON.stringify(cfg));
    if (typeof window.sbSave === 'function') window.sbSave('sst_cert_config', cfg);
    return true;
  } catch (e) {
    if (e && e.name === 'QuotaExceededError') {
      alert('La imagen es demasiado grande para almacenar localmente. Usa una imagen más pequeña o una URL externa.');
    }
    return false;
  }
}

window.getCertConfig  = getCertConfig;
window.saveCertConfig = saveCertConfig;

// ── Subcomponente: campo imagen (URL / base64 / preview) ─────────────────────
function CertImageField({ value, previewFallback, onUpload, onRemove, onUrlChange, placeholder, previewW, previewH }) {
  var isBase64   = value && value.startsWith('data:');
  var displaySrc = value || previewFallback || '';
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 7 }}>
        <input
          type="text"
          placeholder={isBase64 ? '✓ Imagen cargada (base64 — sube otra para reemplazar)' : (placeholder || 'Pegar URL...')}
          value={isBase64 ? '' : (value || '')}
          onChange={function (e) { if (onUrlChange) onUrlChange(e.target.value); }}
          style={{
            width: '100%', padding: '9px 13px', border: '1.5px solid #e2e8f0',
            borderRadius: 8, fontSize: 13, fontFamily: "'Montserrat',sans-serif",
            color: isBase64 ? '#94a3b8' : '#1e293b', background: 'white',
            outline: 'none', boxSizing: 'border-box', fontStyle: isBase64 ? 'italic' : 'normal',
          }}
        />
        <div style={{ display: 'flex', gap: 8 }}>
          <button
            onClick={onUpload}
            style={{ padding: '7px 14px', background: '#f8fafc', border: '1.5px solid #e2e8f0', borderRadius: 7, fontSize: 11, cursor: 'pointer', fontFamily: "'Montserrat',sans-serif", color: '#475569', fontWeight: 600 }}
          >
            📁 Subir imagen
          </button>
          {value && (
            <button
              onClick={onRemove}
              style={{ padding: '7px 12px', background: '#fef2f2', border: '1.5px solid #fecaca', borderRadius: 7, fontSize: 11, cursor: 'pointer', fontFamily: "'Montserrat',sans-serif", color: '#dc2626', fontWeight: 600 }}
            >
              ✕ Quitar
            </button>
          )}
        </div>
      </div>
      <div style={{
        width: previewW || 80, height: previewH || 80,
        border: '1.5px solid #e2e8f0', borderRadius: 10,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: '#f8fafc', flexShrink: 0, overflow: 'hidden', padding: 6,
      }}>
        {displaySrc
          ? <img src={displaySrc} alt="preview" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
          : <span style={{ fontSize: 10, color: '#cbd5e1', textAlign: 'center', lineHeight: 1.4 }}>Vista<br />previa</span>
        }
      </div>
    </div>
  );
}

// ── Panel principal ──────────────────────────────────────────────────────────
function AdminCertConfig() {
  const [config, setConfig] = useCCState(getCertConfig);
  const [status, setStatus] = useCCState('idle'); // 'idle' | 'saved' | 'error'
  const [previewLogo,  setPreviewLogo]  = useCCState('');
  const [previewLogo2, setPreviewLogo2] = useCCState('');
  const [previewSign,  setPreviewSign]  = useCCState('');
  const logoRef  = useCCRef(null);
  const logo2Ref = useCCRef(null);
  const signRef  = useCCRef(null);

  // ── Gestión del Consecutivo: estado local ──────────────────────────────────
  const [ccCounter,      setCCCounter]      = useCCState(function () { return readCertCounter(); });
  const [ccResetConfirm, setCCResetConfirm] = useCCState(false);
  const [ccStartFrom,    setCCStartFrom]    = useCCState('');
  const [ccApplyMsg,     setCCApplyMsg]     = useCCState('');   // '' | 'ok' | 'error'
  const [ccLastApplied,  setCCLastApplied]  = useCCState(null); // número aplicado (para el msg)

  // Carga imágenes para la vista previa en tiempo real
  useCCEffect(function () {
    function load(src, setter) {
      setter('');
      if (!src) return;
      if (src.startsWith('data:')) { setter(src); return; }
      fetch(src)
        .then(function (r) { return r.blob(); })
        .then(function (blob) {
          var fr = new FileReader();
          fr.onloadend = function () { setter(fr.result); };
          fr.readAsDataURL(blob);
        })
        .catch(function () {});
    }
    load(config.logoPrincipal || (window.__resources && window.__resources.logoAssyst) || 'uploads/LOGO.png', setPreviewLogo);
    if (config.logoSecundarioEnabled && config.logoSecundario) {
      load(config.logoSecundario, setPreviewLogo2);
    } else {
      setPreviewLogo2('');
    }
    load(config.imagenFirma || (window.__resources && window.__resources.signAssyst) || 'uploads/pasted-1781199739000-0.png', setPreviewSign);
  }, [config.logoPrincipal, config.logoSecundario, config.logoSecundarioEnabled, config.imagenFirma]);

  // Sincronizar contador al montar (refleja cambios hechos desde otro componente)
  useCCEffect(function () { setCCCounter(readCertCounter()); }, []);

  function setField(key, val) {
    setConfig(function (prev) {
      var n = Object.assign({}, prev);
      n[key] = val;
      return n;
    });
  }

  function loadFile(e, key) {
    var f = e.target.files && e.target.files[0];
    if (!f) return;
    var fr = new FileReader();
    fr.onloadend = function () { setField(key, fr.result); };
    fr.readAsDataURL(f);
    e.target.value = '';
  }

  function handleSave() {
    var ok = saveCertConfig(config);
    setStatus(ok ? 'saved' : 'error');
    if (ok) setTimeout(function () { setStatus('idle'); }, 3200);
  }

  // ── Helpers: gestión del consecutivo ──────────────────────────────────────
  function readCertCounter() {
    try {
      var stored = localStorage.getItem('sst_cert_counter');
      var n = stored ? JSON.parse(stored) : 0;
      return (typeof n === 'number' && n >= 0) ? n : 0;
    } catch (e) { return 0; }
  }
  function doSetCertCounter(n) {
    // Delega a window.setCertCounterTo (App) para actualizar React state + localStorage
    if (typeof window.setCertCounterTo === 'function') {
      window.setCertCounterTo(n);
    } else {
      try { localStorage.setItem('sst_cert_counter', JSON.stringify(n)); } catch (e) {}
    }
    setCCCounter(n);
  }
  function handleCCReset() {
    doSetCertCounter(0);
    setCCResetConfirm(false);
  }
  function handleCCStartFrom() {
    var val = parseInt(ccStartFrom, 10);
    if (isNaN(val) || val < 1) {
      setCCApplyMsg('error');
      setTimeout(function () { setCCApplyMsg(''); }, 3500);
      return;
    }
    // Guardar val-1: el PRÓXIMO certificado recibe el número val
    doSetCertCounter(Math.max(0, val - 1));
    setCCLastApplied(val);
    setCCStartFrom('');
    setCCApplyMsg('ok');
    setTimeout(function () { setCCApplyMsg(''); setCCLastApplied(null); }, 4500);
  }
  // ───────────────────────────────────────────────────────────────────────────

  // ── Estilos compartidos ──
  var lbl = {
    display: 'block', fontSize: 11, fontWeight: 700, color: '#64748b',
    textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 6,
  };
  var inp = {
    width: '100%', padding: '9px 13px', border: '1.5px solid #e2e8f0',
    borderRadius: 8, fontSize: 13, fontFamily: "'Montserrat',sans-serif",
    color: '#1e293b', background: 'white', outline: 'none', boxSizing: 'border-box',
  };
  var card = {
    background: 'white', borderRadius: 12, border: '1px solid #e5e7eb',
    padding: '22px 26px', marginBottom: 16,
  };
  var sh = {
    fontSize: 12, fontWeight: 800, color: '#1c79b4', textTransform: 'uppercase',
    letterSpacing: '0.1em', marginBottom: 18, borderBottom: '1px solid #f1f5f9',
    paddingBottom: 12, display: 'flex', alignItems: 'center', gap: 8,
  };

  return (
    <div style={{ maxWidth: 820, margin: '0 auto', paddingBottom: 40 }}>

      <p style={{ margin: '0 0 22px', fontSize: 13, color: '#6b7280', lineHeight: 1.6 }}>
        Personaliza el certificado que se entrega a los estudiantes. Los cambios se aplican al próximo certificado expedido.
      </p>

      {/* ── 1. Logos ── */}
      <div style={card}>
        <div style={sh}>🖼️ Logos del certificado</div>

        {/* Logo principal */}
        <div style={{ marginBottom: 22 }}>
          <label style={lbl}>Logo principal</label>
          <CertImageField
            value={config.logoPrincipal}
            previewFallback={(window.__resources && window.__resources.logoAssyst) || "uploads/LOGO.png"}
            onUpload={function () { logoRef.current.click(); }}
            onRemove={function () { setField('logoPrincipal', ''); }}
            onUrlChange={function (v) { setField('logoPrincipal', v); }}
            placeholder="Pegar URL del logo principal..."
          />
          <input ref={logoRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={function (e) { loadFile(e, 'logoPrincipal'); }} />
          <p style={{ fontSize: 11, color: '#94a3b8', margin: '7px 0 0' }}>
            Si está vacío usa <strong>uploads/LOGO.png</strong> (logo actual de ASSYST).
          </p>
        </div>

        {/* Logo secundario */}
        <div style={{ borderTop: '1px solid #f1f5f9', paddingTop: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <label style={{ ...lbl, marginBottom: 0 }}>
              Logo secundario / aval
              <span style={{ fontWeight: 400, textTransform: 'none', color: '#94a3b8', marginLeft: 6, fontSize: 11 }}>
                (ej: SENA, ARL, entidad avaladora)
              </span>
            </label>
            {/* Toggle */}
            <button
              onClick={function () { setField('logoSecundarioEnabled', !config.logoSecundarioEnabled); }}
              title={config.logoSecundarioEnabled ? 'Desactivar' : 'Activar'}
              style={{
                width: 46, height: 26, borderRadius: 13, border: 'none', cursor: 'pointer', padding: 0,
                background: config.logoSecundarioEnabled ? '#1c79b4' : '#d1d5db',
                position: 'relative', transition: 'background .2s', flexShrink: 0,
              }}
            >
              <div style={{
                position: 'absolute', top: 4,
                left: config.logoSecundarioEnabled ? 24 : 4,
                width: 18, height: 18, borderRadius: '50%', background: 'white',
                transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.25)',
              }} />
            </button>
          </div>

          <div style={{ opacity: config.logoSecundarioEnabled ? 1 : 0.4, pointerEvents: config.logoSecundarioEnabled ? 'auto' : 'none', transition: 'opacity .2s' }}>
            <CertImageField
              value={config.logoSecundario}
              onUpload={function () { logo2Ref.current.click(); }}
              onRemove={function () { setField('logoSecundario', ''); }}
              onUrlChange={function (v) { setField('logoSecundario', v); }}
              placeholder="Pegar URL del logo secundario..."
            />
            <input ref={logo2Ref} type="file" accept="image/*" style={{ display: 'none' }} onChange={function (e) { loadFile(e, 'logoSecundario'); }} />

            <div style={{ marginTop: 14 }}>
              <label style={lbl}>Texto del aval <span style={{ fontWeight: 400, textTransform: 'none' }}>(opcional)</span></label>
              <input
                type="text"
                placeholder='Ej: Avalado por SENA · Con el apoyo de ARL'
                value={config.textoAval}
                onChange={function (e) { setField('textoAval', e.target.value); }}
                style={inp}
              />
              <p style={{ fontSize: 11, color: '#94a3b8', margin: '5px 0 0' }}>Aparece debajo del logo secundario en el certificado.</p>
            </div>
          </div>
        </div>
      </div>

      {/* ── 2. Institución ── */}
      <div style={card}>
        <div style={sh}>🏛️ Institución</div>
        <label style={lbl}>Nombre de la institución</label>
        <input
          type="text"
          value={config.nombreInstitucion}
          onChange={function (e) { setField('nombreInstitucion', e.target.value); }}
          style={inp}
        />
        <p style={{ fontSize: 11, color: '#94a3b8', margin: '7px 0 0' }}>
          Actualmente aparece como <strong>ASSYST</strong> en el pie de firma del certificado.
        </p>
      </div>

      {/* ── 3. Firmante ── */}
      <div style={card}>
        <div style={sh}>✍️ Firmante</div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
          <div>
            <label style={lbl}>Nombre del firmante</label>
            <input
              type="text"
              value={config.nombreFirmante}
              onChange={function (e) { setField('nombreFirmante', e.target.value); }}
              style={inp}
            />
          </div>
          <div>
            <label style={lbl}>Cargo del firmante</label>
            <input
              type="text"
              value={config.cargoFirmante}
              onChange={function (e) { setField('cargoFirmante', e.target.value); }}
              style={inp}
            />
          </div>
        </div>

        <div>
          <label style={lbl}>Imagen de la firma</label>
          <CertImageField
            value={config.imagenFirma}
            onUpload={function () { signRef.current.click(); }}
            onRemove={function () { setField('imagenFirma', ''); }}
            placeholder="Sube imagen de la firma (PNG con fondo transparente recomendado)"
            previewW={160}
            previewH={64}
          />
          <input ref={signRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={function (e) { loadFile(e, 'imagenFirma'); }} />
          <p style={{ fontSize: 11, color: '#94a3b8', margin: '7px 0 0' }}>Si está vacío usa la firma actual del sistema.</p>
        </div>
      </div>

      {/* ── 4. Contenido ── */}
      <div style={card}>
        <div style={sh}>📋 Contenido del certificado</div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 18 }}>
          <div>
            <label style={lbl}>Texto de la modalidad</label>
            <input
              type="text"
              value={config.modalidad}
              onChange={function (e) { setField('modalidad', e.target.value); }}
              style={inp}
              placeholder='Virtual'
            />
          </div>
          <div>
            <label style={lbl}>País</label>
            <input
              type="text"
              value={config.pais}
              onChange={function (e) { setField('pais', e.target.value); }}
              style={inp}
              placeholder='República de Colombia'
            />
          </div>
        </div>

        <div>
          <label style={lbl}>Nombre del curso en el certificado</label>
          <textarea
            value={config.nombreCurso}
            onChange={function (e) { setField('nombreCurso', e.target.value); }}
            rows={4}
            style={{ ...inp, resize: 'vertical', lineHeight: 1.7 }}
            placeholder="Nombre del curso tal como aparecerá en el certificado..."
          />
          <p style={{ fontSize: 11, color: '#94a3b8', margin: '5px 0 0', lineHeight: 1.5 }}>
            Usa saltos de línea para separar en bloques. La primera línea se muestra más grande; la última en azul.
          </p>
        </div>
      </div>

      {/* ── Vista previa ── */}
      {(function () {
        var CertDocPreview = window.CertificateDoc;
        var pScale = 0.65;
        var pW = Math.round(1123 * pScale);
        var pH = Math.round(794  * pScale);
        var previewUser = { nombre: 'Juan Carlos Pérez González', empresa: 'Empresa Ejemplo S.A.S.', cargo: 'Coordinador SST' };
        return (
          <div style={{ ...card, marginBottom: 16 }}>
            <div style={{ ...sh, justifyContent: 'space-between' }}>
              <span>👁️ Vista previa del certificado</span>
              <span style={{ fontSize: 10, fontWeight: 700, color: '#15803d', background: '#dcfce7', padding: '3px 10px', borderRadius: 20, letterSpacing: '0.05em' }}>● EN VIVO</span>
            </div>
            <p style={{ fontSize: 12, color: '#94a3b8', margin: '0 0 14px', lineHeight: 1.5 }}>
              Vista previa con datos de ejemplo. Los cambios del formulario se reflejan aquí al instante.
            </p>
            <div style={{ background: '#e8eef5', borderRadius: 10, padding: 16, display: 'flex', justifyContent: 'center', overflow: 'hidden' }}>
              <div style={{ width: pW, height: pH, position: 'relative', flexShrink: 0, boxShadow: '0 8px 32px rgba(0,0,0,.18)' }}>
                <div style={{ position: 'absolute', top: 0, left: 0, transform: 'scale(' + pScale + ')', transformOrigin: 'top left', pointerEvents: 'none' }}>
                  {CertDocPreview
                    ? <CertDocPreview
                        user={previewUser}
                        startDate="1 de enero de 2025"
                        endDate="15 de junio de 2025"
                        certNumber="ASSYST-2025-0001"
                        logoSrc={previewLogo}
                        signSrc={previewSign}
                        logo2Src={previewLogo2}
                        certConfig={config}
                        innerRef={null}
                      />
                    : <div style={{ width: 1123, height: 794, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#94a3b8', fontSize: 16 }}>Cargando vista previa…</div>
                  }
                </div>
              </div>
            </div>
          </div>
        );
      })()}

      {/* ── 5. Gestión del Consecutivo ── */}
      <div style={{
        background: '#f0f7ff', borderRadius: 12,
        border: '1px solid #dbeafe', borderLeft: '4px solid #1c79b4',
        padding: '22px 26px', marginBottom: 16
      }}>
        <div style={{ ...sh, color: '#0f2044', borderBottom: '1px solid rgba(28,121,180,.18)' }}>
          🔢 Gestión del Consecutivo
        </div>

        {/* Estado actual */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20,
          padding: '11px 16px', background: 'rgba(28,121,180,.07)',
          borderRadius: 9, border: '1px solid rgba(28,121,180,.15)'
        }}>
          <div style={{
            width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
            background: ccCounter === 0 ? '#94a3b8' : '#22c55e'
          }} />
          <span style={{ fontSize: 13, color: '#475569', fontWeight: 500 }}>Último certificado expedido:</span>
          <span style={{
            fontSize: 15, fontWeight: 900, letterSpacing: '0.05em',
            color: ccCounter === 0 ? '#94a3b8' : '#1c79b4',
            fontFamily: 'monospace'
          }}>
            {ccCounter === 0 ? 'Ninguno aún' : 'ASSYST-SST-' + String(ccCounter).padStart(3, '0')}
          </span>
          {ccCounter > 0 && (
            <span style={{ marginLeft: 'auto', fontSize: 11, color: '#94a3b8', fontWeight: 500 }}>
              {ccCounter} certificado{ccCounter !== 1 ? 's' : ''} expedido{ccCounter !== 1 ? 's' : ''}
            </span>
          )}
        </div>

        {/* Columnas: Reiniciar | Iniciar desde */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>

          {/* Reiniciar consecutivo */}
          <div>
            <label style={lbl}>Reiniciar consecutivo</label>
            <p style={{ fontSize: 11, color: '#6b7280', margin: '0 0 12px', lineHeight: 1.55 }}>
              El próximo certificado empezará desde <strong>ASSYST-SST-001</strong>. Los ya expedidos conservan su código.
            </p>
            {ccResetConfirm ? (
              <div style={{ background: '#fef2f2', border: '1.5px solid #fecaca', borderRadius: 10, padding: '13px 15px' }}>
                <p style={{ margin: '0 0 11px', fontSize: 12, color: '#7f1d1d', lineHeight: 1.6, fontWeight: 500 }}>
                  ¿Estás seguro? Esto reiniciará el consecutivo a 001. Los certificados ya expedidos mantienen su código pero el próximo que se genere empezará desde <strong>ASSYST-SST-001</strong>
                </p>
                <div style={{ display: 'flex', gap: 7 }}>
                  <button
                    onClick={handleCCReset}
                    style={{ background: '#dc2626', color: 'white', border: 'none', borderRadius: 7, padding: '7px 14px', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: "'Montserrat',sans-serif" }}
                    onMouseOver={function (e) { e.currentTarget.style.background = '#b91c1c'; }}
                    onMouseOut={function (e) { e.currentTarget.style.background = '#dc2626'; }}
                  >Sí, reiniciar a 001</button>
                  <button
                    onClick={function () { setCCResetConfirm(false); }}
                    style={{ background: '#f1f5f9', color: '#475569', border: 'none', borderRadius: 7, padding: '7px 14px', fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: "'Montserrat',sans-serif" }}
                    onMouseOver={function (e) { e.currentTarget.style.background = '#e2e8f0'; }}
                    onMouseOut={function (e) { e.currentTarget.style.background = '#f1f5f9'; }}
                  >Cancelar</button>
                </div>
              </div>
            ) : (
              <button
                onClick={function () { setCCResetConfirm(true); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 7,
                  padding: '9px 16px', background: 'white', color: '#dc2626',
                  border: '1.5px solid #fecaca', borderRadius: 8, fontSize: 12,
                  fontWeight: 700, cursor: 'pointer', fontFamily: "'Montserrat',sans-serif",
                  transition: 'background .15s'
                }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#fef2f2'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = 'white'; }}
              >
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="1 4 1 10 7 10"></polyline>
                  <path d="M3.51 15a9 9 0 1 0 .49-3.85"></path>
                </svg>
                Reiniciar consecutivo
              </button>
            )}
          </div>

          {/* Iniciar desde número específico */}
          <div>
            <label style={lbl}>Iniciar consecutivo desde</label>
            <p style={{ fontSize: 11, color: '#6b7280', margin: '0 0 12px', lineHeight: 1.55 }}>
              Ej: escribe <strong>50</strong> y el próximo certificado será <strong>ASSYST-SST-050</strong>.
            </p>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <input
                type="number"
                min="1"
                placeholder="Ej: 50"
                value={ccStartFrom}
                onChange={function (e) { setCCStartFrom(e.target.value); }}
                style={{ ...inp, width: 110 }}
              />
              <button
                onClick={handleCCStartFrom}
                style={{
                  padding: '9px 18px', background: '#1c79b4', color: 'white',
                  border: 'none', borderRadius: 8, fontSize: 12, fontWeight: 700,
                  cursor: 'pointer', fontFamily: "'Montserrat',sans-serif"
                }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#1565a0'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
              >Aplicar</button>
            </div>
            {ccApplyMsg === 'ok' && ccLastApplied !== null && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 9, fontSize: 12, color: '#15803d', fontWeight: 600 }}>
                <span style={{ fontSize: 14 }}>✓</span>
                <span>Próximo certificado: <strong style={{ fontFamily: 'monospace' }}>ASSYST-SST-{String(ccLastApplied).padStart(3, '0')}</strong></span>
              </div>
            )}
            {ccApplyMsg === 'error' && (
              <div style={{ marginTop: 9, fontSize: 12, color: '#dc2626', fontWeight: 600 }}>
                Ingresa un número entero mayor o igual a 1.
              </div>
            )}
          </div>
        </div>

        <p style={{ margin: '16px 0 0', fontSize: 11, color: '#94a3b8', lineHeight: 1.5 }}>
          ⚠️ Cuando se conecte Supabase este consecutivo se guardará en base de datos para ser permanente entre sesiones y dispositivos.
        </p>
      </div>

      {/* ── Botón guardar ── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, paddingTop: 4 }}>
        <button
          onClick={handleSave}
          style={{
            padding: '12px 32px', background: '#1c79b4', color: 'white',
            border: 'none', borderRadius: 10, fontSize: 14, fontWeight: 700,
            cursor: 'pointer', fontFamily: "'Montserrat',sans-serif",
            boxShadow: '0 4px 16px rgba(28,121,180,.25)', transition: 'background .15s',
          }}
          onMouseOver={function (e) { e.currentTarget.style.background = '#1a6fa3'; }}
          onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
        >
          Guardar configuración
        </button>
        {status === 'saved' && (
          <span style={{ display: 'flex', alignItems: 'center', gap: 7, color: '#15803d', fontWeight: 700, fontSize: 13 }}>
            <span style={{ fontSize: 16 }}>✓</span> Configuración guardada correctamente
          </span>
        )}
        {status === 'error' && (
          <span style={{ color: '#dc2626', fontWeight: 700, fontSize: 13 }}>
            Error al guardar. Prueba con imágenes más pequeñas.
          </span>
        )}
      </div>

    </div>
  );
}

window.AdminCertConfig = AdminCertConfig;
