"use client";

import { useEffect, useState } from "react";
import { Navbar } from "@/components/public/Navbar";
import { HeroSection } from "@/components/public/HeroSection";
import { KnowledgeCards } from "@/components/public/KnowledgeCards";
import { AboutSection } from "@/components/public/AboutSection";
import { CommunityLinksSection } from "@/components/public/CommunityLinksSection";
import { MeetupsSection } from "@/components/public/MeetupsSection";
import { FAQSection } from "@/components/public/FAQSection";
import { FinalCTASection } from "@/components/public/FinalCTASection";
import { Footer } from "@/components/public/Footer";
import { api } from "@/lib/api";

export default function HomePage() {
  const [meetup, setMeetup] = useState<any>(null);
  const [allMeetups, setAllMeetups] = useState<any[]>([]);
  const [settings, setSettings] = useState<Record<string, string>>({});

  useEffect(() => {
    api.getMeetups()
      .then((data: any) => {
        const all = Array.isArray(data) ? data : data?.meetups ?? [];
        const now = new Date();
        // Keep only PUBLISHED events with a future date, sorted closest-first
        const upcoming = all
          .filter((m: any) => m.status === "PUBLISHED" && m.date && new Date(m.date) > now)
          .sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime());
        setAllMeetups(upcoming);
        if (upcoming.length > 0) setMeetup(upcoming[0]);
      })
      .catch(() => {});

    api.getPublicSettings()
      .then((data) => setSettings(data))
      .catch(() => {});
  }, []);

  const meetupProps = meetup
    ? {
        id: meetup.id,
        month: new Date(meetup.date).toLocaleString("en-US", { month: "short" }),
        day: String(new Date(meetup.date).getDate()),
        title: meetup.title,
        location: meetup.location,
        time: meetup.time,
        link: meetup.link || "#meetup",
      }
    : undefined;

  return (
    <main>
      <Navbar />
      <section id="meetup">
        <HeroSection meetup={meetupProps} />
      </section>
      <section id="about">
        <AboutSection />
      </section>
      <KnowledgeCards />
      <CommunityLinksSection settings={settings} />
      <section id="upcoming-meetups">
        <MeetupsSection meetups={allMeetups} />
      </section>
      <section id="faq">
        <FAQSection />
      </section>
      <FinalCTASection telegramLink={settings.telegram_link} />
      <Footer />
    </main>
  );
}
