// Persisted preferences for the Multi-Coin Trend Matrix on the dashboard.
// Stores the user's favourite symbols (pinned to the top of the matrix) and
// the number of trending coins to show, in localStorage.

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

const FAV_KEY = "delta-terminal-trend-favorites";
const COUNT_KEY = "delta-terminal-trend-count";
const EVT = "trend-matrix-prefs-changed";

export const DEFAULT_COIN_COUNT = 12;
export const MIN_COIN_COUNT = 4;
export const MAX_COIN_COUNT = 60;

function readFavs(): string[] {
  if (typeof window === "undefined") return [];
  try {
    const raw = window.localStorage.getItem(FAV_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    return Array.isArray(arr) ? (arr.filter((x) => typeof x === "string") as string[]) : [];
  } catch {
    return [];
  }
}

function readCount(): number {
  if (typeof window === "undefined") return DEFAULT_COIN_COUNT;
  const raw = window.localStorage.getItem(COUNT_KEY);
  const n = raw ? Number(raw) : DEFAULT_COIN_COUNT;
  if (!Number.isFinite(n)) return DEFAULT_COIN_COUNT;
  return Math.min(MAX_COIN_COUNT, Math.max(MIN_COIN_COUNT, Math.round(n)));
}

function broadcast() {
  if (typeof window !== "undefined") window.dispatchEvent(new Event(EVT));
}

export function useTrendMatrixPrefs() {
  const [favorites, setFavorites] = useState<string[]>(() => readFavs());
  const [coinCount, setCoinCountState] = useState<number>(() => readCount());

  useEffect(() => {
    const sync = () => {
      setFavorites(readFavs());
      setCoinCountState(readCount());
    };
    window.addEventListener(EVT, sync);
    window.addEventListener("storage", sync);
    return () => {
      window.removeEventListener(EVT, sync);
      window.removeEventListener("storage", sync);
    };
  }, []);

  const toggleFavorite = useCallback((symbol: string) => {
    const current = readFavs();
    const next = current.includes(symbol) ? current.filter((s) => s !== symbol) : [...current, symbol];
    window.localStorage.setItem(FAV_KEY, JSON.stringify(next));
    broadcast();
  }, []);

  const removeFavorite = useCallback((symbol: string) => {
    const next = readFavs().filter((s) => s !== symbol);
    window.localStorage.setItem(FAV_KEY, JSON.stringify(next));
    broadcast();
  }, []);

  const setCoinCount = useCallback((n: number) => {
    const clamped = Math.min(MAX_COIN_COUNT, Math.max(MIN_COIN_COUNT, Math.round(n)));
    window.localStorage.setItem(COUNT_KEY, String(clamped));
    broadcast();
  }, []);

  return { favorites, coinCount, toggleFavorite, removeFavorite, setCoinCount };
}

export function openChartForSymbol(symbol: string) {
  if (typeof window !== "undefined") window.sessionStorage.setItem("chart:symbol", symbol);
}
