"use client";

import { Suspense, useEffect, useState } from "react";
import { ReactFlowProvider } from "@xyflow/react";
import { Header } from "@/components/Header";
import { WorkflowCanvas } from "@/components/WorkflowCanvas";
import { FloatingActionBar } from "@/components/FloatingActionBar";
import { PopiaiEmbedBridge } from "@/components/PopiaiEmbedBridge";
import { useWorkflowStore } from "@/store/workflowStore";
import { FTUXModal } from "@/components/onboarding/FTUXModal";
import { getFTUXCompleted, setFTUXCompleted } from "@/store/utils/localStorage";
import { useFTUXStore } from "@/store/ftuxStore";
import { useSearchParams } from "next/navigation";
import { useModelStore } from "@/store/modelStore";
import { isPopiProviderMode } from "@/lib/providerMode";
import { useCanvasWorkflowLoader } from "@/hooks/useCanvasWorkflowLoader";
import { useCanvasWorkflowAutoUpdate } from "@/hooks/useCanvasWorkflowAutoUpdate";

function CanvasPageContent() {
  const initializeAutoSave = useWorkflowStore(
    (state) => state.initializeAutoSave
  );
  const cleanupAutoSave = useWorkflowStore((state) => state.cleanupAutoSave);
  const initializePopiModels = useModelStore((state) => state.initializePopiModels);
  const [showFTUX, setShowFTUX] = useState(false);

  const searchParams = useSearchParams();
  const workflowId = searchParams.get("workflowId");

  useCanvasWorkflowLoader(workflowId);
  useCanvasWorkflowAutoUpdate();

  useEffect(() => {
    if (!isPopiProviderMode()) return;
    void initializePopiModels();
  }, [initializePopiModels]);

  useEffect(() => {
    initializeAutoSave();
    return () => cleanupAutoSave();
  }, [initializeAutoSave, cleanupAutoSave]);

  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (useWorkflowStore.getState().hasUnsavedChanges) {
        e.preventDefault();
      }
    };
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, []);

  // Client-side only FTUX check (SSR-safe)
  useEffect(() => {
    const isPopiaiEmbed = new URLSearchParams(window.location.search).get("embed") === "popiai";
    if (isPopiaiEmbed) {
      setShowFTUX(false);
      useFTUXStore.getState().resetTutorial();
      return;
    }

    if (!getFTUXCompleted()) {
      setShowFTUX(true);
    }
  }, []);

  const handleFTUXComplete = () => {
    setShowFTUX(false);
    setFTUXCompleted(true);
  };

  const handleStartTutorial = () => {
    setShowFTUX(false);
    setFTUXCompleted(true);
    useFTUXStore.getState().startTutorial();
  };

  return (
    <ReactFlowProvider>
      <div className="h-screen flex flex-col">
        <Header />
        <WorkflowCanvas />
        <FloatingActionBar />
        <PopiaiEmbedBridge />
        {showFTUX && (
          <FTUXModal
            onComplete={handleFTUXComplete}
            onStartTutorial={handleStartTutorial}
          />
        )}
      </div>
    </ReactFlowProvider>
  );
}

export default function Home() {
  return (
    <Suspense fallback={null}>
      <CanvasPageContent />
    </Suspense>
  );
}
