"use client";
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { containArtifactWheel, fixIframe, isHtmlArtifact, registerIframeRef, wrapArtifactContent } from './artifact-utils';
import { useDashboard } from './dashboard-context';
import InactiveIframeShield from './inactive-iframe-shield';

export default function ArtifactBoard({ confirmDeleteId, setConfirmDeleteId, deleteArtifactById, setMoveMenu }) {
  const {
    artifacts,
    visibleArtifacts,
    frontArtifactId,
    zForArtifact,
    artifactLayout,
    registerArtifactFrame,
  } = useDashboard();

  const setBoardEl = artifactLayout.setBoardEl;
  const getLayout = artifactLayout.getLayout;
  const draggingId = artifactLayout.draggingId;
  const resizingId = artifactLayout.resizingId;
  const selectedArtifactId = artifactLayout.selectedArtifactId;
  const toggleMinimize = artifactLayout.toggleMinimize;
  const setFullscreenId = artifactLayout.setFullscreenId;
  const downloadArtifact = artifactLayout.downloadArtifact;
  const startDrag = artifactLayout.startDrag;
  const startResize = artifactLayout.startResize;
  const bringToFront = artifactLayout.bringToFront;

  return (
    <div ref={setBoardEl} className="canvas-board canvas-board--docked">
      {visibleArtifacts.map(a => {
        const stableIdx = artifacts.findIndex(x => x.id === a.id);
        const L = getLayout(a.id, stableIdx);
        const z = zForArtifact(a);
        const isIframeArtifact = isHtmlArtifact(a.kind);
        const isFrontArtifact = a.id === frontArtifactId;
        return (
          <div
            key={a.id}
            className={'artifact-window-wrap' + (draggingId === a.id ? ' is-dragging' : '')}
            data-dragging={draggingId === a.id ? 'true' : 'false'}
            data-resizing={resizingId === a.id ? 'true' : 'false'}
            style={{ transform: `translate3d(${L.x}px, ${L.y}px, 0)`, width: L.width, height: L.height, zIndex: z }}
            onPointerDown={() => bringToFront(a.id)}
          >
            <div className={'window artifact-window' + (a.id === selectedArtifactId ? ' artifact-window--new' : '')}>
              <div
                className="winbar"
                onPointerDown={e => startDrag(e, a.id)}
                onDoubleClick={e => {
                  if (e.target.closest('button, i, .confirm-label')) return;
                  setFullscreenId(a.id);
                }}
                onContextMenu={e => {
                  if (e.target.closest('button, i, .confirm-label')) return;
                  e.preventDefault();
                  setMoveMenu({ artifactId: a.id, x: e.clientX, y: e.clientY });
                }}
                title="Drag onto a space chip to move · Right-click for more · Double-click to expand"
              >
                {confirmDeleteId === a.id ? (
                  <>
                    <span className="confirm-label">Delete permanently?</span>
                    <button className="confirm-cancel" onClick={() => setConfirmDeleteId(null)}>Cancel</button>
                    <button className="confirm-delete" onClick={() => deleteArtifactById(a.id)}>Delete</button>
                  </>
                ) : (
                  <>
                    <i className="dot-close"    onClick={() => setConfirmDeleteId(a.id)} title="Delete" />
                    <i className="dot-minimize" onClick={() => toggleMinimize(a.id)}     title="Minimize" />
                    <i className="dot-zoom"     onClick={() => setFullscreenId(a.id)}    title="Expand" />
                    <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="win-content" onWheelCapture={containArtifactWheel}>
                {draggingId === a.id && <div className="drag-blocker" />}
                {resizingId === a.id && <div className="resize-blocker" />}
                {isIframeArtifact ? (
                  <>
                    {!isFrontArtifact && (
                      <InactiveIframeShield onActivate={() => bringToFront(a.id)} />
                    )}
                    <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>
            {['nw','n','ne','e','se','s','sw','w'].map(d => (
              <div
                key={d}
                className={'resize-edge resize-' + d}
                onPointerDown={e => startResize(e, a.id, d)}
              />
            ))}
          </div>
        );
      })}
    </div>
  );
}
