"use client";

import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import type { SessionWithTokens } from "@/config/authConfig";
import {
  type ChartBoardId,
  CHART_BOARD_DEFAULT_REFRESH_INTERVAL_SEC,
  loadChartBoardRefreshPrefs,
  saveChartBoardRefreshPrefs,
} from "./chartBoardRefreshPrefs";

/** Session id may be string or number from JWT / callbacks — never assume .trim exists. */
function normalizeKeyPart(v: unknown): string | undefined {
  if (v == null) return undefined;
  const s = typeof v === "string" ? v : String(v);
  const t = s.trim();
  return t.length > 0 ? t : undefined;
}

function resolveUserKey(session: SessionWithTokens | null): string | undefined {
  const id = normalizeKeyPart(session?.id);
  if (id) return `id:${id}`;
  const email = normalizeKeyPart(session?.user?.email);
  if (email) return `email:${email.toLowerCase()}`;
  return undefined;
}

export function useChartBoardRefreshPrefs(boardId: ChartBoardId) {
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const userKeyPart = resolveUserKey(session);

  const [autoRefreshOn, setAutoRefreshOn] = useState(false);
  const [refreshIntervalSec, setRefreshIntervalSec] = useState(CHART_BOARD_DEFAULT_REFRESH_INTERVAL_SEC);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    const prefs = loadChartBoardRefreshPrefs(boardId, userKeyPart);
    setAutoRefreshOn(prefs.autoRefreshOn);
    setRefreshIntervalSec(prefs.refreshIntervalSec);
    setHydrated(true);
  }, [boardId, userKeyPart]);

  useEffect(() => {
    if (!hydrated) return;
    saveChartBoardRefreshPrefs(boardId, userKeyPart, {
      autoRefreshOn,
      refreshIntervalSec,
    });
  }, [hydrated, boardId, userKeyPart, autoRefreshOn, refreshIntervalSec]);

  return {
    autoRefreshOn,
    setAutoRefreshOn,
    refreshIntervalSec,
    setRefreshIntervalSec,
    /** Logged-in user key for storage; undefined if not available */
    userKeyPart,
    hydrated,
  };
}
