// ───────────────────────── Vista previa de la actividad (reutilizable) ─────────────────────────
// Resumen reordenable de toda la actividad. Se integra en el último paso del
// asistente (junto a la entrega) y respeta la navegación del wizard.

function PreviewOption({ opt, multiple }) {
  return (
    <div className="flex items-center gap-2.5 py-1">
      <span className={cx('w-[18px] h-[18px] flex items-center justify-center shrink-0',
        multiple ? 'rounded-[5px] border-2' : 'rounded-full border-2',
        opt.correct ? 'border-[#34B27B] bg-[#34B27B] text-white' : 'border-[#cdcdd6]')}>
        {opt.correct && <Icon name="check" size={11} strokeWidth={3.4} />}
      </span>
      <span className={cx('text-[14px]', opt.correct ? 'text-ink font-semibold' : 'text-muted')}>{opt.text}</span>
      {opt.correct && <span className="text-[11px] font-bold text-[#1f8a52]">Correcta</span>}
    </div>
  );
}

function PreviewQuestion({ q, index, total, showSolutions, onMove, dnd }) {
  const [grab, setGrab] = React.useState(false);
  return (
    <div
      draggable={grab}
      onDragStart={() => dnd.onDragStart(q.id)}
      onDragEnter={() => dnd.onDragEnter(q.id)}
      onDragOver={(e) => e.preventDefault()}
      onDragEnd={() => { setGrab(false); dnd.onDragEnd(); }}
      className={cx('group/pq py-5 border-b border-line last:border-0 transition-opacity', dnd.dragging === q.id && 'opacity-40')}>
      <div className="flex items-start gap-3">
        <div className="flex flex-col items-center gap-1 shrink-0">
          <span className="w-7 h-7 rounded-lg bg-slate2 text-white text-[13px] font-bold flex items-center justify-center tabular-nums mt-0.5">{index + 1}</span>
          <div className="flex flex-col items-center gap-1 mt-1 opacity-40 group-hover/pq:opacity-100 transition-opacity">
            <button onClick={() => onMove(-1)} disabled={index === 0}
              className="w-7 h-6 rounded-md flex items-center justify-center text-muted border border-line bg-white hover:text-primary-800 hover:border-primary-300 hover:bg-primary-50 disabled:opacity-30 disabled:pointer-events-none transition-colors" title="Subir">
              <Icon name="chevron-up" size={17} strokeWidth={2.4} />
            </button>
            <button onMouseDown={() => setGrab(true)} onMouseUp={() => setGrab(false)} onMouseLeave={() => setGrab(false)}
              className="w-7 h-6 rounded-md flex items-center justify-center text-muted hover:text-primary-800 cursor-grab active:cursor-grabbing" title="Arrastra para reordenar" aria-label="Reordenar">
              <Icon name="drag" size={16} />
            </button>
            <button onClick={() => onMove(1)} disabled={index === total - 1}
              className="w-7 h-6 rounded-md flex items-center justify-center text-muted border border-line bg-white hover:text-primary-800 hover:border-primary-300 hover:bg-primary-50 disabled:opacity-30 disabled:pointer-events-none transition-colors" title="Bajar">
              <Icon name="chevron-down" size={17} strokeWidth={2.4} />
            </button>
          </div>
        </div>
        <div className="min-w-0 flex-1">
          {q.type === 'fill' ? (
            <p className="text-[15.5px] font-semibold text-ink leading-relaxed">
              {q.text.split(/(\{\{[^}]+\}\})/g).map((p, i) => {
                const m = p.match(/^\{\{([^}]+)\}\}$/);
                return m
                  ? (showSolutions
                      ? <span key={i} className="inline-flex items-center mx-0.5 px-2 py-0.5 rounded-md bg-[#e7f7ee] text-[#1f8a52] font-bold border border-[#bfe6cf]">{m[1]}</span>
                      : <span key={i} className="inline-block mx-0.5 px-6 border-b-2 border-dashed border-[#c2c2cc]" />)
                  : <span key={i}>{p}</span>;
              })}
            </p>
          ) : (
            <p className="text-[15.5px] font-semibold text-ink leading-snug">{q.text || <span className="text-faint italic">(Sin enunciado)</span>}</p>
          )}

          {(q.type === 'simple' || q.type === 'multiple') && (
            <div className="mt-3 space-y-0.5">
              {q.options.map(o => <PreviewOption key={o.id} opt={o} multiple={q.type === 'multiple'} />)}
            </div>
          )}

          {q.type === 'short' && (
            <div className="mt-3 h-9 rounded-lg border border-dashed border-line bg-canvas/50" />
          )}

          {q.type === 'essay' && (
            <>
              <div className="mt-3 h-20 rounded-lg border border-dashed border-line bg-canvas/50" />
              {showSolutions && q.rubric && (
                <div className="mt-2.5 flex items-start gap-2 px-3.5 py-2.5 rounded-lg bg-[#f1faf4] border border-[#d6ecdd]">
                  <Icon name="info" size={15} className="text-[#34B27B] shrink-0 mt-0.5" />
                  <p className="text-[12.5px] text-[#1f8a52]"><span className="font-semibold">Guía de corrección: </span>{q.rubric}</p>
                </div>
              )}
            </>
          )}

          {q.resource && (
            <div className="mt-3 inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary-50 text-primary-800 text-[12px] font-medium">
              <Icon name="image" size={14} /> esquema-celula.png
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Reorderable question list (the document header lives in DeliveryStep).
function ActivityPreview({ questions, setQuestions }) {
  const total = questions.length;
  const [dragId, setDragId] = React.useState(null);

  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 dnd = {
    dragging: dragId,
    onDragStart: (id) => setDragId(id),
    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 n = [...qs]; const [m] = n.splice(from, 1); n.splice(to, 0, m); return n;
      });
      return cur;
    }),
    onDragEnd: () => setDragId(null),
  };

  return (
    <div>
      {/* Reorder hint */}
      <div className="flex items-center gap-2 mb-1 px-1 text-[12.5px] text-muted">
        <Icon name="drag" size={15} className="text-primary-600" />
        Arrastra una pregunta o usa las flechas para cambiar el orden. Las respuestas correctas se muestran resaltadas.
      </div>

      {/* Questions */}
      <Card className="px-6 py-2 mt-2">
        {questions.map((q, i) => (
          <PreviewQuestion key={q.id} q={q} index={i} total={total} showSolutions={true}
            onMove={(d) => move(q.id, d)} dnd={dnd} />
        ))}
      </Card>
    </div>
  );
}

window.ActivityPreview = ActivityPreview;
