// ───────────────────────── Bloque de exportación (final del Paso 5) ─────────────────────────
// Las tarjetas son SELECCIONABLES. La acción se ejecuta desde el botón del
// footer del asistente, que muestra una modal de éxito (SuccessModal).
const EXPORT_OPTS = [
  { fmt: 'PDF',     ic: 'file-pdf', t: 'Exportar a PDF', d: 'Documento listo para imprimir' },
  { fmt: 'ODT',     ic: 'file-doc', t: 'Exportar a ODT', d: 'Editable en tu procesador de textos' },
  { fmt: 'EDEBEON', ic: 'layers',   t: 'Integrar en EdebéOn+', d: 'Crea una tarjeta de evaluación en tu libro' },
];
const EXPORT_LABEL = { PDF: 'Exportar a PDF', ODT: 'Exportar a ODT', EDEBEON: 'Integrar en EdebéOn+' };
const EXPORT_ICON  = { PDF: 'download', ODT: 'download', EDEBEON: 'layers' };

function ExportBlock({ title, selected, onSelect, copies, copy, setCopy }) {
  const hasCopies = copies.length > 0;
  const copyRef = React.useRef(null);

  // Al elegir "Integrar en EdebéOn+", el panel de copias aparece debajo y
  // quedaba tapado por el footer fijo: desplazamos el contenedor para verlo.
  React.useEffect(() => {
    if (selected !== 'EDEBEON' || !hasCopies) return;
    const t = setTimeout(() => {
      const el = copyRef.current;
      if (!el) return;
      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;
      }
      const footer = 96; // alto del footer fijo + margen
      if (p && p !== document.body) {
        const c = p.getBoundingClientRect(), e = el.getBoundingClientRect();
        const overflowBelow = e.bottom - (c.bottom - footer);
        if (overflowBelow > 0) p.scrollTop += overflowBelow + 12;
      } else {
        const e = el.getBoundingClientRect();
        const overflowBelow = e.bottom - (window.innerHeight - footer);
        if (overflowBelow > 0) window.scrollBy({ top: overflowBelow + 12, behavior: 'smooth' });
      }
    }, 80);
    return () => clearTimeout(t);
  }, [selected, hasCopies]);

  return (
    <div>
      <div className="flex items-center gap-2.5 mb-1">
        <Icon name="download" size={19} className="text-primary-800" />
        <h3 className="text-[16px] font-bold text-ink">Exportar e integrar</h3>
      </div>
      <p className="text-[14px] text-muted mb-5">
        Elige cómo quieres usar <span className="font-semibold text-ink">«{title}»</span> y confirma con el botón inferior.
      </p>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {EXPORT_OPTS.map(a => {
          const on = selected === a.fmt;
          const isEde = a.fmt === 'EDEBEON';
          const disabled = isEde && !hasCopies;
          return (
            <button key={a.fmt} disabled={disabled}
              onClick={() => { if (disabled) return; onSelect(on ? null : a.fmt); }}
              className={cx('relative rounded-2xl border-2 p-5 text-left transition-all',
                disabled && 'opacity-60 cursor-not-allowed',
                on ? 'border-primary bg-primary-50/50 shadow-cardhover' : 'border-line bg-white hover:border-primary-200')}>
              {on && <span className="absolute top-4 right-4 w-6 h-6 rounded-full bg-primary flex items-center justify-center"><Icon name="check" size={14} strokeWidth={3} className="text-white" /></span>}
              {disabled && <span className="absolute top-4 right-4"><Badge tone="neutral">No disponible</Badge></span>}
              <div className={cx('w-12 h-12 rounded-xl flex items-center justify-center mb-4 transition-colors', on ? 'bg-primary text-white' : 'bg-canvas text-ink')}>
                <Icon name={a.ic} size={24} />
              </div>
              <h4 className="text-[15.5px] font-bold text-ink">{a.t}</h4>
              <p className="text-[13px] text-muted mt-1">{isEde && !hasCopies ? 'Necesitas una copia del libro para integrar.' : a.d}</p>
            </button>
          );
        })}
      </div>

      {/* Selector de copia — solo al integrar en EdebéOn+ */}
      {selected === 'EDEBEON' && hasCopies && (
        <div ref={copyRef} className="mt-4 p-5 rounded-2xl border border-primary-200 bg-primary-50/40 anim-fade-up scroll-mb-28">
          <div className="flex items-center gap-2 mb-1">
            <Icon name="layers" size={17} className="text-primary-800" />
            <h4 className="text-[14px] font-bold text-ink">¿En qué copia quieres integrarla?</h4>
          </div>
          <p className="text-[13px] text-muted mb-3">La actividad se añade a una copia tuya del libro, nunca a la edición original.</p>
          <div className="space-y-2">
            {copies.map(c => {
              const oc = copy === c.id;
              return (
                <button key={c.id} onClick={() => setCopy(c.id)}
                  className={cx('w-full flex items-center gap-3 px-4 py-3 rounded-xl border text-left transition-all',
                    oc ? 'border-primary bg-white shadow-card' : 'border-line bg-white hover:border-primary-200')}>
                  <Radio checked={oc} onChange={() => setCopy(c.id)} />
                  <div className="w-9 h-9 rounded-lg bg-primary-50 text-primary-800 flex items-center justify-center shrink-0"><Icon name="book" size={18} /></div>
                  <div className="min-w-0 flex-1">
                    <p className="text-[14px] font-semibold text-ink truncate">{c.name}</p>
                    <p className="text-[12px] text-muted">{c.updated}</p>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// Modal de éxito tras confirmar la exportación / integración.
function SuccessModal({ format, solutions, group, copyName, onClose, onNew }) {
  const isIntegrate = format === 'EDEBEON';
  const fmtName = format === 'PDF' ? 'PDF' : 'documento ODT';
  const title = isIntegrate ? '¡Actividad integrada!' : '¡Prueba generada!';
  const sub = isIntegrate
    ? `Disponible en «${copyName}». El alumnado podrá realizarla desde el flipbook de tu copia.`
    : `Tu ${fmtName} se ha generado ${solutions ? 'con' : 'sin'} solucionario y se ha descargado en tu equipo.`;
  const actionLabel = isIntegrate ? 'Ver en EdebéOn+' : 'Hecho';
  const actionIcon = isIntegrate ? 'arrow-right' : null;

  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-50 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(420px,94vw)] p-8 text-center anim-fade-up">
        <div className="w-16 h-16 rounded-full bg-[#e7f7ee] flex items-center justify-center mx-auto mb-5">
          <Icon name="check-circle" size={34} strokeWidth={2} className="text-[#34B27B]" />
        </div>
        <h3 className="text-[21px] font-extrabold text-ink tracking-tight">{title}</h3>
        <p className="text-[14.5px] text-muted mt-2 leading-snug">{sub}</p>
        <div className="flex items-center justify-center gap-3 mt-7">
          <Button variant="outline" onClick={onNew}>Generar otra</Button>
          <Button variant="primary" icon={actionIcon || undefined} onClick={onClose}>{actionLabel}</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ExportBlock, SuccessModal, EXPORT_LABEL, EXPORT_ICON });
