"use client";

import { useState, useEffect, useRef } from "react";
import type { AiIndicatorData } from "@/components/ai-badge";

interface AiIndicatorMap {
  keywords: Record<string, AiIndicatorData>;
  pages: Record<string, AiIndicatorData>;
  loading: boolean;
}

const cache = new Map<string, { data: AiIndicatorMap; ts: number }>();
const CACHE_TTL = 10 * 60 * 1000;

export function useAiIndicators(
  brandId: string,
  items: Array<{ type: "keyword" | "page"; value: string }>,
): AiIndicatorMap {
  const [result, setResult] = useState<AiIndicatorMap>({ keywords: {}, pages: {}, loading: true });
  const fetchedRef = useRef<string>("");

  useEffect(() => {
    if (!brandId || items.length === 0) {
      setResult({ keywords: {}, pages: {}, loading: false });
      return;
    }

    const keywords = items.filter((i) => i.type === "keyword").map((i) => i.value);
    const pages = items.filter((i) => i.type === "page").map((i) => i.value);
    const cacheKey = `${brandId}:${keywords.sort().join(",")}:${pages.sort().join(",")}`;

    if (cacheKey === fetchedRef.current) return;

    const cached = cache.get(cacheKey);
    if (cached && Date.now() - cached.ts < CACHE_TTL) {
      fetchedRef.current = cacheKey;
      setResult(cached.data);
      return;
    }

    fetchedRef.current = cacheKey;
    setResult((prev) => ({ ...prev, loading: true }));

    fetch("/api/ai-indicators", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ brandId, keywords, pages }),
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data) {
          const mapped: AiIndicatorMap = {
            keywords: data.keywords ?? {},
            pages: data.pages ?? {},
            loading: false,
          };
          cache.set(cacheKey, { data: mapped, ts: Date.now() });
          setResult(mapped);
        } else {
          setResult({ keywords: {}, pages: {}, loading: false });
        }
      })
      .catch(() => {
        setResult({ keywords: {}, pages: {}, loading: false });
      });
  }, [brandId, items]);

  return result;
}
