// src/pages/Home.tsx
import { useEffect, useState, useRef } from "react"
import MainLayout from "../layouts/MainLayout"
import DealCardMain from "../components/Shared/DealCardMain"
import { getDeals } from "../api/deal/getDeal"
import { timeAgo } from "../utils/timeAgo"

type Deal = {
  id: number
  title: string
  description: string
  url: string
  images: { imageUrl: string }[]
  price: number
  score: number
  createdAt: string
  user?: { username: string }
}

type HomeProps = {
  onRequireLogin: () => void
}

export default function HomePage({ onRequireLogin }: HomeProps) {
  const [deals, setDeals] = useState<Deal[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const observerRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    const loadDeals = async () => {
      if (loading || !hasMore) return
      setLoading(true)
      try {
        const newDeals = await getDeals(page)
        if (newDeals.length === 0) {
          setHasMore(false)
        } else {
          setDeals((prev) => {
            const existingIds = new Set(prev.map((d) => d.id))
            const filtered = newDeals.filter((d: Deal) => !existingIds.has(d.id))
            return [...prev, ...filtered]
          })
        }
      } catch (err: any) {
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }
    loadDeals()
  }, [page])

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

  if (error) return <p className="p-4 text-red-600">{error}</p>

  return (
    <MainLayout>
      <div className="max-w-[1400px] mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* SOL: 3/4 - Deal listesi */}
        <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 fırsatlar yüklendi.
            </p>
          )}
          <div ref={observerRef} className="h-8" />
        </div>

        {/* SAĞ: sidebar alanı */}
        <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>
    </MainLayout>
  )
}
