"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { ArrowLeft, ArrowRight, Radio } from "lucide-react";

type Featured = {
  title: string;
  slug: string;
  excerpt: string;
  coverImage?: string | null;
  category: { name: string };
};

export function FeaturedSlider({ articles }: { articles: Featured[] }) {
  const [index, setIndex] = useState(0);
  const current = articles[index] || articles[0];

  useEffect(() => {
    if (articles.length < 2) return;
    const timer = window.setInterval(() => setIndex((value) => (value + 1) % articles.length), 5500);
    return () => window.clearInterval(timer);
  }, [articles.length]);

  if (!current) return null;

  return (
    <div className="glass relative overflow-hidden rounded-lg">
      <div className="relative min-h-[430px]">
        {current.coverImage && (
          <Image src={current.coverImage} alt={current.title} fill priority sizes="100vw" className="object-cover opacity-64" />
        )}
        <div className="absolute inset-0 bg-gradient-to-r from-ink via-ink/75 to-transparent" />
        <div className="relative z-10 flex min-h-[430px] max-w-3xl flex-col justify-end p-6 sm:p-10">
          <span className="mb-5 inline-flex w-fit items-center gap-2 rounded-full border border-cyanx/35 bg-cyanx/10 px-3 py-1 text-xs font-bold uppercase tracking-[.18em] text-cyanx">
            <Radio size={14} /> Featured Signal
          </span>
          <h1 className="font-display text-4xl font-black leading-[1.05] text-white sm:text-6xl">{current.title}</h1>
          <p className="mt-5 max-w-2xl text-base leading-7 text-white/72 sm:text-lg">{current.excerpt}</p>
          <div className="mt-8 flex flex-wrap items-center gap-3">
            <Link href={`/article/${current.slug}`} className="rounded-full bg-cyanx px-5 py-3 text-sm font-black text-ink hover:bg-white">Read briefing</Link>
            <Link href="/trending" className="rounded-full border border-white/15 px-5 py-3 text-sm font-semibold text-white hover:border-cyanx hover:text-cyanx">Trending topics</Link>
          </div>
        </div>
      </div>
      {articles.length > 1 && (
        <div className="absolute bottom-6 right-6 flex gap-2">
          <button className="rounded-full bg-ink/70 p-3 text-white backdrop-blur hover:text-cyanx" onClick={() => setIndex((index - 1 + articles.length) % articles.length)} aria-label="Previous">
            <ArrowLeft size={18} />
          </button>
          <button className="rounded-full bg-ink/70 p-3 text-white backdrop-blur hover:text-cyanx" onClick={() => setIndex((index + 1) % articles.length)} aria-label="Next">
            <ArrowRight size={18} />
          </button>
        </div>
      )}
    </div>
  );
}
