"use client";
import { FALLBACK_IMAGE } from "@/config/constants";
import { useState, useEffect } from 'react';
import Link from 'next/link';

export default function HeroSlider({ facilities }: { facilities: any[] }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [sliderItems, setSliderItems] = useState<any[]>([]);

  useEffect(() => {
    if (!Array.isArray(facilities)) return;

    const filtered = facilities.filter(f => {
      // Robust status-sjekk
      const statuses = Array.isArray(f.course_statuses) ? f.course_statuses : [];
      const interesting = ['aapen', 'aapen_med_vintergreener', 'aapner_snart', 'stenger_snart', 'stengt'];
      const hasStatus = statuses.some((s: any) => s && s.status && interesting.includes(s.status));
      
      // Bilde-sjekk
      const img = f.front_image_url || f.image_url || "";
      const isReal = img && !img.includes('Toppbilde-standard.jpg') && String(img).startsWith('http');
      
      return hasStatus && isReal;
    });

    setSliderItems(filtered.sort(() => 0.5 - Math.random()).slice(0, 5));
  }, [facilities]);

  useEffect(() => {
    if (sliderItems.length <= 1) return;
    const t = setInterval(() => setCurrentIndex(p => (p + 1) % sliderItems.length), 6000);
    return () => clearInterval(t);
  }, [sliderItems]);

  if (sliderItems.length === 0) return null;

  return (
    <div className="relative h-[55vh] md:h-[65vh] w-full bg-[#11280f] overflow-hidden">
      {sliderItems.map((f, i) => (
        <div key={f.id} className={`absolute inset-0 transition-opacity duration-1000 ${i === currentIndex ? 'opacity-100 z-10' : 'opacity-0 z-0'}`}>
          <div className="absolute inset-0 bg-black/40 z-10" />
          <img src={f.front_image_url || f.image_url} alt={f.name} className="w-full h-full object-cover" />
          <div className="absolute inset-0 z-20 flex flex-col items-center justify-center text-center px-4">
            <h1 className="text-4xl md:text-7xl font-black text-white mb-2 drop-shadow-2xl">{f.name}</h1>
            <p className="text-sm md:text-lg text-white/90 mb-8 uppercase tracking-widest font-bold">{f.city} • {f.county}</p>
            <Link href={`/golfbaner/${f.slug}`} className="bg-[#7ca982] text-white px-10 py-4 rounded-2xl font-black uppercase text-xs tracking-widest hover:bg-[#5b8260] transition-all shadow-2xl">Se golfanlegget</Link>
          </div>
        </div>
      ))}
    </div>
  );
}
