/* eslint-disable @typescript-eslint/no-explicit-any */
import { buildPageMetadata } from "@/lib/metadata.helpers";
import type { Metadata } from "next";
import { getLocale } from "next-intl/server";
import { cache } from "react";
import { getAllWebsiteData } from "../_api/query";
import GPTOver from "../_comps/layout/widgetLayout/GPT_Cards/GPTOver";
import {
  getAllCategories,
  getAllNews,
  getLatestArticles,
  getMostReadNews,
  getSliderNews,
} from "./_api/query";
import Articles from "./_comps/arabic/articles";
import MostRead from "./_comps/arabic/mostRead";
import ShortLinkParamRedirect from "./_comps/cards/shortLinkParamRedirect";
import HomePageIndex from "./_comps/homePageIndex";
import AdLargeBanner from "../_comps/layout/widgetLayout/GPT_Cards/adLargeBanner";
import RecommendedForYou from "../_comps/tracking/RecommendedForYou";
// import RecommendedForYou from "../_comps/tracking/RecommendedForYou";

// Revalidate every 5 minutes to prevent stale data errors
export const revalidate = 300; // 5 minutes in seconds
export const dynamicParams = true;

const getCachedCategories = cache(async () => {
  return getAllCategories({});
});

const getCachedSliderNews = cache(async () => {
  return getSliderNews({ params: { per_page: 10 } });
});

const getCachedMostRead = cache(async () => {
  return getMostReadNews({ params: { per_page: 8 } });
});

export async function generateMetadata(): Promise<Metadata> {
  const locale = await getLocale();
  const allWebsiteData = await getAllWebsiteData({ params: { type: locale } });
  console.log(allWebsiteData, "allWebsiteData");

  // Use dynamic logo from CMS, fallback to static
  const logo = allWebsiteData?.website_settings?.favicon;

  // Use dynamic favicon from CMS
  const favicon = allWebsiteData?.website_settings?.favicon;

  const description =
    locale === "ar"
      ? "تابع آخر أخبار المال والأعمال والاقتصاد السعودي مع تحليلات متعمقة وتقارير حصرية. مصدرك الموثوق للأخبار المالية والاستثمارية في المملكة."
      : "Follow the latest Saudi business, finance, and economy news with in-depth analysis and exclusive reports. Your trusted source for financial and investment news in the Kingdom.";

  return buildPageMetadata({
    title:
      locale === "ar"
        ? "صحيفة مال - أخبار المال والأعمال والاقتصاد السعودي"
        : "Maaal -Saudi Business, Finance & Economy News",
    description,
    image: logo,
    keywords:
      locale === "ar"
        ? "اخبار، أخبار المال، أخبار الأعمال، الاقتصاد السعودي، البورصة، الأسهم"
        : "News, Business News, Financial News, Saudi Economy, Stock Market",
    url: "/",
    type: "website",
    favicon, // ✅ Pass dynamic favicon
  });
}

export default async function Home() {
  // Use Promise.allSettled to prevent one failure from breaking the entire page
  const results = await Promise.allSettled([
    getCachedCategories(),
    getAllNews({ params: { per_page: 10 } }),
    getCachedSliderNews(),
    getCachedMostRead(),
    getLatestArticles({ per_page: 4 }),
  ]);

  // Extract data with fallbacks for failed promises
  const categories = results[0].status === "fulfilled" ? results[0].value : { list: [] };
  const allNews = results[1].status === "fulfilled" ? results[1].value : { list: [] };
  const sliderNews = results[2].status === "fulfilled" ? results[2].value : { list: [] };
  const mostRead = results[3].status === "fulfilled" ? results[3].value : { list: [] };
  const latestArticles =
    results[4].status === "fulfilled" ? results[4].value : { list: [] };

  // Log any failures in development
  if (process.env.NODE_ENV === "development") {
    results.forEach((result, index) => {
      if (result.status === "rejected") {
        console.error(`Homepage data fetch ${index} failed:`, result.reason);
      }
    });
  }
console.log(categories, "categories");

  const categoriesIndex = categories?.list?.reduce((prev: Record<string, any>, curr: any) => {
    const prevCopy = { ...prev };
    prevCopy[curr.id] = curr;
    return prevCopy;
  }, {});

  return (
    <div className="flex flex-col gap-4 md:gap-6 py-3 pt-6 ">
      <h1 className="sr-only">
        {(await getLocale()) === "ar"
          ? "مال - أخبار المال والأعمال"
          : "Maaal - Business & Financial News"}
      </h1>
      <GPTOver />
      <MostRead
        sliderNewsData={sliderNews}
        mostReadData={mostRead}
        allNews={allNews}
      />
      <AdLargeBanner />
      <Articles className="container" initialArticles={latestArticles} />
      {/* <RecommendedForYou /> */}
      <HomePageIndex categoriesIndex={categoriesIndex} />
      <ShortLinkParamRedirect />
    </div>
  );
}
