// src/pages/SearchPage.tsx
import { useEffect, useState, useRef } from "react"
import { useSearchParams } from "react-router-dom"
import MainLayout from "../layouts/MainLayout"
import DealCardMain from "../components/Shared/DealCardMain"
import { timeAgo } from "../utils/timeAgo"
import { searchDeals } from "../api/deal/searchDeal"

export default function SearchPage({ onRequireLogin }: { onRequireLogin: () => void }) {
  const [searchParams] = useSearchParams()
  const query = searchParams.get("query") || ""

  const [deals, setDeals] = useState<any[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)
  const observerRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    setDeals([])
    setPage(1)
    setHasMore(true)
  }, [query])

  useEffect(() => {
    const load = async () => {
      if (!query || loading || !hasMore) return
      setLoading(true)
      try {
        const newDeals = await searchDeals(query, page)
        if (newDeals.length === 0) setHasMore(false)
        else {
          setDeals((prev) => {
            const ids = new Set(prev.map((d) => d.id))
            return [...prev, ...newDeals.filter((d: any) => !ids.has(d.id))]
          })
        }
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [page, query])

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
          setPage((p) => p + 1)
        }
      },
      { threshold: 1 }
    )
    if (observerRef.current) observer.observe(observerRef.current)
    return () => observer.disconnect()
  }, [hasMore, loading])

  return (
    <MainLayout>
      <div className="max-w-[1400px] mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-4 gap-6">
        
       <aside className="hidden lg:block bg-surface/50 rounded-lg p-4">
          <p className="text-sm text-muted-foreground">Yan içerik / filtre / reklam alanı</p>
        </aside>
        <div className="lg:col-span-3 space-y-4">



          {deals.map((deal) => (
            <DealCardMain
              key={deal.id}
              id={deal.id}
              image={deal.images[0]?.imageUrl || "/placeholder.png"}
              title={deal.title}
              price={`${deal.price}₺`}
              store={deal.url ? new URL(deal.url).hostname : "Bilinmiyor"}
              postedBy={deal.user?.username || "unknown"}
              score={deal.score}
              comments={0}
              postedAgo={timeAgo(deal.createdAt)}
              onRequireLogin={onRequireLogin}
            />
          ))}

          {loading && <p className="text-center py-4">Yükleniyor...</p>}
          {!hasMore && <p className="text-center py-4 text-muted-foreground">Tüm sonuçlar yüklendi.</p>}
          <div ref={observerRef} className="h-8" />
        </div>


      </div>
    </MainLayout>
  )
}
