import { useEffect, useRef } from 'react';
import { useFocusTrap } from '../../hooks/useFocusTrap';
import '../../styles/PreviewModal.css';

/**
 * Print-preview modal.
 *
 * Shows the server-rendered export image in a fullscreen overlay so the
 * user can verify the printable result before adding to cart. Distinct
 * from the in-editor canvas because:
 *
 *   • The editor canvas is design-coordinate (300×300) at viewport scale.
 *     The export is 4500×4500 @ 300 DPI.
 *   • Server-side rendering applies any text path / layer ordering /
 *     transparency that the editor's Konva pipeline simulates but doesn't
 *     necessarily render identically.
 *   • Some quirks (font fallback on the server, complex stroke handling)
 *     only manifest in the export pipeline.
 *
 * Showing the actual exported PNG closes the loop on "what will my
 * shirt look like".
 *
 * Loading state
 * ─────────────
 * The modal can be shown before the export URL is ready — when the user
 * triggers preview, we open the modal immediately with a spinner, then
 * swap in the image once `imageUrl` arrives. Closing while loading is
 * fine; the in-flight export still completes (and the URL ends up in
 * exportUrl state for later use).
 */
export function PreviewModal({ open, imageUrl, loading, error, onClose, onDownload }) {
  const panelRef = useRef(null);

  // Focus trap (S24) — keyboard users can't tab past the modal back
  // into the editor while it's open. Restores focus to the previously
  // focused element on close.
  useFocusTrap(open, panelRef);

  // Lock body scroll while open. Mirrors MobileBottomSheet's pattern so
  // the underlying editor doesn't pan when the user pinch-zooms the
  // preview image.
  useEffect(() => {
    if (!open) return;
    document.body.classList.add('has-preview-modal');
    return () => document.body.classList.remove('has-preview-modal');
  }, [open]);

  // ESC to dismiss.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div className="preview-modal" role="dialog" aria-modal="true" aria-label="Print preview">
      <button
        type="button"
        className="preview-modal__backdrop"
        aria-label="Close preview"
        onClick={onClose}
      />
      <div className="preview-modal__panel" ref={panelRef}>
        <div className="preview-modal__header">
          <h2 className="preview-modal__title">Print preview</h2>
          <button
            type="button"
            className="preview-modal__close"
            onClick={onClose}
            aria-label="Close"
          >✕</button>
        </div>

        <div className="preview-modal__body">
          {loading && (
            <div className="preview-modal__loading">
              <div className="spinner-small" aria-hidden="true" />
              <p>Rendering at print resolution…</p>
            </div>
          )}
          {!loading && error && (
            <div className="preview-modal__error">
              <p>⚠️ Couldn't render preview: {error}</p>
            </div>
          )}
          {!loading && !error && imageUrl && (
            <img
              src={imageUrl}
              alt="Your design at print resolution"
              className="preview-modal__image"
            />
          )}
        </div>

        <div className="preview-modal__footer">
          <p className="preview-modal__hint">
            This is what will print on your shirt — 4500×4500 at 300 DPI.
          </p>
          <div className="preview-modal__actions">
            <button
              type="button"
              className="preview-modal__btn preview-modal__btn--ghost"
              onClick={onClose}
            >
              Keep editing
            </button>
            <button
              type="button"
              className="preview-modal__btn preview-modal__btn--primary"
              onClick={onDownload}
              disabled={!imageUrl || loading}
            >
              Download PNG
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
