'use client';

import { useEffect, useState } from 'react';
import { createClient } from '@/lib/supabase/client';
import Link from 'next/link';
import { ChevronRight } from 'lucide-react';

interface Banner {
    id: string;
    title: string;
    image_url: string;
    link_target: string | null;
    cta_text: string;
}

export default function HeroBanner() {
    const [banner, setBanner] = useState<Banner | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchBanner = async () => {
            try {
                const supabase = createClient();
                const { data, error } = await supabase
                    .from('app_banners')
                    .select('*')
                    .eq('is_active', true)
                    .limit(1)
                    .maybeSingle();

                if (!error && data) {
                    setBanner(data);
                }
            } catch (err) {
                console.warn('[HeroBanner] Failed to fetch:', err);
            } finally {
                setIsLoading(false);
            }
        };

        fetchBanner();
    }, []);

    // Don't render if no active banner
    if (isLoading || !banner) {
        return null;
    }

    const content = (
        <div
            className="relative h-48 rounded-2xl overflow-hidden bg-zinc-900 group"
            style={{
                backgroundImage: `url(${banner.image_url})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
            }}
        >
            {/* Overlay gradient */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />

            {/* Content */}
            <div className="absolute bottom-0 left-0 right-0 p-4">
                <h3 className="text-lg font-bold text-white mb-1 line-clamp-2">
                    {banner.title}
                </h3>
                {banner.link_target && (
                    <div className="flex items-center gap-1 text-orange-500 text-xs font-bold uppercase tracking-wider">
                        {banner.cta_text}
                        <ChevronRight size={14} className="group-hover:translate-x-1 transition-transform" />
                    </div>
                )}
            </div>
        </div>
    );

    if (banner.link_target) {
        return (
            <Link href={banner.link_target} className="block">
                {content}
            </Link>
        );
    }

    return content;
}
