/**
 * Search history hook backed by localStorage via `@/shared/storage`.
 *
 * Persists search history per language with namespaced storage keys.
 * Angular equivalent: `SearchHistoryService` (ClientApp/src/app/shared/
 * services/history/search-history.service.ts), but enhanced with
 * localStorage persistence and per-language namespacing.
 *
 * @module
 */

import { useState, useCallback } from "react";
import { z } from "zod";
import { storage } from "@/shared/storage.js";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/** Search history item type — mirrors Angular's ISearchHistoryItemType */
export type SearchHistoryItemType =
  | "board-route"
  | "schedule-route"
  | "flight-number";

/** Search history item */
export interface SearchHistoryItem {
  type: SearchHistoryItemType;
  url: string;
  label: string;
}

export interface UseSearchHistoryResult {
  items: SearchHistoryItem[];
  add: (item: SearchHistoryItem) => void;
  clear: () => void;
}

// ---------------------------------------------------------------------------
// Schema (for validated storage round-tripping)
// ---------------------------------------------------------------------------

const searchHistoryItemSchema = z.object({
  type: z.enum(["board-route", "schedule-route", "flight-number"]),
  url: z.string(),
  label: z.string(),
});

const searchHistorySchema = z.array(searchHistoryItemSchema);

// ---------------------------------------------------------------------------
// Storage key
// ---------------------------------------------------------------------------

const MAX_HISTORY_ITEMS = 10;

function storageKey(lang: string): string {
  return `history_${lang}`;
}

// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------

/**
 * Hook for search history persisted to localStorage via `@/shared/storage`.
 *
 * @param lang - Current language code (e.g. "ru", "en"). History is
 *   namespaced per language so switching locales shows the appropriate
 *   history.
 */
export function useSearchHistory(lang: string): UseSearchHistoryResult {
  const key = storageKey(lang);

  const [items, setItems] = useState<SearchHistoryItem[]>(() => {
    return storage.get(key, searchHistorySchema) ?? [];
  });

  const add = useCallback(
    (item: SearchHistoryItem) => {
      setItems((prev) => {
        // Deduplicate by URL — don't add if the most recent entry matches
        if (prev[0]?.url === item.url) {
          return prev;
        }

        // Remove any existing entry with same URL, then prepend
        const filtered = prev.filter((existing) => existing.url !== item.url);
        const next = [item, ...filtered].slice(0, MAX_HISTORY_ITEMS);

        storage.set(key, next, searchHistorySchema);
        return next;
      });
    },
    [key],
  );

  const clear = useCallback(() => {
    storage.delete(key);
    setItems([]);
  }, [key]);

  return { items, add, clear };
}
