// ───────────────────────── Step 4 · Previsualización y edición de preguntas ─────────────────────────

function AutoTextarea({ value, onChange, className = '', placeholder, readOnly }) {
  const ref = React.useRef(null);
  const resize = () => { const el = ref.current; if (el) { el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; } };
  React.useLayoutEffect(resize, [value]);
  return (
    <textarea ref={ref} value={value} placeholder={placeholder} readOnly={readOnly}
      onChange={(e) => onChange(e.target.value)} rows={1}
      className={cx('w-full resize-none overflow-hidden bg-transparent outline-none leading-snug', className)} />
  );
}

// alternative phrasings used when "regenerating" a question
const REGEN_VARIANTS = {
  q1: ['Indica cuál es la unidad más pequeña capaz de realizar las funciones vitales.', '¿Qué nivel de organización constituye la base de todos los organismos vivos?'],
  q2: ['Marca todas las estructuras que encontrarías en el interior de una célula animal.', '¿Cuáles de los siguientes orgánulos son propios de la célula eucariota animal?'],
  q3: ['Las células {{procariotas}} carecen de núcleo, a diferencia de las {{eucariotas}}, que lo tienen rodeado de membrana.'],
  q4: ['Describe las principales diferencias estructurales entre la célula vegetal y la animal.', 'Compara la célula animal y la vegetal señalando los orgánulos exclusivos de cada una.'],
};

// pool de preguntas "generadas por IA" al añadir una nueva
const AI_QUESTION_POOL = [
  {
    type: 'simple',
    text: '¿Qué orgánulo se encarga de la respiración celular y la obtención de energía?',
    options: [
      { text: 'El núcleo', correct: false },
      { text: 'La mitocondria', correct: true },
      { text: 'El ribosoma', correct: false },
      { text: 'La vacuola', correct: false },
    ],
  },
  {
    type: 'multiple',
    text: 'Selecciona las estructuras exclusivas de la célula vegetal.',
    options: [
      { text: 'Pared celular de celulosa', correct: true },
      { text: 'Cloroplastos', correct: true },
      { text: 'Mitocondrias', correct: false },
      { text: 'Vacuola central de gran tamaño', correct: true },
    ],
  },
  {
    type: 'fill',
    text: 'El proceso por el que las plantas fabrican su alimento usando la luz se llama {{fotosíntesis}} y ocurre en los {{cloroplastos}}.',
  },
  {
    type: 'short',
    text: '¿Cómo se llama la membrana que rodea y delimita la célula?',
  },
  {
    type: 'essay',
    text: 'Explica por qué se considera la célula la unidad básica de la vida.',
    rubric: 'Valora la mención a las funciones vitales y a la teoría celular.',
  },
];

// Blank question scaffold for a given type (used by "Añadir manualmente")
function blankQuestionOfType(type) {
  const base = { id: 'q' + Date.now(), type, text: '', validated: false };
  if (type === 'simple') base.options = [{ id: 'a', text: '', correct: true }, { id: 'b', text: '', correct: false }];
  else if (type === 'multiple') base.options = [{ id: 'a', text: '', correct: false }, { id: 'b', text: '', correct: false }, { id: 'c', text: '', correct: false }];
  else if (type === 'essay') base.rubric = '';
  return base;
}

// Modal to choose the question type before adding (manual or AI)
function QuestionTypeModal({ mode, onPick, onClose }) {
  const isAI = mode === 'ai';
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  return ReactDOM.createPortal((
    <div className="fixed inset-0 z-[60] bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 anim-fade-in" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} className="bg-white rounded-2xl shadow-pop w-[min(520px,94vw)] anim-fade-up overflow-hidden">
        <div className="flex items-start gap-3.5 px-6 pt-6 pb-4">
          <div className={cx('w-11 h-11 rounded-xl flex items-center justify-center shrink-0', isAI ? 'bg-primary-50 text-primary-800' : 'bg-canvas text-ink')}>
            <Icon name={isAI ? 'sparkle' : 'plus'} size={22} />
          </div>
          <div className="min-w-0">
            <h3 className="text-[18px] font-extrabold text-ink tracking-tight">
              {isAI ? 'Generar pregunta con IA' : 'Añadir pregunta manualmente'}
            </h3>
            <p className="text-[13.5px] text-muted mt-0.5">
              {isAI ? 'Elige el tipo de pregunta que quieres que la IA redacte.' : 'Elige el tipo de pregunta que quieres crear.'}
            </p>
          </div>
          <button onClick={onClose} aria-label="Cerrar" className="ml-auto w-9 h-9 rounded-lg flex items-center justify-center text-muted hover:bg-canvas hover:text-ink transition-colors shrink-0">
            <Icon name="x" size={20} />
          </button>
        </div>
        <div className="px-6 pb-6 grid grid-cols-1 gap-2">
          {QUESTION_TYPES.map(t => (
            <button key={t.id} onClick={() => onPick(t.id)}
              className="group flex items-center gap-3.5 px-4 py-3 rounded-xl border border-line bg-white text-left hover:border-primary-300 hover:bg-primary-50/40 transition-all">
              <span className="w-10 h-10 rounded-lg bg-canvas text-ink flex items-center justify-center shrink-0 group-hover:bg-primary group-hover:text-white transition-colors">
                <Icon name={t.icon} size={20} />
              </span>
              <span className="min-w-0">
                <span className="block text-[14.5px] font-bold text-ink">{t.label}</span>
                <span className="block text-[12.5px] text-muted">{t.desc}</span>
              </span>
              <Icon name={isAI ? 'sparkle' : 'arrow-right'} size={18} className="ml-auto text-faint group-hover:text-primary-800 transition-colors shrink-0" />
            </button>
          ))}
        </div>
      </div>
    </div>
  ), document.body);
}

window.QuestionTypeModal = QuestionTypeModal;
window.blankQuestionOfType = blankQuestionOfType;

function OptionRow({ opt, multiple, onText, onToggle, onDelete, canDelete }) {
  return (
    <div className={cx('group flex items-center gap-3 px-3.5 py-2.5 rounded-xl border transition-colors',
      opt.correct ? 'border-primary-200 bg-primary-50/40' : 'border-line bg-white hover:border-[#dcdce2]')}>
      {multiple
        ? <Checkbox checked={opt.correct} onChange={onToggle} />
        : <Radio checked={opt.correct} onChange={onToggle} />}
      <input value={opt.text} onChange={(e) => onText(e.target.value)}
        className="flex-1 bg-transparent outline-none text-[14px] text-ink placeholder:text-faint rounded-md px-2 py-1 -mx-1 ring-1 ring-transparent hover:bg-black/[0.035] focus:bg-white focus:ring-primary-200 transition-all"
        placeholder="Texto de la opción…" />
      {opt.correct && <span className="text-[11px] font-bold text-primary-800 flex items-center gap-1"><Icon name="check-circle" size={14} />Correcta</span>}
      <button onClick={onDelete} disabled={!canDelete}
        className="opacity-0 group-hover:opacity-100 transition-opacity text-faint hover:text-[#E45455] disabled:opacity-0">
        <Icon name="x" size={16} strokeWidth={2.2} />
      </button>
    </div>
  );
}

function QuestionBody({ q, update }) {
  if (q.type === 'simple' || q.type === 'multiple') {
    const setOpt = (oid, patch) => update({ options: q.options.map(o => o.id === oid ? { ...o, ...patch } : o) });
    const toggle = (oid) => {
      if (q.type === 'multiple') setOpt(oid, { correct: !q.options.find(o => o.id === oid).correct });
      else update({ options: q.options.map(o => ({ ...o, correct: o.id === oid })) });
    };
    const del = (oid) => update({ options: q.options.filter(o => o.id !== oid) });
    const add = () => update({ options: [...q.options, { id: 'o' + Date.now(), text: '', correct: false }] });
    return (
      <div className="space-y-2">
        {q.options.map(o => (
          <OptionRow key={o.id} opt={o} multiple={q.type === 'multiple'}
            onText={(t) => setOpt(o.id, { text: t })} onToggle={() => toggle(o.id)}
            onDelete={() => del(o.id)} canDelete={q.options.length > 2} />
        ))}
        <button onClick={add} className="flex items-center gap-2 text-[13px] font-semibold text-primary-800 hover:text-primary-900 px-3.5 py-2">
          <Icon name="plus" size={16} strokeWidth={2.4} /> Añadir opción
        </button>
      </div>
    );
  }
  if (q.type === 'fill') {
    const parts = q.text.split(/(\{\{[^}]+\}\})/g);
    return (
      <div className="space-y-3">
        <div className="px-4 py-3.5 rounded-xl bg-canvas/70 border border-line text-[14.5px] leading-loose text-ink">
          {parts.map((p, i) => {
            const m = p.match(/^\{\{([^}]+)\}\}$/);
            return m
              ? <span key={i} className="inline-flex items-center mx-0.5 px-2.5 py-0.5 rounded-md bg-primary-100 text-primary-800 font-semibold border border-primary-200">{m[1]}</span>
              : <span key={i}>{p}</span>;
          })}
        </div>
        <label className="block">
          <span className="text-[12px] font-semibold text-muted">Texto editable · usa <code className="text-primary-800">{'{{palabra}}'}</code> para crear un hueco</span>
          <AutoTextarea value={q.text} onChange={(t) => update({ text: t })}
            className="mt-1.5 text-[14px] text-ink bg-white border border-line rounded-xl px-3.5 py-2.5 hover:border-primary-300 focus:border-primary focus:ring-2 focus:ring-primary-100 transition-all" />
        </label>
      </div>
    );
  }
  if (q.type === 'essay') {
    return (
      <div className="space-y-3">
        <div className="px-4 py-3 rounded-xl border border-dashed border-line bg-canvas/50 text-[13.5px] text-muted italic">
          El alumnado escribirá aquí su respuesta desarrollada…
        </div>
        <label className="block">
          <span className="text-[12px] font-semibold text-muted flex items-center gap-1.5"><Icon name="info" size={14} />Guía de corrección (opcional)</span>
          <AutoTextarea value={q.rubric || ''} onChange={(t) => update({ rubric: t })}
            placeholder="Escribe aquí los criterios para corregir esta respuesta…"
            className="mt-1.5 text-[13.5px] text-ink bg-white border border-line rounded-xl px-3.5 py-2.5 hover:border-primary-300 focus:border-primary focus:ring-2 focus:ring-primary-100 transition-all" />
        </label>
      </div>
    );
  }
  // short
  return (
    <div className="flex items-center gap-3 px-4 py-3 rounded-xl border border-line bg-canvas/50">
      <Icon name="type" size={18} className="text-muted" />
      <span className="text-[13.5px] text-muted">Respuesta corta — una palabra o frase breve</span>
    </div>
  );
}

function QuestionCard({ q, index, total, update, onMove, onDelete, onRegen, regenerating, validated, onToggleValid, dnd, flash }) {
  const t = QTYPE[q.type];
  const [grab, setGrab] = React.useState(false);
  const [menu, setMenu] = React.useState(false);
  return (
    <div id={'q-card-' + q.id}
      draggable={grab}
      onDragStart={() => dnd.onDragStart(q.id)}
      onDragEnter={() => dnd.onDragEnter(q.id)}
      onDragOver={(e) => e.preventDefault()}
      onDragEnd={() => { setGrab(false); dnd.onDragEnd(); }}
      className={cx('transition-opacity', dnd.dragging && 'opacity-40')}>
    <Card style={validated ? { borderLeft: '3px solid #34B27B' } : undefined}
      className={cx('overflow-hidden transition-all', regenerating && 'pointer-events-none',
      flash && 'ring-2 ring-primary shadow-cardhover')}>
      <div style={validated ? { backgroundColor: '#F1FAF4' } : undefined}
        className={cx('flex items-center gap-2.5 px-4 py-3 border-b border-line transition-colors', !validated && 'bg-canvas/40')}>
        <button onMouseDown={() => setGrab(true)} onMouseUp={() => setGrab(false)} onMouseLeave={() => setGrab(false)}
          title="Arrastra para reordenar" aria-label="Reordenar"
          className="text-faint hover:text-muted cursor-grab active:cursor-grabbing shrink-0">
          <Icon name="drag" size={18} />
        </button>
        <span className="w-7 h-7 rounded-lg bg-slate2 text-white text-[13px] font-bold flex items-center justify-center tabular-nums shrink-0">{index + 1}</span>
        <Badge tone="primary"><Icon name={t.icon} size={13} />{t.label}</Badge>
        {validated && <Badge tone="green"><Icon name="check" size={12} strokeWidth={3} />Validada</Badge>}
        <div className="flex-1" />
        {/* Validar — acción principal de revisión */}
        <button onClick={onToggleValid}
          className={cx('inline-flex items-center gap-1.5 h-8 px-3 rounded-lg text-[12.5px] font-semibold border transition-colors',
            validated ? 'bg-[#e7f7ee] text-[#1f8a52] border-[#bfe6cf] hover:bg-[#daf1e3]' : 'bg-white text-muted border-line hover:border-[#34B27B] hover:text-[#1f8a52]')}>
          <Icon name="check-circle" size={15} strokeWidth={2} />
          {validated ? 'Validada' : 'Validar'}
        </button>
        {/* Regenerar con IA — botón con texto */}
        <button onClick={onRegen} title="Regenerar con IA" aria-label="Regenerar con IA"
          className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg text-[12.5px] font-semibold border border-line bg-white text-muted hover:border-primary-300 hover:text-primary-800 transition-colors shrink-0">
          <Icon name="sparkle" size={15} />
          Regenerar
        </button>
        {/* Overflow: mover / eliminar (lejos de acciones frecuentes) */}
        <div className="relative shrink-0">
          <button onClick={() => setMenu(m => !m)} title="Más acciones" aria-label="Más acciones"
            className="w-8 h-8 rounded-lg flex items-center justify-center text-muted hover:bg-canvas hover:text-ink transition-colors">
            <Icon name="menu-dots" size={18} />
          </button>
          {menu && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setMenu(false)} />
              <div className="absolute right-0 top-10 z-20 w-48 bg-white rounded-xl border border-line shadow-pop py-1.5 anim-fade-in">
                <button onClick={() => { setMenu(false); onMove(-1); }} disabled={index === 0}
                  className="w-full flex items-center gap-3 px-3.5 py-2 text-sm text-ink hover:bg-canvas disabled:opacity-40 disabled:hover:bg-transparent transition-colors">
                  <Icon name="arrow-up" size={16} className="text-muted" />Mover arriba</button>
                <button onClick={() => { setMenu(false); onMove(1); }} disabled={index === total - 1}
                  className="w-full flex items-center gap-3 px-3.5 py-2 text-sm text-ink hover:bg-canvas disabled:opacity-40 disabled:hover:bg-transparent transition-colors">
                  <Icon name="arrow-down" size={16} className="text-muted" />Mover abajo</button>
                <div className="my-1.5 h-px bg-line" />
                <button onClick={() => { setMenu(false); onDelete(); }}
                  className="w-full flex items-center gap-3 px-3.5 py-2 text-sm text-[#E45455] hover:bg-[#fdeced] transition-colors">
                  <Icon name="trash" size={16} />Eliminar</button>
              </div>
            </>
          )}
        </div>
      </div>

      <div className="p-5 relative">
        {regenerating && (
          <div className="absolute inset-0 z-10 bg-white/80 backdrop-blur-[1px] flex items-center justify-center anim-fade-in">
            <span className="inline-flex items-center gap-2.5 text-primary-800 text-sm font-semibold">
              <Icon name="sparkle" size={18} className="animate-pulse" /> La IA está reescribiendo la pregunta…
            </span>
          </div>
        )}
        {q.type !== 'fill' ? (
          <div className="mb-4">
            <AutoTextarea value={q.text} onChange={(val) => update({ text: val })}
              className="text-[16px] font-semibold text-ink rounded-lg px-3 py-2 w-full border border-line hover:border-primary-300 hover:bg-canvas/40 focus:bg-white focus:border-primary focus:ring-2 focus:ring-primary-100 transition-all"
              placeholder="Escribe el enunciado…" />
          </div>
        ) : (
          <p className="text-[16px] font-semibold text-ink leading-snug mb-4">Completa el texto con las palabras correctas:</p>
        )}

        <QuestionBody q={q} update={update} />

        {q.resource && (
          <div className="mt-4 flex items-center gap-3 px-4 py-3 rounded-xl border border-primary-200 bg-primary-50/40">
            <div className="w-16 h-12 rounded-lg bg-gradient-to-br from-primary-100 to-primary-50 flex items-center justify-center text-primary-600"><Icon name="image" size={22} /></div>
            <div className="flex-1">
              <p className="text-[13px] font-semibold text-ink">esquema-celula.png</p>
              <p className="text-[11.5px] text-muted">Recurso adjunto a la pregunta</p>
            </div>
            <IconButton name="x" label="Quitar recurso" size={16} onClick={() => update({ resource: false })} />
          </div>
        )}

        <div className="mt-4 pt-4 border-t border-line flex items-center gap-2">
          {!q.resource && (
            <Button variant="outline" size="sm" icon="image" onClick={() => update({ resource: true })}>Añadir recurso / imagen</Button>
          )}
        </div>
      </div>
    </Card>
    </div>
  );
}

function QuestionsStep({ questions, setQuestions, config = {} }) {
  const [regenId, setRegenId] = React.useState(null);
  const [regenAll, setRegenAll] = React.useState(false);
  const [addingAI, setAddingAI] = React.useState(false);
  const [dragId, setDragId] = React.useState(null);
  const [flashId, setFlashId] = React.useState(null);

  const update = (id, patch) => setQuestions(qs => qs.map(q => q.id === id ? { ...q, ...patch } : q));
  const move = (id, dir) => setQuestions(qs => {
    const i = qs.findIndex(q => q.id === id); const j = i + dir;
    if (j < 0 || j >= qs.length) return qs;
    const next = [...qs]; [next[i], next[j]] = [next[j], next[i]]; return next;
  });
  const del = (id) => setQuestions(qs => qs.filter(q => q.id !== id));
  const toggleValid = (id) => setQuestions(qs => qs.map(q => q.id === id ? { ...q, validated: !q.validated } : q));
  const validateAll = (on) => setQuestions(qs => qs.map(q => ({ ...q, validated: on })));
  const regen = (id) => {
    setRegenId(id);
    setTimeout(() => {
      const variants = REGEN_VARIANTS[id];
      if (variants) {
        const next = variants[Math.floor(Math.random() * variants.length)];
        update(id, { text: next });
      }
      setRegenId(null);
    }, 1100);
  };
  const regenerarTodo = () => {
    setRegenAll(true);
    setTimeout(() => {
      const fresh = makeGeneratedQuestions().map(q => {
        const v = REGEN_VARIANTS[q.id];
        return v ? { ...q, text: v[Math.floor(Math.random() * v.length)] } : q;
      });
      setQuestions(fresh);
      setRegenAll(false);
    }, 1700);
  };
  const addManual = (type) => {
    setQuestions(qs => [...qs, blankQuestionOfType(type)]);
  };
  const addWithAI = (type) => {
    setAddingAI(true);
    setTimeout(() => {
      const pool = AI_QUESTION_POOL.filter(q => q.type === type);
      const tpl = (pool.length ? pool : AI_QUESTION_POOL)[Math.floor(Math.random() * (pool.length || AI_QUESTION_POOL.length))];
      const base = { id: 'q' + Date.now(), validated: false, type: tpl.type, text: tpl.text };
      if (tpl.options) base.options = tpl.options.map((o, i) => ({ id: 'o' + Date.now() + i, ...o }));
      if (tpl.rubric) base.rubric = tpl.rubric;
      setQuestions(qs => [...qs, base]);
      setAddingAI(false);
    }, 1300);
  };
  // Type-picker modal: { mode: 'manual' | 'ai' } or null
  const [typePicker, setTypePicker] = React.useState(null);
  const pickType = (type) => {
    const mode = typePicker && typePicker.mode;
    setTypePicker(null);
    if (mode === 'ai') addWithAI(type); else addManual(type);
  };

  // drag & drop reordering
  const onDragStart = (id) => setDragId(id);
  const onDragEnter = (overId) => setDragId(cur => {
    if (cur == null || cur === overId) return cur;
    setQuestions(qs => {
      const from = qs.findIndex(q => q.id === cur), to = qs.findIndex(q => q.id === overId);
      if (from < 0 || to < 0) return qs;
      const next = [...qs]; const [m] = next.splice(from, 1); next.splice(to, 0, m); return next;
    });
    return cur;
  });
  const onDragEnd = () => setDragId(null);

  // jump from summary to a card (no scrollIntoView)
  const jumpTo = (id) => {
    setFlashId(id);
    const el = document.getElementById('q-card-' + id);
    if (el) {
      let p = el.parentElement;
      while (p && p !== document.body) {
        const oy = getComputedStyle(p).overflowY;
        if ((oy === 'auto' || oy === 'scroll') && p.scrollHeight > p.clientHeight) break;
        p = p.parentElement;
      }
      if (p && p !== document.body) {
        const c = p.getBoundingClientRect(), e = el.getBoundingClientRect();
        p.scrollTop += (e.top - c.top) - 100;
      }
    }
    setTimeout(() => setFlashId(null), 1200);
  };

  const validatedCount = questions.filter(q => q.validated).length;
  const allValid = questions.length > 0 && validatedCount === questions.length;
  const pct = questions.length ? Math.round(validatedCount / questions.length * 100) : 0;

  return (
    <div className="space-y-5">
      {regenAll && (
        <div className="fixed inset-0 z-50 bg-white/95 backdrop-blur flex items-center justify-center anim-fade-in">
          <div className="text-center px-8">
            <div className="relative w-20 h-20 mx-auto mb-6">
              <span className="absolute inset-0 rounded-full border-4 border-primary-100" />
              <span className="absolute inset-0 rounded-full border-4 border-transparent border-t-primary" style={{ animation: 'spin 0.9s linear infinite' }} />
              <span className="absolute inset-0 flex items-center justify-center text-primary"><Icon name="sparkle" size={28} /></span>
            </div>
            <h2 className="text-[22px] font-bold text-ink">Regenerando todas las preguntas</h2>
            <p className="text-[15px] text-muted mt-2">La IA está redactando una nueva versión de la actividad…</p>
          </div>
        </div>
      )}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div className="flex items-center gap-2 flex-wrap">
          {config.difficulty && <Badge tone={(window.DIFFICULTY_TONE || {})[config.difficulty] || 'neutral'}><Icon name="gauge" size={13} />Dificultad {config.difficulty.toLowerCase()}</Badge>}
        </div>
        <Badge tone="primary" className="px-3 py-1.5 text-[12.5px] shrink-0"><Icon name="clipboard" size={14} />{questions.length} preguntas</Badge>
      </div>

      <p className="text-[14px] text-muted -mt-1">Revisa cada pregunta, edita el texto, valídala cuando esté lista y arrastra para reordenar.</p>

      {/* Resumen / índice de preguntas */}
      <Card className="p-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2.5 mb-3">
          <div className="flex items-center gap-2 min-w-0">
            <Icon name="list" size={17} className="text-muted" />
            <h3 className="text-[14px] font-bold text-ink">Resumen</h3>
            <span className="text-[13px] text-muted whitespace-nowrap">· {validatedCount} de {questions.length} validadas</span>
          </div>
          <div className="flex items-center flex-wrap gap-1.5 sm:shrink-0">
            <Button variant="outline" size="sm" icon="sparkle" onClick={regenerarTodo}>Regenerar todo</Button>
            <span className="w-px h-5 bg-line mx-0.5 hidden sm:block" />
            <Button variant="outline" size="sm" icon="check" onClick={() => validateAll(true)} disabled={allValid}>Validar todas</Button>
            <Button variant="ghost" size="sm" onClick={() => validateAll(false)} disabled={validatedCount === 0}>Quitar validación</Button>
          </div>
        </div>
        <div className="h-1.5 rounded-full bg-line overflow-hidden mb-3.5">
          <div className="h-full rounded-full transition-all duration-300" style={{ width: pct + '%', backgroundColor: '#34B27B' }} />
        </div>
        <div className="flex flex-wrap gap-2">
          {questions.map((q, i) => (
            <button key={q.id} onClick={() => jumpTo(q.id)}
              title={(q.text ? q.text.replace(/\{\{|\}\}/g, '') : QTYPE[q.type].label).slice(0, 90)}
              className={cx('inline-flex items-center gap-1.5 pl-2 pr-2.5 h-8 rounded-lg border text-[12.5px] font-semibold transition-colors',
                q.validated ? 'border-[#bfe6cf] bg-[#e7f7ee] text-[#1f8a52]' : 'border-line bg-white text-muted hover:border-primary-300 hover:text-primary-800')}>
              <span className="tabular-nums">{i + 1}</span>
              <Icon name={QTYPE[q.type].icon} size={13} />
              {q.validated && <Icon name="check" size={13} strokeWidth={3} />}
            </button>
          ))}
        </div>
      </Card>

      <div className="space-y-4">
        {questions.map((q, i) => (
          <QuestionCard key={q.id} q={q} index={i} total={questions.length}
            update={(patch) => update(q.id, patch)} onMove={(d) => move(q.id, d)}
            onDelete={() => del(q.id)} onRegen={() => regen(q.id)} regenerating={regenId === q.id}
            validated={!!q.validated} onToggleValid={() => toggleValid(q.id)}
            dnd={{ onDragStart, onDragEnter, onDragEnd, dragging: dragId === q.id }} flash={flashId === q.id} />
        ))}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <button onClick={() => setTypePicker({ mode: 'manual' })}
          className="flex items-center justify-center gap-2.5 py-5 rounded-2xl border-2 border-dashed border-line text-muted font-semibold hover:border-primary-300 hover:text-primary-800 hover:bg-primary-50/30 transition-all">
          <Icon name="plus" size={20} /> Añadir pregunta manualmente
        </button>
        <button onClick={() => setTypePicker({ mode: 'ai' })} disabled={addingAI}
          className="flex items-center justify-center gap-2.5 py-5 rounded-2xl border-2 border-dashed border-primary-200 bg-primary-50/40 text-primary-800 font-semibold hover:border-primary-400 hover:bg-primary-50 transition-all disabled:opacity-60">
          {addingAI
            ? <><Icon name="sparkle" size={20} className="animate-pulse" /> Generando con IA…</>
            : <><Icon name="sparkle" size={20} /> Generar pregunta con IA</>}
        </button>
      </div>

      {typePicker && (
        <QuestionTypeModal mode={typePicker.mode} onPick={pickType} onClose={() => setTypePicker(null)} />
      )}
    </div>
  );
}

window.QuestionsStep = QuestionsStep;
