import { useState } from "react";
import type { ImageStudioApp } from "@app/app";
import { BottomControlsIsland } from "./BottomControlsIsland";
import { CanvasViewport } from "./CanvasViewport";
import { LayersSheet } from "./LayersSheet";
import { ToolOverlay } from "./ToolOverlay";
import { labelForTool } from "./toolLabels";
import { getSelectionSummary } from "./selectionSummary";
import { useAppState } from "./useAppState";
import { useViewportActivityIsland } from "./useViewportActivityIsland";
import "./index.css";

export type AppProps = {
  app: ImageStudioApp;
};

export function App({ app }: AppProps) {
  const state = useAppState(app.store);
  const zoomPercent = Math.round(state.editor.viewport.zoom * 100);
  const viewportActivityIsland = useViewportActivityIsland(state.editor.viewport);
  const [layersOpen, setLayersOpen] = useState(false);
  const selectionSummary = getSelectionSummary(state.document, state.editor.selection);

  return (
    <main className="relative h-full overflow-hidden bg-background text-foreground">
      <header className="pointer-events-none absolute inset-x-0 top-0 z-10 flex h-8 items-center justify-between px-3 text-white">
        <h1 className="text-sm font-medium">Image Studio</h1>
        <div className="text-xs">
          {state.document.name} · {labelForTool(state.editor.tools.activeTool)} · {zoomPercent}% · {state.editor.viewport.size.w}×
          {state.editor.viewport.size.h}
        </div>
      </header>
      <div className="absolute left-3 top-1/2 z-10 -translate-y-1/2">
        <ToolOverlay
          activeTool={state.editor.tools.activeTool}
          interactionMode={state.editor.tools.interactionMode}
          dispatch={app.store.dispatch}
        />
      </div>
      <LayersSheet document={state.document} selection={state.editor.selection} open={layersOpen} onClose={() => setLayersOpen(false)} />
      <div className="absolute inset-x-0 bottom-4 z-10 flex justify-center">
        <BottomControlsIsland
          viewport={state.editor.viewport}
          visible={selectionSummary.type !== "none" || viewportActivityIsland.visible}
          action={viewportActivityIsland.action}
          selection={selectionSummary}
          dispatch={app.store.dispatch}
          onOpenLayers={() => setLayersOpen(true)}
        />
      </div>
      <CanvasViewport store={app.store} />
    </main>
  );
}

export default App;
