"use client";
export const dynamic = "force-dynamic";
export const revalidate = 0;
export const fetchCache = "force-no-store";
export const runtime = "edge"; // optional, but helps if you deploy to Vercel Edge


import React, { useEffect, useState } from "react";
import Navbar from "../components/Navbar/Navbar";
import { PropertyListings } from "../components/PropertyListings";
import FavouriteListings from "../components/profile/FavouriteListings";
import EditProfileModal from "../components/EditProfileModal";
import { Button } from "@/components/ui/button";
import Footer from "../components/Footer";
import { baseUrl } from "@/lib/config";

const page = () => {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [favorites, setFavorites] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    setName(localStorage.getItem("name"));
    setEmail(localStorage.getItem("email"));
  }, []);

  const getFavourites = async () => {
    try {
      setLoading(true);
      setError(null);

      const token = localStorage.getItem("sadu_auth_token"); // 🔑 get token (from localStorage, cookie, etc.)

      const res = await fetch(`${baseUrl}/api/favorites`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`, // attach token
        },
      });

      if (!res.ok) {
        throw new Error("Failed to fetch favorites");
      }

      const data = await res.json();
      setFavorites(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
      if (typeof window !== "undefined") {

    getFavourites();
      }
  }, []);

  console.log("favorites", favorites);
  return (
    <div>
      <Navbar />
      <div className="flex items-center justify-between mx-5 md:mx-[50px] lg:mx-[96px] p-4 rounded-2xl bg-ligbg mt-2 mb-8">
        <div>
          <h2 className="font-semibold">{name}</h2>
          <p>{email}</p>
        </div>
        <Button onClick={() => setOpen(true)} className="btn">
          Edit Profile
        </Button>
      </div>
      <EditProfileModal
        open={open}
        setOpen={setOpen}
        emailP={email}
        nameP={name}
      />
      <FavouriteListings favorites={favorites} getFavourites={getFavourites} />
      <Footer />
    </div>
  );
};

export default page;
