/* @jsx React.createElement */
const { useEffect: useEffectModal } = React;

// In-page lightbox. Renders one or more images stacked vertically.
// PDFs come as an array of preview JPGs (one per page) so users can
// scroll through every page. The original-file link goes into the
// bar so users who want to print or download the real PDF still can.
// Closes on backdrop click, Esc, X button.
function Modal({ open, onClose, srcs, externalSrc, title }) {
  useEffectModal(() => {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    if (window.lucide) setTimeout(() => window.lucide.createIcons(), 30);
    return () => {
      document.body.style.overflow = prevOverflow;
      document.removeEventListener("keydown", onKey);
    };
  }, [open, onClose]);

  if (!open) return null;

  // Render at document.body so we escape any ancestor stacking
  // context (sections with transform/filter create stacking
  // contexts that would trap the modal below the sticky page
  // header even with a high z-index).
  return ReactDOM.createPortal(
    <React.Fragment>
      <div className="os-modal-backdrop" onClick={onClose} />
      <div className="os-modal-shell" role="dialog" aria-modal="true" aria-label={title || "Vorschau"}>
        <div className="os-modal-bar">
          <div className="os-modal-title">{title}</div>
          <div style={{ display: "flex", gap: 8 }}>
            {externalSrc && (
              <a href={externalSrc} target="_blank" rel="noopener" className="os-modal-btn" aria-label="In neuem Tab oeffnen" title="In neuem Tab öffnen">
                <i data-lucide="external-link" style={{ width: 14, height: 14 }}></i>
              </a>
            )}
            <button type="button" onClick={onClose} className="os-modal-btn" aria-label="Schliessen" title="Schliessen">
              <i data-lucide="x" style={{ width: 14, height: 14 }}></i>
            </button>
          </div>
        </div>
        <div className="os-modal-body">
          {(srcs || []).map((s, i) => (
            <img
              key={i}
              src={s}
              alt={title ? title + ((srcs.length > 1) ? ` — Seite ${i + 1}` : "") : ""}
              className="os-modal-page"
            />
          ))}
        </div>
      </div>
    </React.Fragment>,
    document.body
  );
}

window.Modal = Modal;
