'use client';

import {ExternalLink, Maximize2, X} from 'lucide-react';
import {useTranslations} from 'next-intl';
import {useEffect, useState} from 'react';
import {createPortal} from 'react-dom';

type DemoFrameProps = {
  title: string;
  url: string;
  openLabel: string;
};

export function DemoFrame({title, url, openLabel}: DemoFrameProps) {
  const t = useTranslations('common');
  const [isFullscreen, setIsFullscreen] = useState(false);

  useEffect(() => {
    if (!isFullscreen) {
      return;
    }

    function onKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        setIsFullscreen(false);
      }
    }

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener('keydown', onKeyDown);
    };
  }, [isFullscreen]);

  const overlay =
    isFullscreen
      ? createPortal(
          <div
            className="demoFrameOverlay"
            role="dialog"
            aria-modal="true"
            aria-label={title}
            onClick={() => setIsFullscreen(false)}
          >
            <div className="demoFrameOverlay__panel demoFrame" onClick={event => event.stopPropagation()}>
              <div className="demoFrame__bar">
                <span>{title}</span>
                <div className="demoFrame__actions">
                  <a href={url} target="_blank" rel="noreferrer" aria-label={t('openInNewTab')}>
                    <ExternalLink size={18} />
                  </a>
                  <button type="button" aria-label={t('close')} onClick={() => setIsFullscreen(false)}>
                    <X size={18} />
                  </button>
                </div>
              </div>
              <div className="demoFrameOverlay__viewport">
                <iframe title={title} src={url} allowFullScreen />
              </div>
            </div>
          </div>,
          document.body
        )
      : null;

  return (
    <>
      <div className="demoFrame">
        <div className="demoFrame__bar">
          <span>{title}</span>
          <div className="demoFrame__actions">
            <a href={url} target="_blank" rel="noreferrer" aria-label={t('openInNewTab')}>
              <ExternalLink size={18} />
            </a>
            <button type="button" aria-label={t('fullscreen')} onClick={() => setIsFullscreen(true)}>
              <Maximize2 size={18} />
            </button>
          </div>
        </div>
        <div className="demoFrame__viewport">
          <iframe title={title} src={url} loading="lazy" allowFullScreen />
          <a className="demoFrame__fallback" href={url} target="_blank" rel="noreferrer">
            {openLabel}
          </a>
        </div>
      </div>
      {overlay}
    </>
  );
}
