// PreviewModal.jsx v3
// Ændringer fra v2:
// - Iframe-aspect ratio er nu 1:1 (540x540 i stedet for 540x720)
// - Fejlmeddelelser inkluderer hvilket format der blev requestet

const PreviewModal = ({ previewUrl, adName, source, format, warning, error, onClose }) => {
  const [iframeLoaded, setIframeLoaded] = React.useState(false);

  React.useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKeyDown);

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = originalOverflow;
    };
  }, [onClose]);

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) onClose();
  };

  const renderBody = () => {
    if (error || !previewUrl) {
      return (
        <div className="preview-modal__error">
          <svg viewBox="0 0 64 64" width="48" height="48" aria-hidden="true">
            <circle cx="32" cy="32" r="30" fill="none" stroke="#e53e3e" strokeWidth="2"/>
            <path d="M32 16 L32 36" stroke="#e53e3e" strokeWidth="3" strokeLinecap="round"/>
            <circle cx="32" cy="46" r="2.5" fill="#e53e3e"/>
          </svg>
          <div className="preview-modal__error-title">
            {error && error.includes('format tilgængeligt')
              ? 'Intet 1:1 format tilgængeligt'
              : 'Preview kunne ikke hentes'}
          </div>
          <div className="preview-modal__error-detail">
            {error || 'Graph API returnerede ingen preview URL'}
          </div>
        </div>
      );
    }

    return (
      <>
        {!iframeLoaded && (
          <div className="preview-modal__loading">
            <div className="spinner" />
            <div className="preview-modal__loading-text">Henter preview fra Facebook...</div>
          </div>
        )}
        <iframe
          src={previewUrl}
          className="preview-modal__iframe"
          onLoad={() => setIframeLoaded(true)}
          title="Facebook preview"
          sandbox="allow-scripts allow-same-origin allow-popups"
        />
      </>
    );
  };

  const sourceLabel = (() => {
    if (error) return null;
    if (source === 'cache') return 'Cached';
    if (source === 'graph_api') return 'Live';
    if (source === 'sheet_fallback') return 'Sheet (kan være udløbet)';
    return null;
  })();

  return (
    <div className="preview-modal__backdrop" onClick={handleBackdropClick}>
      <div className="preview-modal__container preview-modal__container--square" role="dialog" aria-label="Annonce preview">
        <div className="preview-modal__header">
          <div className="preview-modal__title-area">
            <div className="preview-modal__title" title={adName}>
              {adName || 'Annonce preview'}
            </div>
            {sourceLabel && (
              <span className={`preview-modal__source preview-modal__source--${source}`}>
                {sourceLabel}
              </span>
            )}
          </div>
          <button
            type="button"
            className="preview-modal__close"
            onClick={onClose}
            aria-label="Luk preview"
          >
            <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
              <path
                d="M6 6 L18 18 M18 6 L6 18"
                stroke="currentColor"
                strokeWidth="2.5"
                strokeLinecap="round"
              />
            </svg>
          </button>
        </div>

        {warning && !error && (
          <div className="preview-modal__warning">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path d="M12 2 L22 20 L2 20 Z" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"/>
              <path d="M12 9 L12 14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
              <circle cx="12" cy="17" r="1" fill="currentColor"/>
            </svg>
            <span>{warning}</span>
          </div>
        )}

        <div className="preview-modal__body">
          {renderBody()}
        </div>
      </div>
    </div>
  );
};
