import { useCallback, useEffect, useState } from "react";

import type { FleetResourceSlug } from "@/pages/fleet/config/resources";

export type FleetViewMode = "table" | "cards";

const STORAGE_PREFIX = "edr-freight-fleet-view:";

type ViewModeSlug = FleetResourceSlug | "routes" | "train-scheduling-v2" | "batch-board";

const readStored = (slug: ViewModeSlug): FleetViewMode => {
  try {
    const raw = localStorage.getItem(`${STORAGE_PREFIX}${slug}`);
    return raw === "cards" ? "cards" : "table";
  } catch {
    return "table";
  }
};

export const useFleetViewMode = (slug: ViewModeSlug) => {
  const [viewMode, setViewModeState] = useState<FleetViewMode>(() => readStored(slug));

  useEffect(() => {
    setViewModeState(readStored(slug));
  }, [slug]);

  const setViewMode = useCallback(
    (mode: FleetViewMode) => {
      setViewModeState(mode);
      try {
        localStorage.setItem(`${STORAGE_PREFIX}${slug}`, mode);
      } catch {
        /* ignore */
      }
    },
    [slug],
  );

  return { viewMode, setViewMode };
};
