"use client";

import "react-multi-carousel/lib/styles.css";
import { HOME_CAROUSEL_SECTION_CLASS, HOME_CAROUSEL_HEADER_CLASS } from "./homeCarouselLayout";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import Title from "@/components/shared/Title";
import Link from "next/link";
import apiClient from "@/lib/api/client";
import { useAuthStore } from "@/store/authStore";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import EventCard from "./EventCard";
import type { HomeEvent } from "@/features/home/types";

interface EventsProps {
  /** Pre-fetched events from the server (optional — client fetches if absent) */
  initialEvents?: HomeEvent[];
}

export default function Events({ initialEvents = [] }: EventsProps) {
  const { t } = useTranslation();
  const user = useAuthStore((s) => s.user);

  // The authenticated homepage renders this section with no server data, so it
  // has to fetch for itself. Seeding only from a NON-empty server list matters:
  // `initialData` counts as fresh for `staleTime`, so seeding with [] would pin
  // the section empty for two minutes instead of fetching.
  const { data: eventsData, isError, error, refetch } = useQuery({
    queryKey: ["events-homepage"],
    queryFn: async () => {
      const { data } = await apiClient.get("/events/", {
        params: { page: 1, limit: 6 },
      });
      return data;
    },
    initialData: initialEvents.length > 0 ? { data: initialEvents } : undefined,
    staleTime: 2 * 60 * 1000,
  });

  const events: HomeEvent[] = Array.isArray(eventsData?.data)
    ? eventsData.data
    : initialEvents;

  return (
    <div className="border-b border-b-[#000000]/20">
      <div className={HOME_CAROUSEL_SECTION_CLASS}>
        <div className={HOME_CAROUSEL_HEADER_CLASS}>
          <h2>
            <Title
              text={t("COMMON.EVENTS")}
              variant="orange"
              hasMargin={false}
            />
          </h2>

          {/* {navigationVisibility && ( */}
            <Link
              href="/events-and-activities"
              className="text-primary-801 font-bold lg:text-lg md:text-lg text-base 2xl:text-xl"
              aria-label={t("COMMON.SHOW_ALL_EVENTS")}
            >
              {t("COMMON.SHOW.ALL")}
            </Link>
          {/* )} */}
        </div>
        {/* A failed load is not "no events" (p.37: distinct error state). */}
        {isError && events.length === 0 ? (
          <QueryErrorNotice error={error} onRetry={() => void refetch()} />
        ) : (
          <EventCard
            events={events}
            is_homepage={true}
            currentUser={user}
          />
        )}
      </div>
    </div>
  );
}
