"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { ResearchMapRefinePanel } from "@/components/research-map-refine-panel";
import {
  hydrateRefineSessionsFromStorage,
  setActiveTopicId,
} from "@/lib/refine-session/store";
import { useRefineSession, useRefineSessionStore } from "@/lib/refine-session/use-refine-session";

export function RefineSessionHost() {
  const [mounted, setMounted] = useState(false);
  const pathname = usePathname();
  const { displayTopicId } = useRefineSessionStore();
  const session = useRefineSession(displayTopicId);

  useEffect(() => {
    hydrateRefineSessionsFromStorage();
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    const match = pathname.match(/^\/scans\/([^/]+)/);
    if (match) {
      setActiveTopicId(match[1]);
    }
  }, [pathname, mounted]);

  if (!mounted) return null;
  if (!displayTopicId || !session?.draft || !session.engaged) return null;

  return (
    <ResearchMapRefinePanel
      topicId={displayTopicId}
      topicLabel={session.topicLabel}
    />
  );
}