import { useCallback, useRef, useState } from 'react';
import type Konva from 'konva';
import type { TraceMetadata } from './types/engine';
import { useCanvasState } from './hooks/useCanvasState';
import ImportConvert from './views/ImportConvert';
import DesignCanvas from './views/DesignCanvas';
import ExportView from './views/ExportView';
import './App.css';

type ViewState = 'import' | 'canvas' | 'export';

function App() {
  const [view, setView] = useState<ViewState>('import');
  const [svgResult, setSvgResult] = useState<string | null>(null);
  const [traceMetadata, setTraceMetadata] = useState<TraceMetadata | null>(null);
  const [pngDataUrl, setPngDataUrl] = useState<string | null>(null);

  // Lifted canvas state — shared between View 2 (DesignCanvas) and View 3 (ExportView)
  const canvasState = useCanvasState(traceMetadata);

  // Stage ref created here so View 3 can capture PNG from View 2's Konva stage
  const stageRef = useRef<Konva.Stage | null>(null);

  const handleUseThis = (svgOutput: string, metadata: TraceMetadata) => {
    setSvgResult(svgOutput);
    setTraceMetadata(metadata);
    setView('canvas');
  };

  const handleExport = useCallback(() => {
    // Capture PNG data URL from the Konva stage before navigating away
    if (stageRef.current) {
      const dataUrl = stageRef.current.toDataURL({ pixelRatio: 2 });
      setPngDataUrl(dataUrl);
    }
    setView('export');
  }, []);

  const handleBackToCanvas = useCallback(() => {
    setView('canvas');
  }, []);

  return (
    <div id="app">
      {view === 'import' && <ImportConvert onUseThis={handleUseThis} />}
      {view === 'canvas' && (
        <DesignCanvas
          svgData={svgResult}
          stageRef={stageRef}
          onExport={handleExport}
          {...canvasState}
        />
      )}
      {view === 'export' && (
        <ExportView
          objects={canvasState.state.objects}
          artboard={canvasState.state.artboard}
          pngDataUrl={pngDataUrl}
          onBack={handleBackToCanvas}
        />
      )}
    </div>
  );
}

export default App;
