"use client";
import { memo, useState } from 'react';
import { useDashboard } from './dashboard-context';
import ArtifactDock from './artifact-dock';
import ArtifactBoard from './artifact-board';
import ArtifactFullscreen from './artifact-fullscreen';
import RuntimePopover from './runtime-popover';
import WinbarMoveMenu from './winbar-move-menu';

function CanvasSection() {
  const {
    initializing,
    activeHermesJobs,
    runtimeActions,
    mainAgent,
    approvalRun,
    artifacts,
    visibleArtifacts,
    dockedArtifacts,
    artifactLayout,
    spaces: spacesHook,
    registerArtifactFrame,
    designStyle,
  } = useDashboard();
  const approveClaudeRun = runtimeActions.approveClaudeRun;
  const approvalBusyId = runtimeActions.approvalBusyId;
  const resetArtifactLayout = artifactLayout.resetArtifactLayout;
  const layoutMode = artifactLayout.layoutMode;
  const fullscreenId = artifactLayout.fullscreenId;
  const setFullscreenId = artifactLayout.setFullscreenId;
  const confirmDeleteId = artifactLayout.confirmDeleteId;
  const setConfirmDeleteId = artifactLayout.setConfirmDeleteId;
  const deleteArtifactById = artifactLayout.deleteArtifactById;
  const toggleMinimize = artifactLayout.toggleMinimize;
  const downloadArtifact = artifactLayout.downloadArtifact;
  const minimizedIds = artifactLayout.minimizedIds;
  const hoveredDockId = artifactLayout.hoveredDockId;
  const setHoveredDockId = artifactLayout.setHoveredDockId;
  const pointerDropSpaceId = artifactLayout.pointerDropSpaceId;
  const busy = mainAgent.busy;
  const liveTool = mainAgent.liveTool;
  const liveText = mainAgent.liveText;
  const command = mainAgent.command;
  const spaces = spacesHook.spaces;
  const activeSpaceId = spacesHook.activeSpaceId;
  const setActiveSpaceId = spacesHook.setActiveSpaceId;
  const createSpace = spacesHook.createSpace;
  const renameSpace = spacesHook.renameSpace;
  const deleteSpace = spacesHook.deleteSpace;
  const moveArtifactToSpace = spacesHook.moveArtifactToSpace;
  const isSpaceSwitching = spacesHook.isSwitching;

  const [moveMenu, setMoveMenu] = useState(null); // { artifactId, x, y } | null

  return (
<section className={'canvas fresh-canvas' + (isSpaceSwitching ? ' is-space-switching' : '')}>
  <div className="toolbar fresh-toolbar">
    <span className="tb-wordmark" aria-label="madarX OS">madar<b>X</b><i>OS</i></span>
    {approvalRun && (
      <button
        onClick={() => approveClaudeRun(approvalRun.id)}
        disabled={approvalBusyId === approvalRun.id}
        style={{border:0,borderRadius:999,padding:'7px 10px',background:'#111318',color:'#fff',fontSize:12,fontWeight:700,cursor:approvalBusyId ? 'wait' : 'pointer'}}
      >
        {approvalBusyId === approvalRun.id ? 'Running Claude...' : 'Approve & Run'}
      </button>
    )}
    <div className="hermes-wrap">
      <span
        className={'tb-icon-btn' + (activeHermesJobs.length > 0 ? ' on' : '')}
        role="status"
        aria-label={activeHermesJobs.length > 0 ? `Hermes ${activeHermesJobs.length} running` : 'Hermes idle'}
      >
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/>
        </svg>
        {activeHermesJobs.length > 0 && <span>{activeHermesJobs.length}</span>}
      </span>
      <div className="hermes-tooltip" role="tooltip">
        <b>Hermes</b>
        <small>{activeHermesJobs.length > 0 ? `${activeHermesJobs.length} running` : 'idle'}</small>
        {activeHermesJobs.length > 0 && (
          <ul>
            {activeHermesJobs.map(j => (
              <li key={j.id}>{j.title || (j.prompt ? j.prompt.slice(0, 60) : 'Untitled job')}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
    <RuntimePopover />
    {artifacts.length > 0 && (
      <button
        className="tb-icon-btn"
        style={{ marginLeft: 'auto' }}
        onClick={resetArtifactLayout}
        title={layoutMode === 'manual' ? 'Reset to auto layout' : 'Auto layout active'}
        aria-label={layoutMode === 'manual' ? 'Reset to auto layout' : 'Auto layout active'}
      >
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="7" height="7"/>
          <rect x="14" y="3" width="7" height="7"/>
          <rect x="14" y="14" width="7" height="7"/>
          <rect x="3" y="14" width="7" height="7"/>
        </svg>
      </button>
    )}
  </div>

  {(() => {
    const visible = visibleArtifacts;
    const docked  = dockedArtifacts;

    if (initializing) {
      return (
        <div className="canvas-board canvas-board--skel" aria-hidden="true">
          <div className="artifact-window-wrap artifact-skel-wrap artifact-skel-wrap--solo">
            <div className="window artifact-window">
              <div className="winbar">
                <i className="dot-close" />
                <i className="dot-minimize" />
                <i className="dot-zoom" />
                <div className="skel sk-winbar-title" />
                <div className="skel sk-kind-badge" />
              </div>
              <div className="win-content artifact-skel-content">
                <div className="skel sk-art-hero" />
                <div className="skel sk-line sk-line--w90" />
                <div className="skel sk-line sk-line--w80" />
                <div className="skel sk-line sk-line--w65" />
                <div className="skel sk-art-block" />
                <div className="skel sk-line sk-line--w75" />
                <div className="skel sk-line sk-line--w55" />
              </div>
            </div>
          </div>
        </div>
      );
    }

    if (busy && visible.length === 0 && docked.length === 0) {
      return (
        <div className="building-card-wrap">
          <div className="building-card">
            <div className="building-winbar">
              <div className="building-dots"><span /><span /><span /></div>
              <span className="building-winbar-title">
                {liveTool === 'generate_ui' ? `Designing ${designStyle} UI…`
                  : liveTool === 'create_artifact' ? 'Building artifact…'
                  : liveTool ? `Running ${liveTool.replace(/_/g, ' ')}…`
                  : 'Agent composing…'}
              </span>
              <div className="building-pill">
                <div className="building-pill-dot" />
                Live
              </div>
            </div>
            <div className="building-body">
              <div className="building-illustration">
                <div className="building-mesh" />
                <div className="building-skeleton">
                  <div className="skel hd" />
                  <div className="skel la" />
                  <div className="skel lb" />
                  <div className="skel lc" />
                  <div className="skel ld" />
                </div>
              </div>
              <div className="building-footer">
                <div className="building-footer-label">{liveTool ? 'Active tool' : 'Status'}</div>
                <div className="building-footer-tool">
                  {liveTool === 'generate_ui' ? `${designStyle} design rules active`
                    : liveTool ? liveTool.replace(/_/g, ' ')
                    : 'Agent is thinking…'}
                </div>
                {liveText && (
                  <div className="building-stream-text">{liveText.slice(-320)}</div>
                )}
              </div>
            </div>
          </div>
        </div>
      );
    }

    return <>
      {visible.length > 0 ? (
        <ArtifactBoard
          confirmDeleteId={confirmDeleteId}
          setConfirmDeleteId={setConfirmDeleteId}
          deleteArtifactById={deleteArtifactById}
          setMoveMenu={setMoveMenu}
        />
      ) : docked.length === 0 && artifacts.length === 0 ? (
        <div className="fresh-workspace">
          <div className="fresh-hero full-width">
            <small>Clean workspace</small>
            <h1>Start from zero.</h1>
            <p>Your local-first agent workspace. Create agents that research competitors, generate reports, run scheduled tasks, and prepare actions for your approval — all running on your machine, backed by SQLite, with no cloud dependencies.</p>
            <div className="fresh-actions">
              <button onClick={() => command('Create the first Client Workspace competitor research agent with browser scraper and report writer daily at 07:30')}>Create first agent</button>
              <button className="secondary" onClick={() => command('Look for all Client Workspace competitors and provide the daily report')}>Test report flow</button>
            </div>
          </div>
        </div>
      ) : null}

      <ArtifactDock
        spaces={spaces}
        activeSpaceId={activeSpaceId}
        setActiveSpaceId={setActiveSpaceId}
        createSpace={createSpace}
        renameSpace={renameSpace}
        deleteSpace={deleteSpace}
        moveArtifactToSpace={moveArtifactToSpace}
        artifacts={artifacts}
        dockedArtifacts={docked}
        minimizedIds={minimizedIds}
        hoveredDockId={hoveredDockId}
        setHoveredDockId={setHoveredDockId}
        toggleMinimize={toggleMinimize}
        pointerDropSpaceId={pointerDropSpaceId}
      />
    </>;
  })()}

  {/* Fullscreen overlay — animates in on expand, out on close. */}
  {fullscreenId && (() => {
    const a = artifacts.find(x => x.id === fullscreenId);
    if (!a) return null;
    return (
      <ArtifactFullscreen
        key={a.id}
        artifact={a}
        docked={true}
        onClose={() => setFullscreenId(null)}
        confirmDeleteId={confirmDeleteId}
        setConfirmDeleteId={setConfirmDeleteId}
        deleteArtifactById={deleteArtifactById}
        toggleMinimize={toggleMinimize}
        downloadArtifact={downloadArtifact}
        registerArtifactFrame={registerArtifactFrame}
      />
    );
  })()}

  {moveMenu && (
    <WinbarMoveMenu
      x={moveMenu.x}
      y={moveMenu.y}
      spaces={spaces}
      activeSpaceId={activeSpaceId}
      onMove={targetSpaceId => moveArtifactToSpace(moveMenu.artifactId, targetSpaceId)}
      onClose={() => setMoveMenu(null)}
    />
  )}

</section>
  );
}

export default memo(CanvasSection);
