const { useState: useStateAC, useEffect: useEffectAC } = React;

function SSTModal({ title, onClose, children, wide }) {
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,61,94,.75)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: wide ? 620 : 520, maxHeight: '88vh', overflowY: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,.28)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '22px 28px', borderBottom: '1px solid #f1f5f9', position: 'sticky', top: 0, background: 'white', zIndex: 1 }}>
          <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: '#1c79b4' }}>{title}</h3>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 24, cursor: 'pointer', color: '#9ca3af', lineHeight: 1, padding: '0 4px' }}>×</button>
        </div>
        <div style={{ padding: '24px 28px' }}>{children}</div>
      </div>
    </div>
  );
}

function FF({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{ display: 'block', fontSize: 10, fontWeight: 700, color: '#6b7280', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{label}</label>
      {children}
    </div>
  );
}

function ToggleSwitch({ checked, onChange, label, hint }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', marginBottom: 2 }}>{label}</div>
        <div style={{ fontSize: 11, color: '#9ca3af', lineHeight: 1.45 }}>{hint}</div>
      </div>
      <div
        onClick={onChange}
        role="switch"
        aria-checked={checked}
        style={{ width: 44, height: 24, background: checked ? '#0F2044' : '#d1d5db', borderRadius: 12, cursor: 'pointer', position: 'relative', transition: 'background .22s', flexShrink: 0 }}
      >
        <div style={{ width: 18, height: 18, background: checked ? '#F5A623' : 'white', borderRadius: '50%', position: 'absolute', top: 3, left: checked ? 23 : 3, transition: 'left .22s, background .22s', boxShadow: '0 1px 4px rgba(0,0,0,.22)' }} />
      </div>
    </div>
  );
}

var FI_AC = { width: '100%', padding: '10px 14px', border: '1.5px solid #e5e7eb', borderRadius: 8, fontSize: 14, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box', color: '#1e293b' };
var BTN_P = { background: '#1c79b4', color: 'white', border: 'none', borderRadius: 8, padding: '10px 22px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' };
var BTN_G = { background: '#c4b400', color: '#1c79b4', border: 'none', borderRadius: 8, padding: '8px 16px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' };
var BTN_GH = { background: '#f1f5f9', color: '#475569', border: 'none', borderRadius: 6, padding: '6px 12px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' };
var BTN_D = { background: '#fee2e2', color: '#dc2626', border: 'none', borderRadius: 6, padding: '6px 10px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' };

function AdminContent() {
  const [modules, setModules] = useStateAC(getModules());
  const [expanded, setExpanded] = useStateAC(null);
  const [modal, setModal] = useStateAC(null);
  const [form, setForm] = useStateAC({});
  const [newDoc, setNewDoc] = useStateAC({ nombre: '', url: '' });
  const [questions, setQuestions] = useStateAC([]);

  function refresh() { setModules(getModules()); }
  function sf(k, v) { setForm(function (f) { return Object.assign({}, f, { [k]: v }); }); }

  function openMod(mode, data) {
    setForm(data || {}); setModal({ type: 'mod', mode: mode, data: data });
  }
  function openLesson(mode, modId, data) {
    setForm(data ? Object.assign({}, data) : { docs: [] });
    setNewDoc({ nombre: '', url: '' });
    setModal({ type: 'lesson', mode: mode, modId: modId, data: data });
  }

  function saveMod() {
    var mods = getModules();
    if (modal.mode === 'add') {
      saveModules(mods.concat([{ id: 'm' + Date.now(), titulo: form.titulo || 'Nuevo módulo', descripcion: form.descripcion || '', orden: mods.length + 1, lecciones: [] }]));
    } else {
      saveModules(mods.map(function (m) { return m.id === modal.data.id ? Object.assign({}, m, { titulo: form.titulo, descripcion: form.descripcion }) : m; }));
    }
    setModal(null); refresh();
  }

  function deleteMod(id) {
    if (!window.confirm('¿Eliminar este módulo y todas sus lecciones?')) return;
    saveModules(getModules().filter(function (m) { return m.id !== id; }));
    refresh();
  }

  function saveLesson() {
    var mods = getModules();
    var updated = mods.map(function (m) {
      if (m.id !== modal.modId) return m;
      if (modal.mode === 'add') {
        var nl = { id: 'l' + Date.now(), titulo: form.titulo || 'Nueva lección', duracion: form.duracion || '', videoUrl: form.videoUrl || '', videoType: form.videoType || 'drive', descripcion: form.descripcion || '', docs: form.docs || [] };
        return Object.assign({}, m, { lecciones: m.lecciones.concat([nl]) });
      } else {
        return Object.assign({}, m, { lecciones: m.lecciones.map(function (l) { return l.id === modal.data.id ? Object.assign({}, l, form) : l; }) });
      }
    });
    saveModules(updated); setModal(null); refresh();
  }

  function deleteLesson(modId, lesId) {
    if (!window.confirm('¿Eliminar esta lección?')) return;
    saveModules(getModules().map(function (m) { return m.id === modId ? Object.assign({}, m, { lecciones: m.lecciones.filter(function (l) { return l.id !== lesId; }) }) : m; }));
    refresh();
  }

  function openEval(mode, modId, data) {
    setForm(data ? {
      titulo: data.titulo,
      descripcion: data.descripcion,
      puntajeMinimo: data.puntajeMinimo,
      intentosMaximos: data.intentosMaximos !== undefined ? data.intentosMaximos : 3,
      mostrarRespuestas: data.mostrarRespuestas !== undefined ? data.mostrarRespuestas : true,
      ordenAleatorio: data.ordenAleatorio !== undefined ? data.ordenAleatorio : false
    } : { puntajeMinimo: 70, intentosMaximos: 3, mostrarRespuestas: true, ordenAleatorio: false });
    setQuestions(data && data.preguntas ? data.preguntas.map(function (q) { return Object.assign({}, q, { opciones: q.opciones.map(function (o) { return Object.assign({}, o); }) }); }) : []);
    setModal({ type: 'eval', mode: mode, modId: modId, data: data });
  }
  function addQuestion() {
    var ts = Date.now();
    setQuestions(function (qs) {
      return qs.concat([{ id: 'q' + ts, texto: '', tipo: 'multiple', opciones: [
        { id: 'o1_' + ts, texto: '', correcta: true },
        { id: 'o2_' + ts, texto: '', correcta: false },
        { id: 'o3_' + ts, texto: '', correcta: false },
        { id: 'o4_' + ts, texto: '', correcta: false }
      ] }]);
    });
  }
  function removeQuestion(qIdx) {
    setQuestions(function (qs) { return qs.filter(function (_, i) { return i !== qIdx; }); });
  }
  function updateQField(qIdx, field, value) {
    setQuestions(function (qs) {
      return qs.map(function (q, i) {
        if (i !== qIdx) return q;
        var updated = Object.assign({}, q, { [field]: value });
        if (field === 'tipo' && value === 'vf') {
          updated.opciones = [{ id: 'vfv_' + q.id, texto: 'Verdadero', correcta: true }, { id: 'vff_' + q.id, texto: 'Falso', correcta: false }];
        } else if (field === 'tipo' && value === 'multiple') {
          updated.opciones = [{ id: 'mo1_' + q.id, texto: '', correcta: true }, { id: 'mo2_' + q.id, texto: '', correcta: false }, { id: 'mo3_' + q.id, texto: '', correcta: false }, { id: 'mo4_' + q.id, texto: '', correcta: false }];
        }
        return updated;
      });
    });
  }
  function updateOpTxt(qIdx, oIdx, value) {
    setQuestions(function (qs) {
      return qs.map(function (q, i) {
        if (i !== qIdx) return q;
        return Object.assign({}, q, { opciones: q.opciones.map(function (o, oi) { return oi === oIdx ? Object.assign({}, o, { texto: value }) : o; }) });
      });
    });
  }
  function setCorrect(qIdx, oIdx) {
    setQuestions(function (qs) {
      return qs.map(function (q, i) {
        if (i !== qIdx) return q;
        return Object.assign({}, q, { opciones: q.opciones.map(function (o, oi) { return Object.assign({}, o, { correcta: oi === oIdx }); }) });
      });
    });
  }
  function saveEval() {
    var mods = getModules();
    var evalData = {
      id: (modal.data && modal.data.id) || 'ev' + Date.now(),
      tipo: 'evaluacion',
      titulo: form.titulo || 'Evaluación sin título',
      descripcion: form.descripcion || '',
      puntajeMinimo: parseInt(form.puntajeMinimo, 10) || 70,
      intentosMaximos: parseInt(form.intentosMaximos, 10) || 3,
      mostrarRespuestas: form.mostrarRespuestas !== undefined ? !!form.mostrarRespuestas : true,
      ordenAleatorio: !!form.ordenAleatorio,
      preguntas: questions
    };
    var updated = mods.map(function (m) {
      if (m.id !== modal.modId) return m;
      var evs = m.evaluaciones || [];
      if (modal.mode === 'add') return Object.assign({}, m, { evaluaciones: evs.concat([evalData]) });
      return Object.assign({}, m, { evaluaciones: evs.map(function (ev) { return ev.id === evalData.id ? evalData : ev; }) });
    });
    saveModules(updated); setModal(null); refresh();
  }
  function deleteEval(modId, evalId) {
    if (!window.confirm('¿Eliminar esta evaluación?')) return;
    saveModules(getModules().map(function (m) { return m.id === modId ? Object.assign({}, m, { evaluaciones: (m.evaluaciones || []).filter(function (ev) { return ev.id !== evalId; }) }) : m; }));
    refresh();
  }

  function openSurvey(mode, modId, data) {
    setForm(data ? { titulo: data.titulo, formUrl: data.formUrl } : {});
    setModal({ type: 'survey', mode: mode, modId: modId, data: data });
  }
  function saveSurvey() {
    var mods = getModules();
    var surveyData = {
      id: (modal.data && modal.data.id) || 'enc' + Date.now(),
      tipo: 'encuesta',
      titulo: form.titulo || 'Encuesta sin título',
      formUrl: form.formUrl || ''
    };
    var updated = mods.map(function (m) {
      if (m.id !== modal.modId) return m;
      var encs = m.encuestas || [];
      if (modal.mode === 'add') return Object.assign({}, m, { encuestas: encs.concat([surveyData]) });
      return Object.assign({}, m, { encuestas: encs.map(function (enc) { return enc.id === surveyData.id ? surveyData : enc; }) });
    });
    saveModules(updated); setModal(null); refresh();
  }
  function deleteSurvey(modId, encId) {
    if (!window.confirm('¿Eliminar esta encuesta?')) return;
    saveModules(getModules().map(function (m) { return m.id === modId ? Object.assign({}, m, { encuestas: (m.encuestas || []).filter(function (enc) { return enc.id !== encId; }) }) : m; }));
    refresh();
  }

  function addDoc() {
    if (!newDoc.nombre || !newDoc.url) return;
    setForm(function (f) { return Object.assign({}, f, { docs: (f.docs || []).concat([{ id: 'd' + Date.now(), nombre: newDoc.nombre, url: newDoc.url }]) }); });
    setNewDoc({ nombre: '', url: '' });
  }

  function removeDoc(docId) {
    setForm(function (f) { return Object.assign({}, f, { docs: (f.docs || []).filter(function (d) { return d.id !== docId; }) }); });
  }

  var totalLessons = modules.reduce(function (a, m) { return a + m.lecciones.length + (m.evaluaciones || []).length + (m.encuestas || []).length; }, 0);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: '#1c79b4' }}>Contenido del Curso</h2>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: '#6b7280' }}>{modules.length} módulos · {totalLessons} elementos en total</p>
        </div>
        <button style={BTN_G} onClick={function () { openMod('add'); }}>+ Nuevo módulo</button>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {modules.map(function (mod, idx) {
          var isOpen = expanded === mod.id;
          return (
            <div key={mod.id} style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', overflow: 'hidden' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 20px' }}>
                <div style={{ width: 38, height: 38, background: '#1c79b4', borderRadius: 9, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#c4b400', fontSize: 14, fontWeight: 800, flexShrink: 0 }}>{idx + 1}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14, color: '#1c79b4' }}>{mod.titulo}</div>
                  <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 2 }}>{mod.lecciones.length} lección{mod.lecciones.length !== 1 ? 'es' : ''}{(mod.evaluaciones || []).length > 0 ? ' · ' + (mod.evaluaciones || []).length + ' evaluación' + ((mod.evaluaciones || []).length !== 1 ? 'es' : '') : ''}{(mod.encuestas || []).length > 0 ? ' · ' + (mod.encuestas || []).length + ' encuesta' + ((mod.encuestas || []).length !== 1 ? 's' : '') : ''}</div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button style={BTN_GH} onClick={function () { openMod('edit', mod); }}>Editar</button>
                  <button style={BTN_D} onClick={function () { deleteMod(mod.id); }}>Eliminar</button>
                  <button style={Object.assign({}, BTN_GH, { fontWeight: 700, minWidth: 36 })} onClick={function () { setExpanded(isOpen ? null : mod.id); }}>{isOpen ? '▲' : '▼'}</button>
                </div>
              </div>

              {isOpen && (
                <div style={{ borderTop: '1px solid #f1f5f9' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 20px 8px' }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Lecciones</span>
                    <div style={{ display: 'flex', gap: 6 }}>
                      <button style={Object.assign({}, BTN_GH, { padding: '5px 12px', fontSize: 11, fontWeight: 700 })} onClick={function () { openLesson('add', mod.id); }}>+ Lección</button>
                      <button style={Object.assign({}, BTN_G, { padding: '5px 12px', fontSize: 11 })} onClick={function () { openEval('add', mod.id); }}>+ Evaluación</button>
                      <button style={Object.assign({}, BTN_GH, { padding: '5px 12px', fontSize: 11, fontWeight: 700, color: '#b87800', border: '1px solid rgba(245,166,35,.45)' })} onClick={function () { openSurvey('add', mod.id); }}>⭐ Encuesta</button>
                    </div>
                  </div>
                  {mod.lecciones.length === 0 && <div style={{ textAlign: 'center', padding: '20px 0', color: '#d1d5db', fontSize: 13 }}>Sin lecciones aún</div>}
                  {mod.lecciones.map(function (les, li) {
                    return (
                      <div key={les.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 20px', borderTop: '1px solid #f9fafb' }}>
                        <div style={{ width: 26, height: 26, background: '#f8fafc', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: '#94a3b8', flexShrink: 0 }}>{li + 1}</div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>{les.titulo}</div>
                          <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1, display: 'flex', gap: 10 }}>
                            <span>{les.duracion || '—'}</span>
                            {les.videoUrl && <span style={{ color: '#16a34a' }}>● {les.videoType === 'youtube' ? 'YouTube' : 'Drive'}</span>}
                            {les.docs && les.docs.length > 0 && <span style={{ color: '#c4b400' }}>📎 {les.docs.length} doc</span>}
                          </div>
                        </div>
                        <div style={{ display: 'flex', gap: 6 }}>
                          <button style={BTN_GH} onClick={function () { openLesson('edit', mod.id, les); }}>Editar</button>
                          <button style={BTN_D} onClick={function () { deleteLesson(mod.id, les.id); }}>×</button>
                        </div>
                      </div>
                    );
                  })}
                  {(mod.evaluaciones || []).map(function (ev) {
                    return (
                      <div key={ev.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 20px', borderTop: '1px solid #f9fafb' }}>
                        <div style={{ width: 26, height: 26, background: 'rgba(196,180,0,0.15)', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flexShrink: 0 }}>📝</div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>{ev.titulo}</div>
                          <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1, display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                            <span style={{ color: '#c4b400', fontWeight: 700 }}>Evaluación</span>
                            <span>{ev.preguntas.length} pregunta{ev.preguntas.length !== 1 ? 's' : ''}</span>
                            <span>Mín. {ev.puntajeMinimo}%</span>
                            <span style={{ color: '#6b7280' }}>· {ev.intentosMaximos || 3} intentos máx.</span>
                            {ev.ordenAleatorio && <span style={{ background: 'rgba(15,32,68,.08)', color: '#0F2044', borderRadius: 5, padding: '1px 7px', fontSize: 10, fontWeight: 700, letterSpacing: '0.03em' }}>🔀 Aleatorio</span>}
                            {ev.mostrarRespuestas === false && <span style={{ background: 'rgba(239,68,68,.08)', color: '#b91c1c', borderRadius: 5, padding: '1px 7px', fontSize: 10, fontWeight: 700, letterSpacing: '0.03em' }}>Sin respuestas</span>}
                          </div>
                        </div>
                        <div style={{ display: 'flex', gap: 6 }}>
                          <button style={BTN_GH} onClick={function () { openEval('edit', mod.id, ev); }}>Editar</button>
                          <button style={BTN_D} onClick={function () { deleteEval(mod.id, ev.id); }}>×</button>
                        </div>
                      </div>
                    );
                  })}
                  {(mod.encuestas || []).map(function (enc) {
                    return (
                      <div key={enc.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 20px', borderTop: '1px solid #f9fafb' }}>
                        <div style={{ width: 26, height: 26, background: 'rgba(245,166,35,0.15)', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flexShrink: 0 }}>⭐</div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>{enc.titulo}</div>
                          <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1, display: 'flex', gap: 8, alignItems: 'center' }}>
                            <span style={{ color: '#b87800', fontWeight: 700 }}>Encuesta</span>
                            {enc.formUrl ? <span style={{ color: '#22c55e', fontWeight: 600 }}>· Link configurado</span> : <span style={{ color: '#ef4444' }}>· Sin link</span>}
                          </div>
                        </div>
                        <div style={{ display: 'flex', gap: 6 }}>
                          <button style={BTN_GH} onClick={function () { openSurvey('edit', mod.id, enc); }}>Editar</button>
                          <button style={BTN_D} onClick={function () { deleteSurvey(mod.id, enc.id); }}>×</button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Modal módulo */}
      {modal && modal.type === 'mod' && (
        <SSTModal title={modal.mode === 'add' ? 'Nuevo módulo' : 'Editar módulo'} onClose={function () { setModal(null); }}>
          <FF label="Título del módulo">
            <input style={FI_AC} value={form.titulo || ''} onChange={function (e) { sf('titulo', e.target.value); }} placeholder="Ej: Identificación de Peligros" />
          </FF>
          <FF label="Descripción">
            <textarea style={Object.assign({}, FI_AC, { height: 80, resize: 'vertical' })} value={form.descripcion || ''} onChange={function (e) { sf('descripcion', e.target.value); }} placeholder="Descripción breve del módulo" />
          </FF>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
            <button style={BTN_GH} onClick={function () { setModal(null); }}>Cancelar</button>
            <button style={BTN_P} onClick={saveMod}>Guardar módulo</button>
          </div>
        </SSTModal>
      )}

      {/* Modal lección */}
      {modal && modal.type === 'lesson' && (
        <SSTModal title={modal.mode === 'add' ? 'Nueva lección' : 'Editar lección'} onClose={function () { setModal(null); }} wide>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div style={{ gridColumn: 'span 2' }}>
              <FF label="Título de la lección">
                <input style={FI_AC} value={form.titulo || ''} onChange={function (e) { sf('titulo', e.target.value); }} placeholder="Ej: Jerarquía de Controles" />
              </FF>
            </div>
            <FF label="Duración">
              <input style={FI_AC} value={form.duracion || ''} onChange={function (e) { sf('duracion', e.target.value); }} placeholder="Ej: 15 min" />
            </FF>
            <FF label="Tipo de video">
              <select style={FI_AC} value={form.videoType || 'drive'} onChange={function (e) { sf('videoType', e.target.value); }}>
                <option value="drive">Google Drive</option>
                <option value="youtube">YouTube</option>
              </select>
            </FF>
            <FF label={form.videoType === 'youtube' ? 'URL Video YouTube' : 'URL Video Google Drive'}>
              <input style={FI_AC} value={form.videoUrl || ''} onChange={function (e) { sf('videoUrl', e.target.value); }} placeholder={form.videoType === 'youtube' ? 'https://www.youtube.com/watch?v=ID' : 'https://drive.google.com/file/d/ID/view'} />
            </FF>
            <div style={{ gridColumn: 'span 2' }}>
              <FF label="Descripción">
                <textarea style={Object.assign({}, FI_AC, { height: 72, resize: 'vertical' })} value={form.descripcion || ''} onChange={function (e) { sf('descripcion', e.target.value); }} />
              </FF>
            </div>
          </div>
          <FF label="Documentos descargables">
            {(form.docs || []).map(function (doc) {
              return (
                <div key={doc.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: '#f8fafc', borderRadius: 7, marginBottom: 6, fontSize: 13 }}>
                  <span style={{ fontSize: 14 }}>📎</span>
                  <span style={{ flex: 1, fontWeight: 500, color: '#374151' }}>{doc.nombre}</span>
                  <button style={BTN_D} onClick={function () { removeDoc(doc.id); }}>×</button>
                </div>
              );
            })}
            <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
              <input style={Object.assign({}, FI_AC, { flex: 1, fontSize: 12 })} value={newDoc.nombre} onChange={function (e) { setNewDoc(function (d) { return Object.assign({}, d, { nombre: e.target.value }); }); }} placeholder="Nombre del documento" />
              <input style={Object.assign({}, FI_AC, { flex: 2, fontSize: 12 })} value={newDoc.url} onChange={function (e) { setNewDoc(function (d) { return Object.assign({}, d, { url: e.target.value }); }); }} placeholder="URL (Drive, Dropbox...)" />
              <button style={Object.assign({}, BTN_G, { whiteSpace: 'nowrap', padding: '8px 14px' })} onClick={addDoc}>+ Agregar</button>
            </div>
          </FF>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
            <button style={BTN_GH} onClick={function () { setModal(null); }}>Cancelar</button>
            <button style={BTN_P} onClick={saveLesson}>Guardar lección</button>
          </div>
        </SSTModal>
      )}
      {/* Modal encuesta */}
      {modal && modal.type === 'survey' && (
        <SSTModal title={modal.mode === 'add' ? 'Nueva encuesta' : 'Editar encuesta'} onClose={function () { setModal(null); }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 14px', background: 'rgba(245,166,35,0.08)', borderRadius: 9, border: '1px solid rgba(245,166,35,.3)', marginBottom: 18 }}>
            <span style={{ fontSize: 20, flexShrink: 0 }}>⭐</span>
            <div style={{ fontSize: 12, color: '#92630a', lineHeight: 1.5 }}>El estudiante verá un botón dorado <strong>"Responder encuesta →"</strong> que abre el formulario en una nueva pestaña. El link nunca se muestra directamente.</div>
          </div>
          <FF label="Nombre de la encuesta">
            <input style={FI_AC} value={form.titulo || ''} onChange={function (e) { sf('titulo', e.target.value); }} placeholder="Ej: Calificación de satisfacción Módulo 1" />
          </FF>
          <FF label="Link de Google Form">
            <input style={FI_AC} value={form.formUrl || ''} onChange={function (e) { sf('formUrl', e.target.value); }} placeholder="https://forms.gle/..." />
          </FF>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
            <button style={BTN_GH} onClick={function () { setModal(null); }}>Cancelar</button>
            <button style={{ background: '#F5A623', color: '#0F2044', border: 'none', borderRadius: 8, padding: '10px 22px', fontSize: 13, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit' }} onClick={saveSurvey}>Guardar encuesta</button>
          </div>
        </SSTModal>
      )}

      {/* Modal evaluación */}
      {modal && modal.type === 'eval' && (
        <SSTModal title={modal.mode === 'add' ? 'Nueva evaluación' : 'Editar evaluación'} onClose={function () { setModal(null); }} wide>
          <FF label="Nombre de la evaluación">
            <input style={FI_AC} value={form.titulo || ''} onChange={function (e) { sf('titulo', e.target.value); }} placeholder="Ej: Evaluación Final del Módulo" />
          </FF>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div style={{ gridColumn: 'span 2' }}>
              <FF label="Descripción breve">
                <textarea style={Object.assign({}, FI_AC, { height: 64, resize: 'vertical' })} value={form.descripcion || ''} onChange={function (e) { sf('descripcion', e.target.value); }} placeholder="Descripción de la evaluación" />
              </FF>
            </div>
            <FF label="Puntaje mínimo para aprobar (%)">
              <input type="number" min="0" max="100" style={Object.assign({}, FI_AC, { width: '100%' })} value={form.puntajeMinimo !== undefined ? form.puntajeMinimo : 70} onChange={function (e) { sf('puntajeMinimo', e.target.value); }} />
            </FF>
            <FF label="Número máximo de intentos">
              <input type="number" min="1" max="99" style={Object.assign({}, FI_AC, { width: '100%' })} value={form.intentosMaximos !== undefined ? form.intentosMaximos : 3} onChange={function (e) { sf('intentosMaximos', e.target.value); }} />
            </FF>
          </div>

          {/* ── Opciones de comportamiento ── */}
          <div style={{ background: '#f8fafc', borderRadius: 10, border: '1px solid #e5e7eb', padding: '14px 18px', marginBottom: 18 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>Opciones de comportamiento</div>
            <ToggleSwitch
              checked={form.mostrarRespuestas !== false}
              onChange={function () { sf('mostrarRespuestas', form.mostrarRespuestas === false ? true : false); }}
              label="Mostrar respuestas correctas al estudiante"
              hint={form.mostrarRespuestas !== false
                ? 'El estudiante verá cuáles respondió bien y cuáles mal'
                : 'Solo verá su puntaje y si aprobó o no'}
            />
            <div style={{ borderTop: '1px solid #e5e7eb', margin: '14px 0' }} />
            <ToggleSwitch
              checked={!!form.ordenAleatorio}
              onChange={function () { sf('ordenAleatorio', !form.ordenAleatorio); }}
              label="Preguntas en orden aleatorio"
              hint={form.ordenAleatorio
                ? 'Cada intento presenta las preguntas en orden diferente'
                : 'Las preguntas aparecen siempre en el orden creado'}
            />
          </div>

          <div style={{ borderTop: '1px solid #f1f5f9', paddingTop: 16, marginTop: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <span style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Preguntas ({questions.length})</span>
              <button style={Object.assign({}, BTN_G, { padding: '6px 14px', fontSize: 11 })} onClick={addQuestion}>+ Agregar pregunta</button>
            </div>
            {questions.length === 0 && (
              <div style={{ textAlign: 'center', padding: '20px 0', color: '#d1d5db', fontSize: 13, border: '1px dashed #e5e7eb', borderRadius: 8 }}>Sin preguntas aún</div>
            )}
            {questions.map(function (q, qi) {
              return (
                <div key={q.id} style={{ background: '#f8fafc', borderRadius: 10, padding: '16px', marginBottom: 12, border: '1px solid #e5e7eb' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: '#1c79b4', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Pregunta {qi + 1}</span>
                    <button style={Object.assign({}, BTN_D, { padding: '4px 10px', fontSize: 11 })} onClick={function () { removeQuestion(qi); }}>× Eliminar</button>
                  </div>
                  <FF label="Texto de la pregunta">
                    <textarea style={Object.assign({}, FI_AC, { height: 56, resize: 'vertical', background: 'white' })} value={q.texto} onChange={function (e) { updateQField(qi, 'texto', e.target.value); }} placeholder="Escribe la pregunta aquí..." />
                  </FF>
                  <FF label="Tipo">
                    <div style={{ display: 'flex', gap: 8 }}>
                      <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 12, padding: '7px 14px', borderRadius: 7, border: '1.5px solid ' + (q.tipo === 'multiple' ? '#1c79b4' : '#e5e7eb'), background: q.tipo === 'multiple' ? 'rgba(28,121,180,.07)' : 'white', fontFamily: 'inherit', fontWeight: q.tipo === 'multiple' ? 700 : 400 }}>
                        <input type="radio" name={'tipo_' + q.id} value="multiple" checked={q.tipo === 'multiple'} onChange={function () { updateQField(qi, 'tipo', 'multiple'); }} style={{ accentColor: '#1c79b4' }} />
                        Selección múltiple
                      </label>
                      <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 12, padding: '7px 14px', borderRadius: 7, border: '1.5px solid ' + (q.tipo === 'vf' ? '#1c79b4' : '#e5e7eb'), background: q.tipo === 'vf' ? 'rgba(28,121,180,.07)' : 'white', fontFamily: 'inherit', fontWeight: q.tipo === 'vf' ? 700 : 400 }}>
                        <input type="radio" name={'tipo_' + q.id} value="vf" checked={q.tipo === 'vf'} onChange={function () { updateQField(qi, 'tipo', 'vf'); }} style={{ accentColor: '#1c79b4' }} />
                        Verdadero / Falso
                      </label>
                    </div>
                  </FF>
                  <div>
                    <label style={{ display: 'block', fontSize: 10, fontWeight: 700, color: '#6b7280', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Opciones <span style={{ color: '#22c55e', fontWeight: 600 }}>(● = correcta)</span></label>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                      {q.opciones.map(function (op, oi) {
                        return (
                          <div key={op.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <input type="radio" name={'correct_' + q.id} checked={op.correcta} onChange={function () { setCorrect(qi, oi); }} style={{ accentColor: '#22c55e', cursor: 'pointer', width: 16, height: 16, flexShrink: 0 }} title="Marcar como correcta" />
                            {q.tipo === 'vf' ? (
                              <div style={{ flex: 1, padding: '8px 12px', background: 'white', borderRadius: 7, border: '1.5px solid ' + (op.correcta ? '#22c55e' : '#e5e7eb'), fontSize: 13, color: '#374151', fontWeight: op.correcta ? 700 : 400 }}>{op.texto}</div>
                            ) : (
                              <input style={Object.assign({}, FI_AC, { flex: 1, margin: 0, background: 'white', borderColor: op.correcta ? '#22c55e' : '#e5e7eb', fontSize: 12 })} value={op.texto} onChange={function (e) { updateOpTxt(qi, oi, e.target.value); }} placeholder={'Opción ' + (oi + 1) + (op.correcta ? ' (correcta)' : '')} />
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 16 }}>
            <button style={BTN_GH} onClick={function () { setModal(null); }}>Cancelar</button>
            <button style={BTN_P} onClick={saveEval}>Guardar evaluación</button>
          </div>
        </SSTModal>
      )}

    </div>
  );
}

window.AdminContent = AdminContent;
window.SSTModal = SSTModal;
