"use client";

import { useCallback } from "react";
import { useLocalStorage } from "./useLocalStorage.js";

export type HeatmapColorScheme = "green-red" | "blue-orange" | "purple-yellow" | "mono";

export interface AppPreferences {
  /** Hide allocations that belong to COMPLETED or CANCELLED projects. Default: true. */
  hideCompletedProjects: boolean;
  /**
   * Timeline row rendering style.
   * "strip"   — horizontal colored blocks per allocation (classic Gantt) + load graph
   * "bar"     — stacked vertical bars per day showing hours by project
   * "heatmap" — strips overlaid with a green→red utilization colour per day column
   */
  timelineDisplayMode: "strip" | "bar" | "heatmap";
  /** Color palette used for heatmap overlays and bar-mode project view bars. */
  heatmapColorScheme: HeatmapColorScheme;
  /** Show open demand / placeholder entries by default when loading the timeline. Default: true. */
  showDemandProjects: boolean;
  /** Blink overbooked days (>8h) as a warning on the timeline. Default: false. */
  blinkOverbookedDays: boolean;
}

const STORAGE_KEY = "capakraken_prefs";
const CHANGE_EVENT = "capakraken-prefs-changed";

const DEFAULT: AppPreferences = {
  hideCompletedProjects: true,
  timelineDisplayMode: "strip",
  heatmapColorScheme: "green-red",
  showDemandProjects: true,
  blinkOverbookedDays: false,
};

export function readAppPreferences(): AppPreferences {
  if (typeof window === "undefined") return DEFAULT;
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return DEFAULT;
    return { ...DEFAULT, ...(JSON.parse(raw) as Partial<AppPreferences>) };
  } catch {
    return DEFAULT;
  }
}

export function useAppPreferences() {
  const [prefs, setPrefs] = useLocalStorage<AppPreferences>(STORAGE_KEY, DEFAULT, CHANGE_EVENT);

  const setHideCompletedProjects = useCallback((value: boolean) => {
    setPrefs((prev) => ({ ...prev, hideCompletedProjects: value }));
  }, [setPrefs]);

  const setTimelineDisplayMode = useCallback((value: AppPreferences["timelineDisplayMode"]) => {
    setPrefs((prev) => ({ ...prev, timelineDisplayMode: value }));
  }, [setPrefs]);

  const setHeatmapColorScheme = useCallback((value: HeatmapColorScheme) => {
    setPrefs((prev) => ({ ...prev, heatmapColorScheme: value }));
  }, [setPrefs]);

  const setShowDemandProjects = useCallback((value: boolean) => {
    setPrefs((prev) => ({ ...prev, showDemandProjects: value }));
  }, [setPrefs]);

  const setBlinkOverbookedDays = useCallback((value: boolean) => {
    setPrefs((prev) => ({ ...prev, blinkOverbookedDays: value }));
  }, [setPrefs]);

  return { prefs, setHideCompletedProjects, setTimelineDisplayMode, setHeatmapColorScheme, setShowDemandProjects, setBlinkOverbookedDays };
}
