/* DocumentModal.jsx — Detalle del documento al hacer clic.
 * - Abierto: muestra todo (resumen completo, metadatos, video, ver/descargar).
 * - Registro (bloqueado): resumen recortado, contenido y video con candado,
 *   boton para registrarse. Exposed as window.DocumentModal.
 */
function DocumentModal({ open, doc, unlocked, onClose, onRegister, onOpenFile }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  React.useEffect(() => {
    if (open && window.lucide) {
      setTimeout(() => window.lucide.createIcons(), 30);
    }
  }, [open, doc, unlocked]);

  if (!open || !doc) return null;

  const locked = doc.accessLevel === "registro" && !unlocked;
  const fileMeta = ResourceStore.getFileTypeMeta(doc.fileType);
  const videoMeta = doc.videoUrl ? ResourceStore.getVideoMeta(doc.videoUrl) : null;

  const fmtDate = (s) => {
    if (!s) return "—";
    try {
      return new Date(s + "T00:00:00").toLocaleDateString("es-HN", { day: "2-digit", month: "long", year: "numeric" });
    } catch { return s; }
  };

  // Resumen: completo si abierto/desbloqueado; recortado si bloqueado.
  const fullSummary = doc.summary || "Sin resumen disponible para este documento.";
  const shownSummary = locked && fullSummary.length > 180
    ? fullSummary.slice(0, 180).trim() + "…"
    : fullSummary;

  const renderVideo = () => {
    if (!videoMeta) return null;
    if (videoMeta.kind === "file") {
      return (
        <video className="doc-modal-video" controls src={videoMeta.embed}></video>
      );
    }
    if (videoMeta.kind === "youtube" || videoMeta.kind === "vimeo") {
      return (
        <div className="doc-modal-video-wrap">
          <iframe
            src={videoMeta.embed}
            title="Video del recurso"
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
          ></iframe>
        </div>
      );
    }
    return (
      <a className="doc-modal-videolink" href={videoMeta.embed} target="_blank" rel="noopener">
        <i data-lucide="external-link"></i> Ver video
      </a>
    );
  };

  return (
    <div className="doc-modal-overlay" onClick={onClose}>
      <div className="doc-modal" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="doc-modal-title">
        <button className="doc-modal-close" onClick={onClose} aria-label="Cerrar">
          <i data-lucide="x"></i>
        </button>

        <div className="doc-modal-head">
          <div className="doc-modal-filetype">
            <i data-lucide={fileMeta.icon}></i>
            <span>{fileMeta.label}</span>
          </div>
          <span className={"doc-modal-cat " + doc.type}>{doc.category}</span>
          {doc.accessLevel === "registro" && (
            <span className="doc-modal-access">
              <i data-lucide="lock"></i> Requiere registro
            </span>
          )}
        </div>

        <h2 id="doc-modal-title" className="doc-modal-title">{doc.name}</h2>

        <div className="doc-modal-meta">
          {doc.author && <span><i data-lucide="user"></i> {doc.author}</span>}
          {doc.version && <span><i data-lucide="git-branch"></i> Version {doc.version}</span>}
          <span><i data-lucide="calendar"></i> Publicado: {fmtDate(doc.publishedAt)}</span>
          {doc.updatedAt && <span><i data-lucide="refresh-cw"></i> Actualizado: {fmtDate(doc.updatedAt)}</span>}
        </div>

        <div className="doc-modal-section">
          <h3 className="doc-modal-subtitle">Resumen</h3>
          <p className="doc-modal-summary">{shownSummary}</p>
        </div>

        {doc.videoUrl && (
          <div className="doc-modal-section">
            <h3 className="doc-modal-subtitle">Video</h3>
            {locked ? (
              <div className="doc-modal-locked">
                <i data-lucide="lock"></i>
                <p>Registrese para ver el video completo</p>
              </div>
            ) : renderVideo()}
          </div>
        )}

        {doc.tags && doc.tags.length > 0 && (
          <div className="doc-modal-tags">
            {doc.tags.map(t => <span key={t}>#{t}</span>)}
          </div>
        )}

        <div className="doc-modal-actions">
          {locked ? (
            <button className="doc-modal-btn locked" onClick={() => onRegister(doc)}>
              <i data-lucide="lock"></i>
              Registrarse para acceder
            </button>
          ) : doc.fileType === "video" ? (
            doc.videoUrl ? (
              <a className="doc-modal-btn" href={doc.videoUrl} target="_blank" rel="noopener">
                <i data-lucide="external-link"></i>
                Abrir video en nueva pestaña
              </a>
            ) : null
          ) : (
            <button className="doc-modal-btn" onClick={() => onOpenFile(doc)}>
              <i data-lucide={doc.fileUrl ? "download" : "eye"}></i>
              {doc.fileUrl ? "Descargar documento" : "Ver documento"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DocumentModal });
