"use client";

import { useState, useCallback, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";

export type ViewMode = "executive" | "full";

const LS_KEY = "meseo-view-mode";

export function useViewMode(
  auditType: "1st" | "3rd",
  hasExecutiveBrief: boolean,
): { viewMode: ViewMode; setViewMode: (m: ViewMode) => void } {
  const router = useRouter();
  const searchParams = useSearchParams();

  // Determine default: 3rd-party → executive (if brief available), 1st-party → full
  const typeDefault: ViewMode = auditType === "3rd" && hasExecutiveBrief ? "executive" : "full";

  function resolveInitial(): ViewMode {
    const fromUrl = searchParams.get("view");
    if (fromUrl === "executive" || fromUrl === "full") {
      // Only allow executive if brief exists
      if (fromUrl === "executive" && !hasExecutiveBrief) return "full";
      return fromUrl;
    }
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem(LS_KEY);
      if (stored === "executive" || stored === "full") {
        if (stored === "executive" && !hasExecutiveBrief) return "full";
        return stored;
      }
    }
    return typeDefault;
  }

  const [viewMode, setViewModeState] = useState<ViewMode>(resolveInitial);

  // Sync localStorage → state on mount (client-side hydration)
  useEffect(() => {
    const resolved = resolveInitial();
    if (resolved !== viewMode) setViewModeState(resolved);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const setViewMode = useCallback((m: ViewMode) => {
    setViewModeState(m);
    try { localStorage.setItem(LS_KEY, m); } catch { /* ignore */ }
    const p = new URLSearchParams(searchParams.toString());
    p.set("view", m);
    router.push(`?${p.toString()}`, { scroll: false });
  }, [router, searchParams]);

  return { viewMode, setViewMode };
}
