'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Video, ShoppingBag, Users, TrendingUp, Clock, ChevronRight, Play } from 'lucide-react';

// ── TYPES ──

interface Stream {
  id: string;
  youtubeVideoId: string;
  sellerName: string;
  sellerAvatar: string;
  title: string;
  category: string;
  isLive: boolean;
  scheduledAt?: string;
  viewerCount: number;
  purchaseCount: number;
  thumbnailUrl: string;
}

interface Category {
  id: string;
  name: string;
  slug: string;
  imageUrl: string;
}

// ── MOCK DATA ──

const FEATURED_STREAM: Stream = {
  id: 'stream-001',
  youtubeVideoId: 'LIVE_VIDEO_ID',
  sellerName: 'Sophia Beauty',
  sellerAvatar: '/images/avatars/sophia.jpg',
  title: 'Summer Glow Makeup Collection',
  category: 'Makeup',
  isLive: true,
  viewerCount: 1247,
  purchaseCount: 42,
  thumbnailUrl: '/images/streams/sophia-live.jpg',
};

const LIVE_STREAMS: Stream[] = [
  {
    id: 'stream-002',
    youtubeVideoId: 'VIDEO_2',
    sellerName: 'Luxe Skin',
    sellerAvatar: '/images/avatars/luxe.jpg',
    title: 'Anti-Aging Secrets',
    category: 'Skin Care',
    isLive: true,
    viewerCount: 892,
    purchaseCount: 15,
    thumbnailUrl: '/images/streams/luxe-live.jpg',
  },
  {
    id: 'stream-003',
    youtubeVideoId: 'VIDEO_3',
    sellerName: 'Fragrance House',
    sellerAvatar: '/images/avatars/fragrance.jpg',
    title: 'New Summer Scents',
    category: 'Perfumes',
    isLive: true,
    viewerCount: 2156,
    purchaseCount: 38,
    thumbnailUrl: '/images/streams/fragrance-live.jpg',
  },
  {
    id: 'stream-004',
    youtubeVideoId: 'VIDEO_4',
    sellerName: 'Pure Hygiene',
    sellerAvatar: '/images/avatars/pure.jpg',
    title: 'Organic Sanitary Products',
    category: 'Sanitary Hygiene',
    isLive: true,
    viewerCount: 567,
    purchaseCount: 22,
    thumbnailUrl: '/images/streams/pure-live.jpg',
  },
];

const UPCOMING_STREAMS: Stream[] = [
  {
    id: 'stream-005',
    youtubeVideoId: '',
    sellerName: 'Glam Closet',
    sellerAvatar: '/images/avatars/glam.jpg',
    title: 'Summer Dress Collection',
    category: 'Clothing',
    isLive: false,
    scheduledAt: '2026-07-18T14:00:00Z',
    viewerCount: 0,
    purchaseCount: 0,
    thumbnailUrl: '/images/streams/glam-upcoming.jpg',
  },
  {
    id: 'stream-006',
    youtubeVideoId: '',
    sellerName: 'Bath Essentials',
    sellerAvatar: '/images/avatars/bath.jpg',
    title: 'Luxury Bath Bombs & Oils',
    category: 'Toiletries',
    isLive: false,
    scheduledAt: '2026-07-18T15:30:00Z',
    viewerCount: 0,
    purchaseCount: 0,
    thumbnailUrl: '/images/streams/bath-upcoming.jpg',
  },
  {
    id: 'stream-007',
    youtubeVideoId: '',
    sellerName: 'Beauty Tools Pro',
    sellerAvatar: '/images/avatars/tools.jpg',
    title: 'Professional Brush Sets',
    category: 'Beauty Industry',
    isLive: false,
    scheduledAt: '2026-07-18T17:00:00Z',
    viewerCount: 0,
    purchaseCount: 0,
    thumbnailUrl: '/images/streams/tools-upcoming.jpg',
  },
  {
    id: 'stream-008',
    youtubeVideoId: '',
    sellerName: 'Glow Up',
    sellerAvatar: '/images/avatars/glow.jpg',
    title: 'Vitamin C Serum Launch',
    category: 'Skin Care',
    isLive: false,
    scheduledAt: '2026-07-18T19:00:00Z',
    viewerCount: 0,
    purchaseCount: 0,
    thumbnailUrl: '/images/streams/glow-upcoming.jpg',
  },
];

const CATEGORIES: Category[] = [
  { id: 'cat-1', name: 'Makeup', slug: 'makeup', imageUrl: '/images/categories/makeup.jpg' },
  { id: 'cat-2', name: 'Skin Care', slug: 'skincare', imageUrl: '/images/categories/skincare.jpg' },
  { id: 'cat-3', name: 'Perfumes', slug: 'perfumes', imageUrl: '/images/categories/perfumes.jpg' },
  { id: 'cat-4', name: 'Toiletries', slug: 'toiletries', imageUrl: '/images/categories/toiletries.jpg' },
  { id: 'cat-5', name: 'Sanitary Hygiene', slug: 'sanitary-hygiene', imageUrl: '/images/categories/sanitary-hygiene.jpg' },
  { id: 'cat-6', name: 'Clothing', slug: 'clothing', imageUrl: '/images/categories/clothing.jpg' },
  { id: 'cat-7', name: 'Beauty Industry', slug: 'beauty-industry', imageUrl: '/images/categories/beauty-industry.jpg' },
];

// ── HELPERS ──

function formatViewerCount(count: number): string {
  if (count >= 1000) return `${(count / 1000).toFixed(1)}K`;
  return count.toString();
}

function formatTimeUntil(dateString?: string): string {
  if (!dateString) return 'Starting soon';
  const now = new Date();
  const scheduled = new Date(dateString);
  const diffMs = scheduled.getTime() - now.getTime();
  if (diffMs <= 0) return 'Starting now';
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours > 0) return `Starts in ${diffHours}h ${diffMins % 60}m`;
  return `Starts in ${diffMins}m`;
}

// ── COMPONENTS ──

function LiveBadge() {
  return (
    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-red-500 rounded-md">
      <span className="w-2 h-2 bg-white rounded-full animate-pulse" />
      <span className="text-white text-xs font-bold tracking-wider">LIVE</span>
    </span>
  );
}

function HeroSection({ featured }: { featured: Stream }) {
  return (
    <section className="relative w-full min-h-[600px] flex items-center overflow-hidden">
      {/* Background Image */}
      <div
        className="absolute inset-0 bg-cover bg-center bg-no-repeat"
        style={{ backgroundImage: 'url(/images/hero-bg.jpg)' }}
      />
      {/* Overlay */}
      <div className="absolute inset-0 bg-gradient-to-br from-pink-300/55 via-pink-400/40 to-pink-600/30" />

      <div className="relative z-10 w-full max-w-7xl mx-auto px-6 flex items-center justify-between gap-12">
        {/* Left: Text */}
        <div className="flex-1 max-w-xl">
          <span className="inline-block px-4 py-1.5 bg-primary-400 text-white text-xs font-bold tracking-widest uppercase rounded-full mb-5">
            Live Beauty Deals
          </span>
          <h1 className="text-5xl font-extrabold text-white leading-tight mb-4">
            Discover Beauty<br />
            <span className="text-secondary-400">Live</span>
          </h1>
          <p className="text-lg text-white/95 leading-relaxed mb-8">
            Watch live streams from top beauty sellers. Shop exclusive deals on makeup, skincare, perfumes, and more — all in real time.
          </p>
          <div className="flex gap-4 flex-wrap">
            <Link
              href="/live"
              className="inline-flex items-center gap-2 px-8 py-3.5 bg-primary-400 text-white font-bold rounded-full shadow-lg shadow-primary-400/40 hover:bg-primary-500 hover:-translate-y-0.5 transition-all"
            >
              <span className="w-2 h-2 bg-green-400 rounded-full animate-pulse" />
              Browse Live Streams
            </Link>
            <Link
              href="/products"
              className="inline-flex items-center px-8 py-3.5 bg-white/20 text-white font-semibold rounded-full border border-white/30 backdrop-blur-sm hover:bg-white/30 transition-all"
            >
              Shop Products
            </Link>
          </div>
          <div className="flex gap-8 mt-10">
            <div><div className="text-3xl font-extrabold text-white">500+</div><div className="text-sm text-white/80">Live Sellers</div></div>
            <div><div className="text-3xl font-extrabold text-white">50K+</div><div className="text-sm text-white/80">Daily Viewers</div></div>
            <div><div className="text-3xl font-extrabold text-white">10K+</div><div className="text-sm text-white/80">Products</div></div>
          </div>
        </div>

        {/* Right: Featured Stream Card */}
        <div className="flex-shrink-0 w-80 hidden lg:block">
          <div className="bg-white rounded-2xl overflow-hidden shadow-2xl">
            <div className="relative">
              <div className="absolute top-3 left-3 z-10"><LiveBadge /></div>
              <div className="relative w-full pb-[177.78%] bg-gray-900">
                <img src={featured.thumbnailUrl} alt={featured.title} className="absolute inset-0 w-full h-full object-cover" />
                <div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/70 to-transparent flex gap-4">
                  <span className="text-white text-sm flex items-center gap-1"><Users size={14} /> {formatViewerCount(featured.viewerCount)}</span>
                  <span className="text-secondary-400 text-sm flex items-center gap-1"><ShoppingBag size={14} /> {featured.purchaseCount} sold</span>
                </div>
              </div>
            </div>
            <div className="p-4">
              <div className="flex items-center gap-2.5 mb-2">
                <img src={featured.sellerAvatar} alt={featured.sellerName} className="w-8 h-8 rounded-full object-cover border-2 border-primary-400" />
                <span className="text-sm font-semibold text-gray-700">{featured.sellerName}</span>
              </div>
              <h3 className="text-sm font-bold text-gray-900 mb-3 leading-snug">{featured.title}</h3>
              <Link href={`/live/${featured.id}`} className="block w-full py-3 bg-primary-400 text-white text-center text-sm font-bold rounded-xl hover:bg-primary-500 transition-all">
                Watch Live
              </Link>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function StreamCard({ stream }: { stream: Stream }) {
  return (
    <div className="flex-shrink-0 w-56">
      <Link href={`/live/${stream.id}`} className="block group">
        <div className="relative w-full pb-[177.78%] rounded-2xl overflow-hidden bg-gray-900 mb-3">
          <img
            src={stream.thumbnailUrl}
            alt={stream.title}
            className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
          />
          {stream.isLive && (
            <div className="absolute top-2.5 left-2.5">
              <LiveBadge />
            </div>
          )}
          {!stream.isLive && stream.scheduledAt && (
            <div className="absolute top-2.5 left-2.5 px-2 py-1 bg-black/70 rounded-md">
              <span className="text-secondary-400 text-xs font-semibold flex items-center gap-1"><Clock size={12} /> {formatTimeUntil(stream.scheduledAt)}</span>
            </div>
          )}
          <div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/60 to-transparent flex gap-3">
            <span className="text-white text-xs flex items-center gap-1"><Users size={12} /> {formatViewerCount(stream.viewerCount)}</span>
            <span className="text-secondary-400 text-xs flex items-center gap-1"><ShoppingBag size={12} /> {stream.purchaseCount}</span>
          </div>
        </div>
        <h3 className="text-sm font-bold text-beauty-dark mb-1 leading-snug">{stream.title}</h3>
        <div className="flex items-center gap-1.5">
          <img src={stream.sellerAvatar} alt={stream.sellerName} className="w-5 h-5 rounded-full object-cover" />
          <span className="text-xs text-beauty-muted">{stream.sellerName}</span>
        </div>
      </Link>
    </div>
  );
}

function LiveStreamsSection({ streams }: { streams: Stream[] }) {
  const scrollRef = React.useRef<HTMLDivElement>(null);
  const scroll = (dir: 'left' | 'right') => {
    if (scrollRef.current) scrollRef.current.scrollBy({ left: dir === 'left' ? -300 : 300, behavior: 'smooth' });
  };

  return (
    <section className="py-12 bg-beauty-light">
      <div className="max-w-7xl mx-auto px-6">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <h2 className="text-2xl font-extrabold text-beauty-dark">Live Now</h2>
            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-red-500 text-white text-xs font-bold rounded">
              <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse" />
              {streams.length} LIVE
            </span>
          </div>
          <div className="flex gap-2">
            <button onClick={() => scroll('left')} className="w-9 h-9 rounded-full border border-gray-200 bg-white flex items-center justify-center hover:bg-gray-50 transition-colors">←</button>
            <button onClick={() => scroll('right')} className="w-9 h-9 rounded-full border border-gray-200 bg-white flex items-center justify-center hover:bg-gray-50 transition-colors">→</button>
          </div>
        </div>
        <div ref={scrollRef} className="flex gap-5 overflow-x-auto pb-3 snap-x snap-mandatory scrollbar-hide" style={{ scrollbarWidth: 'none' }}>
          {streams.map(s => <StreamCard key={s.id} stream={s} />)}
        </div>
      </div>
    </section>
  );
}

function UpcomingCard({ stream }: { stream: Stream }) {
  return (
    <div className="bg-beauty-light rounded-2xl overflow-hidden hover:-translate-y-1 hover:shadow-lg hover:shadow-primary-400/15 transition-all duration-200">
      <div className="relative w-full pb-[56.25%] bg-gray-900">
        <img src={stream.thumbnailUrl} alt={stream.title} className="absolute inset-0 w-full h-full object-cover" />
        <div className="absolute top-3 left-3 px-3 py-1.5 bg-black/70 rounded-lg">
          <span className="text-secondary-400 text-xs font-bold flex items-center gap-1"><Clock size={12} /> {formatTimeUntil(stream.scheduledAt)}</span>
        </div>
      </div>
      <div className="p-4">
        <span className="inline-block px-2 py-0.5 bg-primary-400 text-white text-xs font-semibold rounded mb-2">{stream.category}</span>
        <h3 className="text-sm font-bold text-beauty-dark mb-2 leading-snug">{stream.title}</h3>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <img src={stream.sellerAvatar} alt={stream.sellerName} className="w-7 h-7 rounded-full object-cover" />
            <span className="text-sm font-semibold text-gray-700">{stream.sellerName}</span>
          </div>
          <button className="px-3.5 py-1.5 text-primary-400 text-xs font-bold border-2 border-primary-400 rounded-full hover:bg-primary-400 hover:text-white transition-all">
            Remind Me
          </button>
        </div>
      </div>
    </div>
  );
}

function UpcomingSection({ streams }: { streams: Stream[] }) {
  return (
    <section className="py-12 bg-white">
      <div className="max-w-7xl mx-auto px-6">
        <h2 className="text-2xl font-extrabold text-beauty-dark mb-6">Coming Up</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {streams.map(s => <UpcomingCard key={s.id} stream={s} />)}
        </div>
      </div>
    </section>
  );
}

function CategoriesSection({ categories }: { categories: Category[] }) {
  return (
    <section className="py-12 bg-beauty-light">
      <div className="max-w-7xl mx-auto px-6">
        <h2 className="text-2xl font-extrabold text-beauty-dark mb-6 text-center">Shop by Category</h2>
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-5">
          {categories.map(cat => (
            <Link key={cat.id} href={`/products/${cat.slug}`} className="group">
              <div className="relative aspect-square rounded-2xl overflow-hidden hover:scale-105 transition-transform duration-200">
                <img src={cat.imageUrl} alt={cat.name} className="w-full h-full object-cover" />
                <div className="absolute inset-0 bg-gradient-to-t from-beauty-dark/80 via-transparent to-transparent flex items-end justify-center p-3">
                  <span className="text-white text-sm font-bold text-center">{cat.name}</span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}

function EmptyState({ nextStream }: { nextStream?: Stream }) {
  return (
    <div className="text-center py-16">
      <div className="text-6xl mb-4">📺</div>
      <h3 className="text-xl font-bold text-beauty-dark mb-2">No one is live right now</h3>
      <p className="text-beauty-muted mb-6">Check out upcoming streams or browse products in the meantime.</p>
      {nextStream && (
        <div className="bg-white rounded-2xl p-5 max-w-md mx-auto shadow-lg">
          <p className="text-xs text-beauty-muted mb-2">Next live stream</p>
          <h4 className="text-base font-bold text-beauty-dark mb-1">{nextStream.title}</h4>
          <p className="text-primary-400 font-semibold text-sm">{formatTimeUntil(nextStream.scheduledAt)}</p>
        </div>
      )}
    </div>
  );
}

// ── MAIN PAGE ──

export default function LandingPage() {
  const [isLoading, setIsLoading] = useState(true);
  const [liveStreams, setLiveStreams] = useState<Stream[]>([]);
  const [upcomingStreams, setUpcomingStreams] = useState<Stream[]>([]);
  const [featuredStream, setFeaturedStream] = useState<Stream | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      // Simulate API fetch
      setTimeout(() => {
        setLiveStreams(LIVE_STREAMS);
        setUpcomingStreams(UPCOMING_STREAMS);
        setFeaturedStream(FEATURED_STREAM);
        setIsLoading(false);
      }, 600);
    };
    fetchData();
  }, []);

  if (isLoading) {
    return (
      <main className="min-h-screen bg-beauty-light">
        <div className="w-full h-[600px] bg-gradient-to-br from-pink-200 via-pink-300 to-pink-500 animate-pulse" />
        <div className="max-w-7xl mx-auto px-6 py-12">
          <div className="h-8 w-48 bg-gray-200 rounded-lg mb-6 animate-pulse" />
          <div className="flex gap-5">
            {[1, 2, 3, 4].map(i => (
              <div key={i} className="flex-shrink-0 w-56 h-96 bg-gray-200 rounded-2xl animate-pulse" style={{ animationDelay: `${i * 0.1}s` }} />
            ))}
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-white">
      {featuredStream && <HeroSection featured={featuredStream} />}

      {liveStreams.length > 0 ? (
        <LiveStreamsSection streams={liveStreams} />
      ) : (
        <div className="bg-beauty-light py-12">
          <div className="max-w-7xl mx-auto px-6">
            <EmptyState nextStream={upcomingStreams.length > 0 ? upcomingStreams[0] : undefined} />
          </div>
        </div>
      )}

      {upcomingStreams.length > 0 && <UpcomingSection streams={upcomingStreams} />}
      <CategoriesSection categories={CATEGORIES} />
    </main>
  );
}