"use client";

import { useEffect, useState } from "react";
import { baseUrl } from "@/lib/config";
import Navbar from "../components/Navbar/Navbar";
import HeroParent from "../components/HeroParent";
import AboutSection from "../components/AboutSection";
import ServicesSection from "../components/ServicesSection";
import { PropertyListings } from "../components/PropertyListings";
import WhatSetsAsApart from "../components/WhatSetsAsApart";
import BlogInHome from "../components/blogComponents/BlogInHome";
import Footer from "../components/Footer";
import BrandMarquee from "../components/marquee/BrandMarquee";
import { ClientTestimonials } from "../components/ClientTestimonials";

export default function Home() {
  const [blogData, setBlogData] = useState([]);
  const [propertyData, setPropertyData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = document.cookie
          .split("; ")
          .find((row) => row.startsWith("sadu_auth_token="))
          ?.split("=")[1];

        const [blogsRes, propertiesRes] = await Promise.all([
          fetch(`${baseUrl}/api/blogs`, { cache: "no-store" }),
          fetch(`${baseUrl}/api/properties`, {
            cache: "no-store",
            headers: token ? { Authorization: `Bearer ${token}` } : {},
          }),
        ]);

        if (!blogsRes.ok || !propertiesRes.ok) {
          throw new Error("Failed to fetch one or more resources");
        }

        const [blogs, properties] = await Promise.all([
          blogsRes.json(),
          propertiesRes.json(),
        ]);

        setBlogData(blogs);
        setPropertyData(properties);
      } catch (err) {
        console.error(err);
        setError("Error loading data. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading)
    return (
      <div className="flex justify-center items-center h-screen text-lg font-semibold">
        Loading...
      </div>
    );

  if (error)
    return (
      <div className="flex justify-center items-center h-screen text-red-600 font-semibold">
        {error}
      </div>
    );

  return (
    <div>
      <Navbar />
      <main>
        <HeroParent isBtn isHome />
        <BrandMarquee />
        <AboutSection />
        <ServicesSection />
        <PropertyListings propertyData={propertyData} />
        <WhatSetsAsApart />
        <ClientTestimonials />
        <BlogInHome data={blogData} />
      </main>
      <Footer />
    </div>
  );
}
