"use client";

import dynamic from "next/dynamic";
import ComponentPalette from "@/components/palette/ComponentPalette";
import PropertiesPanel from "@/components/panels/PropertiesPanel";
import ResultsPanel from "@/components/panels/ResultsPanel";
import DofStatusBar from "@/components/DofStatusBar";
import Toolbar from "@/components/Toolbar";
import { useDiagramStore } from "@/store/diagramStore";

// React Flow needs the DOM — load only on the client.
const Canvas = dynamic(() => import("@/components/canvas/Canvas"), { ssr: false });

export default function Page() {
  const { result, simError, lastConfig, nodes, simulating } = useDiagramStore();

  return (
    <div className="flex h-screen flex-col">
      <Toolbar />
      <div className="flex min-h-0 flex-1 overflow-hidden">
        <ComponentPalette />

        <div className="relative flex-1">
          <Canvas />
          {nodes.length === 0 && <EmptyHint />}
        </div>

        {/* Right column: parameter dialog + results, stacked & scrollable */}
        <div className="flex w-96 flex-col overflow-y-auto border-l border-[var(--line)] bg-[var(--panel)]">
          <PropertiesPanel />
          <div className="h-2 bg-[var(--chrome)]" />
          <ResultsPanel result={result} error={simError} config={lastConfig} simulating={simulating} />
        </div>
      </div>
      {/* Live DoF indicator: equations vs unknowns (fix/free discipline) */}
      <DofStatusBar />
    </div>
  );
}

function EmptyHint() {
  return (
    <div className="pointer-events-none absolute inset-0 grid place-items-center">
      <div className="max-w-sm text-center">
        <p className="text-[15px] font-semibold text-[var(--ink-dim)]">Start your cycle</p>
        <p className="mt-1 text-[12px] leading-relaxed text-[var(--ink-faint)]">
          Drag parts from the library onto the sheet, then wire ports. Select a part,
          then use the top bar, right-click menu, or{" "}
          <span className="mono">R</span>/<span className="mono">H</span>/
          <span className="mono">V</span>. Drop a pipe on a line to insert it.
        </p>
      </div>
    </div>
  );
}
