"use client";

import { useEffect, useMemo, useState } from "react";
import { zodiacSigns, ZodiacSign } from "./zodiac";
import { getHoroscopeSigns } from "./horoscope";

export interface ZodiacSignWithImage extends ZodiacSign {
  svgImage?: string;
}

// GET /user/horoscope/signs supplies real inline SVG artwork per sign
// (no login needed) but no date-range/element/slug — those still come
// from the local zodiacSigns table in app/lib/zodiac.ts. This hook
// merges the two by numeric id (zodiacSigns.id === signs API's
// `zodiac`) so every page that renders the 12-sign picker/nav can show
// the real artwork instead of the plain symbol. Deliberately uses
// svg_image, not the sign's separate `image` PNG URL — confirmed live
// that 9 of the 12 PNG URLs 302-redirect to an HTML admin login page
// (a real backend storage bug), while svg_image ships as markup
// directly inside this same JSON response, so there's no separate
// network request that can fail.
export function useZodiacSigns(): {
  signs: ZodiacSignWithImage[];
  imagesLoaded: boolean;
} {
  const [svgImages, setSvgImages] = useState<Record<number, string>>({});
  const [imagesLoaded, setImagesLoaded] = useState(false);

  useEffect(() => {
    let cancelled = false;

    getHoroscopeSigns().then((result) => {
      if (cancelled) return;

      if (result.success && result.data.length > 0) {
        const map: Record<number, string> = {};

        for (const sign of result.data) {
          if (sign.svg_image) map[sign.zodiac] = sign.svg_image;
        }

        setSvgImages(map);
      }

      setImagesLoaded(true);
    });

    return () => {
      cancelled = true;
    };
  }, []);

  // Memoized on `svgImages` so callers can safely put `signs` in their
  // own effect deps without an infinite refetch loop — zodiacSigns.map
  // would otherwise return a brand-new array reference every render.
  const signs = useMemo(
    () =>
      zodiacSigns.map((zodiac) => ({
        ...zodiac,
        svgImage: svgImages[zodiac.id],
      })),
    [svgImages]
  );

  return { signs, imagesLoaded };
}
