"use client";
import { useState, useRef } from "react";
import { AnimatePresence } from "framer-motion";
import HeroSearch from "./HeroSearch";
import ShowIfOwner from "./ShowIfOwner";
import MapSection from "./MapSection";
import useApplyFilters from "../../hooks/useApplyFilters";
import HeroSection from "./HeroSection";
import FeatureSection from "./FeatureSection";
import ArrowForScroll from "./ArrowForScroll";
import useAuth from "@/app/hooks/useAuth";

export default function HomeClient() {
  const mapSectionRef = useRef(null);
  const [showMap, setShowMap] = useState(false);
  const [isScrolling, setIsScrolling] = useState(false);
  const { filteredProperties, applyFilters, resetFilters } = useApplyFilters();
  const { name, isOwner, isAuthenticated, role } = useAuth();
  const handleSearch = (filters) => {
    applyFilters(filters);
    if (!showMap) {
      setShowMap(true);
      setTimeout(() => {
        scrollToMap();
      }, 300);
    } else {
      scrollToMap();
    }
  };
  const scrollToMap = () => {
    if (mapSectionRef.current) {
      setIsScrolling(true);
      mapSectionRef.current.scrollIntoView({
        behavior: "smooth",
        block: "center",
      });
      setTimeout(() => setIsScrolling(false), 1000);
    }
  };
  const resetSearch = () => {
    setShowMap(false);
    resetFilters();
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };

  return (
    <div className="min-h-screen">
      <section className="relative min-h-screen flex items-center justify-center overflow-hidden">
        <div className="relative z-10 container mx-auto px-4 sm:px-6 lg:px-8">
          <div className="max-w-6xl mx-auto">
            <HeroSection />
            {!isOwner && <HeroSearch onSearch={handleSearch}  />}
            {isOwner && <ShowIfOwner name={name} />}
          </div>
        </div>
        {!showMap && !isOwner && <ArrowForScroll />}
      </section>
      {!isOwner && (
        <>
          <AnimatePresence mode="wait">
            {showMap && <MapSection mapSectionRef={mapSectionRef} isScrolling={isScrolling} resetSearch={resetSearch} filteredProperties={filteredProperties} />}
          </AnimatePresence>
        </>
      )}
      <FeatureSection />
    </div>
  );
}
