const useTlStore = () => {
  const [state, setState] = React.useState(() => TrLearningModel.get());
  const [error, setError] = React.useState('');
  React.useEffect(() => {
    const sync = () => setState(TrLearningModel.get());
    window.addEventListener('atica-learning-change', sync);
    return () => window.removeEventListener('atica-learning-change', sync);
  }, []);
  React.useEffect(() => {
    const current = TrLearningModel.get();
    const active = TrLearningModel.activate(current);
    if (active.deliveries.length !== current.deliveries.length) {
      try {
        TrLearningModel.save(active);
      } catch (e) {
        setError(e.message);
      }
    }
  }, []);
  const change = action => {
    try {
      const next = action(TrLearningModel.get());
      TrLearningModel.save(next);
      setError('');
      return true;
    } catch (e) {
      setError(e.message);
      return false;
    }
  };
  return [state, change, error, setError];
};
const TlField = ({
  label,
  children,
  wide = false
}) => <label className={`tl-field ${wide ? 'tl-wide' : ''}`}><span>{label}</span>{React.isValidElement(children) ? React.cloneElement(children, {
    'aria-label': children.props['aria-label'] || label
  }) : children}</label>;
const TlError = ({
  message
}) => message ? <div className="tl-error" role="alert"><IconAlert size={16} />{message}</div> : null;
const TlPill = ({
  value
}) => <span className={`pill ${['Aprobado', 'Aprobada', 'Vigente', 'Apto', 'Ejecutado'].includes(value) ? 'green' : ['Rechazado', 'No apto', 'Vencido'].includes(value) ? 'rose' : ['Devuelto', 'Devuelta', 'Pendiente por ejecutar', 'Próximo a vencer'].includes(value) ? 'amber' : 'navy'}`}>{value || 'Sin registrar'}</span>;
const TlHero = ({
  eyebrow,
  title,
  description,
  metrics,
  children
}) => <section className="tl-hero"><div className="tl-hero-top"><div><div className="tl-eyebrow">{eyebrow}</div><h2>{title}</h2><p>{description}</p></div>{children && <div className="tl-actions">{children}</div>}</div><div className="tl-metrics">{metrics.map(([value, label]) => <div key={label}><strong>{value}</strong><span>{label}</span></div>)}</div></section>;
const TlDateControl = ({
  state,
  change
}) => <div className="tl-date-control"><span className="muted-xs">Fecha de demostración</span><input aria-label="Fecha de demostración" type="date" value={state.today} onChange={e => {
    if (e.target.value) change(s => TrLearningModel.activate({
      ...s,
      today: e.target.value
    }));
  }} /><span className="muted-xs">Los avisos se registran sin enviar mensajes reales.</span></div>;
const TlUpload = ({
  label,
  file,
  onChange,
  accept = '.pdf,video/mp4,video/webm',
  readOnly = false
}) => {
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const load = event => {
    const f = event.target.files[0];
    if (!f) return;
    const types = accept.includes('video') ? ['application/pdf', 'video/mp4', 'video/webm'] : accept.includes('image') ? ['application/pdf', 'image/png', 'image/jpeg', 'image/webp'] : ['application/pdf'];
    if (!types.includes(f.type)) {
      setError('Selecciona un archivo del tipo permitido.');
      return;
    }
    if (f.size > 2 * 1024 * 1024) {
      setError('Para guardar en este prototipo, usa un archivo de hasta 2 MB.');
      return;
    }
    setLoading(true);
    const reader = new FileReader();
    reader.onload = () => {
      onChange({
        nombre: f.name,
        tipo: f.type,
        tamKB: Math.round(f.size / 1024),
        data: reader.result
      });
      setLoading(false);
      setError('');
    };
    reader.onerror = () => {
      setLoading(false);
      setError('No se pudo leer el archivo. Inténtalo de nuevo.');
    };
    reader.readAsDataURL(f);
  };
  return <div className="tl-upload"><b>{label}</b>{file && <div className="tl-file-row"><IconDoc size={17} /><span>{file.nombre}{!file.data && <small> · {file.demo ? 'Material de ejemplo' : 'Referencia histórica, archivo no cargado'}</small>}</span>{file.data && <button className="btn" type="button" onClick={() => TrLearningModel.downloadFile(file)}>Descargar</button>}</div>}{!readOnly && <label className="tl-file-picker"><input aria-label={label} type="file" accept={accept} onChange={load} disabled={loading} /><span>{loading ? 'Leyendo archivo…' : file ? 'Cambiar archivo' : 'Seleccionar archivo'}</span><small>PDF {accept.includes('video') ? 'o video' : accept.includes('image') ? 'o imagen' : ''} · hasta 2 MB en esta demo</small></label>}<TlError message={error} /></div>;
};
const TlEmployee = ({
  employee
}) => !employee ? null : <div className="tl-employee-grid">{[['Cédula', employee.doc], ['Nombre completo', employee.name], ['Empresa actual', employee.sociedad], ['Regional', employee.regional], ['Planta', employee.planta], ['Cargo', employee.cargo], ['Línea de negocio', employee.lineaNegocio], ['Proceso', employee.proceso], ['Subproceso', employee.subproceso], ['Género', employee.genero], ['Fecha de ingreso', employee.fechaIngreso], ['Jefe inmediato', employee.jefeInmediato], ['Celular', employee.celular], ['Correo', employee.correo]].map(([label, value]) => <div key={label}><small>{label}</small><span>{value || 'Sin información'}</span></div>)}</div>;
const tlEmployee = id => TrLearningModel.roster().find(e => e.id === id);
const tlDownloadDiploma = r => TrLearningModel.download(`Diploma-${r.id}.html`, TrLearningModel.diploma(r, r.employeeSnapshot || tlEmployee(r.empId)));
const tlExport = (name, headers, rows) => {
  const quote = value => '"' + String(value ?? '').replace(/^[=+@-]/, "'$&").replaceAll('"', '""') + '"';
  TrLearningModel.download(name, '\ufeff' + [headers, ...rows].map(row => row.map(quote).join(';')).join('\r\n'), 'text/csv;charset=utf-8');
};
// Colección descargable en un único HTML imprimible; no promete un ZIP ficticio.
const tlDownloadCollection = records => {
  if (!records.length) return;
  const body = records.map(r => TrLearningModel.diploma(r, r.employeeSnapshot || tlEmployee(r.empId)).match(/<article>[\s\S]*<\/article>/)[0]).join('');
  TrLearningModel.download('Diplomas-del-equipo.html', `<!doctype html><html lang="es"><meta charset="utf-8"><title>Diplomas del equipo</title><style>body{font:18px Arial;color:#2E1A46}article{padding:60px;margin:30px;border:2px solid #0E5964;text-align:center;break-after:page}small{color:#5B5468}</style>${body}</html>`);
};
window.TrLearningUI = {
  useTlStore,
  TlField,
  TlError,
  TlHero,
  TlUpload,
  TlEmployee,
  TlPill
};
