"use client";

import { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  filterByCategory,
  initializeNewsroom,
  refreshNewsrooms,
  selectNewsroom,
} from "@/store/slices/newsroomSlice";
import { CategorySlider } from "./CategorySlider";
import { NewsroomArchives } from "./NewsroomArchives";
import { NewsroomGrid } from "./NewsroomGrid";
import { NewsroomHero } from "./NewsroomHero";
import type {
  NewsroomCategory,
  NewsroomItem,
  NewsroomPagination,
} from "@/types/newsroom";

interface NewsroomContentProps {
  initialCategories: NewsroomCategory[];
  initialNewsrooms: NewsroomPagination;
  initialLatestRecord: NewsroomItem | null;
  initialLatestRecords?: NewsroomItem[];
  initialArchiveYears?: (number | string)[];
}

export function NewsroomContent({
  initialCategories,
  initialNewsrooms,
  initialLatestRecord,
  initialLatestRecords = [],
  initialArchiveYears = [],
}: NewsroomContentProps) {
  const dispatch = useAppDispatch();

  // Initialize Redux store on client mount & immediately fetch fresh articles from the API
  useEffect(() => {
    // 1. Instantly populate store with SSR/initial data for zero layout shift
    dispatch(
      initializeNewsroom({
        categories: initialCategories,
        articles: initialNewsrooms.docs || [],
        latestRecord: initialLatestRecord,
        latestRecords: initialLatestRecords,
        pagination: initialNewsrooms,
        archiveYears: initialArchiveYears,
      }),
    );

    // 2. Call the API to fetch latest newsroom articles (ensures navigating back gets newest data)
    dispatch(refreshNewsrooms(""));
  }, [dispatch, initialCategories, initialNewsrooms, initialLatestRecord, initialLatestRecords, initialArchiveYears]);

  const reduxState = useAppSelector(selectNewsroom);

  // Use Redux state once populated or action performed; fallback to initial SSR data on first paint
  const categories =
    reduxState.categories.length > 0 ? reduxState.categories : initialCategories;

  const articles =
    reduxState.articles.length > 0 || reduxState.selectedCategory !== ""
      ? reduxState.articles
      : initialNewsrooms.docs || [];

  const latestRecord = reduxState.latestRecord ?? initialLatestRecord;
  const latestRecords =
    reduxState.latestRecords.length > 0
      ? reduxState.latestRecords
      : initialLatestRecords.length > 0
        ? initialLatestRecords
        : articles.slice(0, 3);

  const selectedCategory = reduxState.selectedCategory;
  const loading = reduxState.loading;

  const handleSelectCategory = (categoryId: string) => {
    dispatch(filterByCategory(categoryId));
  };

  const handleResetCategory = () => {
    dispatch(filterByCategory(""));
  };

  return (
    <div className="mx-auto w-full max-w-[1280px] px-[60px] max-[769px]:px-5">
      {/* 1. Latest Record / Hero Section */}
      <NewsroomHero
        latestRecords={latestRecords}
        latestRecord={latestRecord}
      />

      {/* Section Header: Explore all topics */}
      {/* <div id="explore-topics" className="mb-6 w-full pt-4">
        <h2 className="text-2xl font-normal tracking-tight text-[#0d2440] sm:text-3xl">
          Explore all topics
        </h2>
      </div> */}

      {/* 2. Category Filter Chips with Image 4 styling */}
      {/* <CategorySlider
        categories={categories}
        selectedCategory={selectedCategory}
        onSelectCategory={handleSelectCategory}
        disabled={loading}
      /> */}

      {/* 3. Newsroom Cards Grid */}
      <NewsroomGrid
        articles={articles}
        loading={loading}
        onResetCategory={handleResetCategory}
      />

      {/* 4. Archives Section */}
      <NewsroomArchives
        years={
          reduxState.archiveYears.length > 0
            ? reduxState.archiveYears
            : initialArchiveYears
        }
      />
    </div>
  );
}
