'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import StoreLayout from '@/components/layout/StoreLayout';
import ProductCard from '@/components/ui/ProductCard';
import { useLanguage } from '@/context/LanguageContext';
import { getCategories, getFlashDeals, getFeaturedProducts } from '@/lib/actions';
import styles from './Home.module.css';

function CountdownTimer({ target }: { target: Date }) {
  const [time, setTime] = useState({ h: 0, m: 0, s: 0 });
  const { t } = useLanguage();

  useEffect(() => {
    const calc = () => {
      const diff = Math.max(0, target.getTime() - Date.now());
      setTime({
        h: Math.floor(diff / 3600000),
        m: Math.floor((diff % 3600000) / 60000),
        s: Math.floor((diff % 60000) / 1000),
      });
    };
    calc();
    const id = setInterval(calc, 1000);
    return () => clearInterval(id);
  }, [target]);

  const pad = (n: number) => String(n).padStart(2, '0');

  return (
    <div className="countdown">
      <span className={styles.endsIn}>{t.deals.endsIn}:</span>
      <div className="countdown-unit"><span className="countdown-value">{pad(time.h)}</span><span className="countdown-label">{t.deals.hours}</span></div>
      <span className="countdown-sep">:</span>
      <div className="countdown-unit"><span className="countdown-value">{pad(time.m)}</span><span className="countdown-label">{t.deals.minutes}</span></div>
      <span className="countdown-sep">:</span>
      <div className="countdown-unit"><span className="countdown-value">{pad(time.s)}</span><span className="countdown-label">{t.deals.seconds}</span></div>
    </div>
  );
}

const dealEndTime = new Date(Date.now() + 6 * 3600 * 1000 + 24 * 60 * 1000);

const reviews = [
  { name: 'Ahmad Al-Rashidi', nameAr: 'أحمد الراشدي', text: 'Best tech store in Kuwait! Got my iPhone 15 Pro Max delivered the next day. Amazing service!', textAr: 'أفضل متجر تقنية في الكويت! استلمت آيفون 15 برو ماكس في اليوم التالي. خدمة رائعة!', stars: 5, product: 'iPhone 15 Pro Max' },
  { name: 'Sara Al-Mutairi', nameAr: 'سارة المطيري', text: 'Incredible prices and genuine products. The compare feature helped me choose the perfect phone!', textAr: 'أسعار لا تُصدق ومنتجات أصلية. ميزة المقارنة ساعدتني في اختيار الهاتف المثالي!', stars: 5, product: 'Samsung Galaxy S24 Ultra' },
  { name: 'Khalid Al-Hamdan', nameAr: 'خالد الحمدان', text: 'Super fast delivery and excellent packaging. Will definitely buy again from Fast Time Phone!', textAr: 'توصيل سريع جداً وتغليف ممتاز. سأشتري مجدداً بالتأكيد من فاست تايم فون!', stars: 5, product: 'AirPods Pro 2nd Gen' },
];

export default function HomePage() {
  const { t, language } = useLanguage();
  const [activeReview, setActiveReview] = useState(0);
  const [categories, setCategories] = useState<any[]>([]);
  const [flashDeals, setFlashDeals] = useState<any[]>([]);
  const [featuredProducts, setFeaturedProducts] = useState<any[]>([]);

  useEffect(() => {
    const fetchHomeData = async () => {
      const [cats, deals, feats] = await Promise.all([
        getCategories(),
        getFlashDeals(),
        getFeaturedProducts()
      ]);
      setCategories(cats);
      setFlashDeals(deals);
      setFeaturedProducts(feats);
    };
    fetchHomeData();
  }, []);

  useEffect(() => {
    const id = setInterval(() => setActiveReview(p => (p + 1) % reviews.length), 4000);
    return () => clearInterval(id);
  }, []);

  return (
    <StoreLayout>
      {/* ===== HERO ===== */}
      <section className={styles.hero}>
        <div className={styles.heroParticles}>
          {[...Array(20)].map((_, i) => (
            <span key={i} className={styles.particle} style={{
              left: `${Math.random() * 100}%`,
              animationDelay: `${Math.random() * 8}s`,
              animationDuration: `${6 + Math.random() * 8}s`,
              width: `${2 + Math.random() * 3}px`,
              height: `${2 + Math.random() * 3}px`,
            }} />
          ))}
        </div>
        <div className={`container ${styles.heroInner}`}>
          <div className={styles.heroContent}>
            <span className={`badge badge-blue ${styles.heroBadge}`}>⚡ {t.hero.badge}</span>
            <h1 className={styles.heroTitle}>
              {t.hero.title}<br />
              <span className={styles.heroHighlight}>{t.hero.titleHighlight}</span>
            </h1>
            <p className={styles.heroSubtitle}>{t.hero.subtitle}</p>
            <div className={styles.heroBtns}>
              <Link href="/products" className="btn btn-primary btn-lg">{t.hero.cta} →</Link>
              <Link href="/deals" className="btn btn-outline btn-lg">⚡ {t.hero.ctaDeals}</Link>
            </div>
            <div className={styles.heroStats}>
              <div className={styles.heroStat}><span className={styles.statNum}>500+</span><span className={styles.statLabel}>{language === 'ar' ? 'منتج' : 'Products'}</span></div>
              <div className={styles.heroDivider}></div>
              <div className={styles.heroStat}><span className={styles.statNum}>10K+</span><span className={styles.statLabel}>{language === 'ar' ? 'عميل سعيد' : 'Happy Customers'}</span></div>
              <div className={styles.heroDivider}></div>
              <div className={styles.heroStat}><span className={styles.statNum}>5★</span><span className={styles.statLabel}>{language === 'ar' ? 'تقييم' : 'Rating'}</span></div>
            </div>
          </div>
          <div className={styles.heroVisual}>
            <div className={styles.heroRing}></div>
            <div className={styles.heroRing2}></div>
            <div className={styles.logoWrap}>
              <Image src="/logo.png" alt="Fast Time Phone" width={200} height={200} className={styles.heroLogo} priority />
            </div>
          </div>
        </div>
      </section>

      {/* ===== BANNER ===== */}
      <div className={styles.bannerStrip}>
        <div className="container">
          <div className={styles.bannerItems}>
            <span>🌙 {t.banners.ramadan}</span>
            <span className={styles.bannerSep}>●</span>
            <span>🔥 {t.banners.weekend}</span>
            <span className={styles.bannerSep}>●</span>
            <span>🚚 {t.banners.delivery}</span>
          </div>
        </div>
      </div>

      {/* ===== CATEGORIES ===== */}
      <section className={styles.section}>
        <div className="container">
          <div className="section-header">
            <h2 className="section-title">{t.categories.title}</h2>
            <div className="section-line"></div>
          </div>
          <div className={styles.catGrid}>
            {categories.map(cat => (
              <Link key={cat.id} href={`/products?category=${cat.id}`} className={styles.catCard}>
                <span className={styles.catIcon}>{cat.icon}</span>
                <span className={styles.catName}>{language === 'ar' ? cat.nameAr : cat.name}</span>
                <span className={styles.catCount}>{cat.count} {language === 'ar' ? 'منتج' : 'items'}</span>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* ===== FLASH DEALS ===== */}
      <section className={`${styles.section} ${styles.dealsSection}`}>
        <div className="container">
          <div className={styles.dealsHeader}>
            <div>
              <h2 className="section-title" style={{ textAlign: 'left' }}>
                {t.deals.title}
              </h2>
              <p className="text-secondary" style={{ fontSize: '0.9rem' }}>{t.deals.subtitle}</p>
            </div>
            <CountdownTimer target={dealEndTime} />
          </div>
          <div className="products-grid">
            {flashDeals.map(p => <ProductCard key={p.id} product={p} />)}
          </div>
          <div style={{ textAlign: 'center', marginTop: '32px' }}>
            <Link href="/deals" className="btn btn-outline">{t.deals.viewAll}</Link>
          </div>
        </div>
      </section>

      {/* ===== FEATURED PRODUCTS ===== */}
      <section className={styles.section}>
        <div className="container">
          <div className="section-header">
            <h2 className="section-title">{language === 'ar' ? '⭐ المنتجات المميزة' : '⭐ Featured Products'}</h2>
            <div className="section-line"></div>
          </div>
          <div className="products-grid-wide">
            {featuredProducts.slice(0, 6).map(p => <ProductCard key={p.id} product={p} />)}
          </div>
          <div style={{ textAlign: 'center', marginTop: '32px' }}>
            <Link href="/products" className="btn btn-primary">{language === 'ar' ? 'عرض جميع المنتجات' : 'View All Products'} →</Link>
          </div>
        </div>
      </section>

      {/* ===== COMPARE CTA ===== */}
      <section className={styles.compareCta}>
        <div className="container">
          <div className={styles.compareCtaInner}>
            <div className={styles.compareCtaContent}>
              <h2 className={styles.compareCtaTitle}>
                {language === 'ar' ? 'قارن بين أفضل الهواتف' : 'Compare Top Phones'}
              </h2>
              <p className="text-secondary">
                {language === 'ar'
                  ? 'اختر حتى 4 هواتف وقارن مواصفاتها جنباً إلى جنب للحصول على أفضل قرار.'
                  : 'Pick up to 4 phones and compare their specs side by side to make the best decision.'}
              </p>
              <Link href="/compare" className="btn btn-orange btn-lg" style={{ marginTop: '20px' }}>
                ⚖️ {t.compare.title}
              </Link>
            </div>
            <div className={styles.compareCtaVisual}>
              <div className={styles.phoneStack}>
                {['📱', '📱', '📱'].map((e, i) => (
                  <div key={i} className={styles.phoneEmoji} style={{ animationDelay: `${i * 0.3}s` }}>{e}</div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ===== REVIEWS ===== */}
      <section className={styles.section}>
        <div className="container">
          <div className="section-header">
            <h2 className="section-title">💬 {t.reviews.title}</h2>
            <div className="section-line"></div>
          </div>
          <div className={styles.reviewsGrid}>
            {reviews.map((r, i) => (
              <div key={i} className={`${styles.reviewCard} ${i === activeReview ? styles.reviewActive : ''}`}>
                <div className={styles.reviewStars}>{'★'.repeat(r.stars)}</div>
                <p className={styles.reviewText}>{language === 'ar' ? r.textAr : r.text}</p>
                <div className={styles.reviewAuthor}>
                  <div className={styles.reviewAvatar}>{(language === 'ar' ? r.nameAr : r.name)[0]}</div>
                  <div>
                    <div className={styles.reviewName}>{language === 'ar' ? r.nameAr : r.name}</div>
                    <div className={styles.reviewProduct}>✓ {r.product}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ===== DELIVERY BANNER ===== */}
      <section className={styles.deliveryBanner}>
        <div className="container">
          <div className={styles.deliveryGrid}>
            {[
              { icon: '🚀', title: language === 'ar' ? 'توصيل سريع' : 'Fast Delivery', desc: language === 'ar' ? 'في جميع أنحاء الكويت' : 'All across Kuwait' },
              { icon: '🛡️', title: language === 'ar' ? 'ضمان رسمي' : 'Official Warranty', desc: language === 'ar' ? 'ضمان الشركة المصنّعة' : 'Manufacturer warranty' },
              { icon: '↩️', title: language === 'ar' ? 'إرجاع سهل' : 'Easy Returns', desc: language === 'ar' ? '7 أيام بدون أسئلة' : '7 days no questions' },
              { icon: '💳', title: language === 'ar' ? 'دفع آمن' : 'Secure Payment', desc: language === 'ar' ? 'KNET، فيزا، آبل باي' : 'KNET, Visa, Apple Pay' },
            ].map((item, i) => (
              <div key={i} className={styles.deliveryItem}>
                <span className={styles.deliveryIcon}>{item.icon}</span>
                <div>
                  <div className={styles.deliveryTitle}>{item.title}</div>
                  <div className={styles.deliveryDesc}>{item.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </StoreLayout>
  );
}
