// src/pages/properties/index.js

import HomeSlider from "@/components/Commen/HomeSlider";
import NotificationBar from "@/components/Commen/NotificationBar";
import HomePageNewComponent from "@/components/UpdateBharat/HomePageNewComponent";
import SearchBar from "@/components/UpdateBharat/SearchBar";
import { URL } from "@/components/url";
import Head from "next/head";

/* ================= COMMON FETCH ================= */
const fetchJSON = async (url, options = {}) => {
  try {
    const res = await fetch(url, options);
    if (!res.ok) throw new Error("Failed to fetch " + url);
    const data = await res.json();
    return data?.data || [];
  } catch (err) {
    console.error("Fetch error:", err);
    return [];
  }
};

/* ================= API CALLS ================= */
const getNewsList = ({ cate, search, locationar, location, locationst }) =>
  fetchJSON(
    `${URL.API_BASE_URL}/publicApi/getNewListPub1/1?category=${cate}&currentPage=home&search=${search}&locationar=${locationar}&location=${location}&locationst=${locationst}`,
  );

/* ================= PAGE ================= */
export default function PropertiesPage({
  categoriesList,
  newsList,
  sliderList,
  seo,
  cate,
}) {
  return (
    <>
      {/* SEO */}
      <Head>
        <title>{seo.title}</title>
        <meta name="description" content={seo.description} />

        <meta property="og:title" content={seo.title} />
        <meta property="og:description" content={seo.description} />
        <meta property="og:image" content={seo.image} />
        <meta property="og:url" content={seo.url} />
        <meta property="og:type" content="website" />
      </Head>

      <HomeSlider sliderList={sliderList} />
      <SearchBar slug={cate} />
      <NotificationBar />

      <HomePageNewComponent
        categoriesList={categoriesList}
        newsList={newsList}
        params={{ slug: cate }}
      />
    </>
  );
}

/* ================= SERVER SIDE ================= */
export async function getServerSideProps(context) {
  const { query } = context;
  const { slug } = context.params;
  const cate = slug || "";
  const search = query?.search || "";
  const locationar = query?.locationar || "";
  const location = query?.location || "";
  const locationst = query?.locationst || "";

  const newsList1 = await getNewsList({
    cate,
    search,
    locationar,
    location,
    locationst,
  });

  const seoTitle = cate
    ? cate.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
    : "Properties";

  const seo = {
    title: `${seoTitle} | Update Bharat`,
    description: `Find properties related to "${seoTitle}" on Update Bharat.`,
    url: "https://apnaplotdekho.com/properties",
    image: "https://apnaplotdekho.com/image/property-2.jpg",
  };

  return {
    props: {
      newsList: newsList1?.newsList || [],
      categoriesList: newsList1?.categoryList || [],
      sliderList: newsList1?.sliderList || [],
      seo,
      cate,
    },
  };
}
