"use client";
import { useEffect, useRef, useState } from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { fixIframe, isHtmlArtifact, registerIframeRef, wrapArtifactContent } from './artifact-utils';

const FS_ANIM_MS = 260;

export default function ArtifactFullscreen({
  artifact,
  docked,
  onClose,
  confirmDeleteId,
  setConfirmDeleteId,
  deleteArtifactById,
  toggleMinimize,
  downloadArtifact,
  registerArtifactFrame,
}) {
  // Lifecycle: 'enter' (just mounted, hidden) -> 'open' (animated in) -> 'exit' (animating out)
  const [phase, setPhase] = useState('enter');
  const closingRef = useRef(false);

  // Kick off the enter animation on next frame so the browser actually transitions
  // from the 'enter' styles to the 'open' styles instead of mounting in the final state.
  useEffect(() => {
    const rafs = { first: 0, second: 0 };
    rafs.first = requestAnimationFrame(() => {
      rafs.second = requestAnimationFrame(() => setPhase('open'));
    });
    return () => {
      if (rafs.first) cancelAnimationFrame(rafs.first);
      if (rafs.second) cancelAnimationFrame(rafs.second);
    };
  }, []);

  function requestClose(after) {
    if (closingRef.current) return;
    closingRef.current = true;
    setPhase('exit');
    setTimeout(() => {
      if (typeof after === 'function') after();
      onClose();
    }, FS_ANIM_MS);
  }

  useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') requestClose(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const a = artifact;
  return (
    <div
      className={'artifact-fs' + (docked ? ' artifact-fs--docked' : '')}
      data-phase={phase}
    >
      <div
        className="winbar artifact-fs-bar"
        onDoubleClick={e => {
          if (e.target.closest('button, i, .confirm-label')) return;
          requestClose();
        }}
        title="Double-click to exit fullscreen"
      >
        {confirmDeleteId === a.id ? (
          <>
            <span className="confirm-label">Delete permanently?</span>
            <button className="confirm-cancel" onClick={() => setConfirmDeleteId(null)}>Cancel</button>
            <button className="confirm-delete" onClick={() => requestClose(() => deleteArtifactById(a.id))}>Delete</button>
          </>
        ) : (
          <>
            <i className="dot-close"    onClick={() => setConfirmDeleteId(a.id)} title="Delete" />
            <i className="dot-minimize" onClick={() => requestClose(() => toggleMinimize(a.id))} title="Minimize" />
            <i className="dot-zoom"     onClick={() => requestClose()} title="Exit fullscreen" />
            <b>{a.title || 'Artifact'}</b>
            <span className={'artifact-kind-badge ' + (a.kind || 'text')}>{a.kind}</span>
            <button className="winbar-dl" onClick={() => downloadArtifact(a)} title={isHtmlArtifact(a.kind) ? 'Download .html' : 'Download .md'}>
              <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M8 2v9M4 7l4 4 4-4"/><line x1="2" y1="14" x2="14" y2="14"/>
              </svg>
            </button>
          </>
        )}
      </div>
      <div className="artifact-fs-content">
        {isHtmlArtifact(a.kind) ? (
          <iframe ref={registerIframeRef(registerArtifactFrame)} srcDoc={wrapArtifactContent(a.content)} sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox" title={a.title} onLoad={fixIframe} />
        ) : (
          <div className="win-md"><Markdown remarkPlugins={[remarkGfm]}>{a.content || ''}</Markdown></div>
        )}
      </div>
    </div>
  );
}
