'use client';

import { useEffect, useState, useRef } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import api from '@/lib/axios';
import { useAuthStore } from '@/store/auth';
import {
  Gift, ChevronRight, Sparkles, Star, Phone, CheckCircle2, LogOut, User, X, Calendar,
} from 'lucide-react';
import { formatDate, formatPromoPeriod, formatPromoEnd } from '@/lib/dateUtils';

interface ContentData {
  settings: Record<string, string>;
  products: { id: number; name: string; price: number; image_url: string }[];
  promotions: {
    id: number; name: string; description: string;
    reward_method: string; start_date: string; end_date: string;
    start_time: string | null; end_time: string | null;
    start_datetime: string | null; end_datetime: string | null;
    banner_image: string | null;
  }[];
}

function formatPrice(price: number) {
  return 'Rp ' + Number(price).toLocaleString('id-ID');
}

const methodLabel: Record<string, string> = {
  hadiah_langsung: 'Hadiah Langsung',
  undian: 'Undian',
  point_reward: 'Point Reward',
};
const methodColor: Record<string, string> = {
  hadiah_langsung: 'bg-green-100 text-green-700',
  undian: 'bg-purple-100 text-purple-700',
  point_reward: 'bg-blue-100 text-blue-700',
};

export default function LandingPage() {
  const [data, setData] = useState<ContentData | null>(null);
  const [loading, setLoading] = useState(true);
  const [productPage, setProductPage] = useState(0);
  const PRODUCTS_PER_PAGE = 4;
  const router = useRouter();
  const [loggedUser, setLoggedUser] = useState<{ full_name: string } | null>(null);
  const [selectedPromo, setSelectedPromo] = useState<ContentData['promotions'][0] | null>(null);
  const [showHowTo, setShowHowTo] = useState(false);

  useEffect(() => {
    // Hydrate auth state
    useAuthStore.getState().hydrate();
    const { token, user } = useAuthStore.getState();
    if (token && user) {
      setLoggedUser(user);
    }

    // Capture ?outlet= param and persist for claim page
    const params = new URLSearchParams(window.location.search);
    const outletCode = params.get('outlet');
    if (outletCode) {
      sessionStorage.setItem('outlet_code', outletCode);
      sessionStorage.setItem('outlet_from_url', '1');
    }

    api.get('/content')
      .then((r) => setData(r.data.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleLogout = async () => {
    try { await api.post('/end-user/logout'); } catch {}
    useAuthStore.getState().clearAuth();
    setLoggedUser(null);
  };

  const s = data?.settings ?? {};
  const products = data?.products ?? [];
  const totalPages = Math.ceil(products.length / PRODUCTS_PER_PAGE);
  const visibleProducts = products.slice(productPage * PRODUCTS_PER_PAGE, (productPage + 1) * PRODUCTS_PER_PAGE);
  const siteName = s.site_name || 'Bonus-MU';
  const ctaHref = loggedUser ? '/dashboard/claim' : '/register';
  const handleCtaClick = (e: React.MouseEvent) => {
    e.preventDefault();
    setShowHowTo(true);
  };

  const steps = [
    {
      step: '01', icon: '📝',
      title: s.howto_step1_title || 'Daftar Akun',
      desc: s.howto_step1_desc || 'Buat akun dengan data diri Anda yang valid',
    },
    {
      step: '02', icon: '📱',
      title: s.howto_step2_title || 'Input Device',
      desc: s.howto_step2_desc || 'Masukkan IMEI dan detail handphone Samsung Anda',
    },
    {
      step: '03', icon: '🎁',
      title: s.howto_step3_title || 'Terima Reward',
      desc: s.howto_step3_desc || 'Voucher reward akan dikirim ke email Anda',
    },
  ];

  const rewardBullets = [
    s.reward_bullet_1 || 'Proses klaim mudah dan cepat',
    s.reward_bullet_2 || 'Voucher berlaku di seluruh merchant partner',
    s.reward_bullet_3 || 'Bonus tambahan untuk member setia',
  ].filter(Boolean);

  const rewardSubtitle = s.reward_subtitle || 'Daftarkan pembelian handphone Samsung Anda dan dapatkan voucher reward menarik!';

  return (
    <div className="min-h-screen gradient-bmu-light">

      {/* ── How To Modal ── */}
      {showHowTo && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4" onClick={() => setShowHowTo(false)}>
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-lg p-8 relative" onClick={e => e.stopPropagation()}>
            <button onClick={() => setShowHowTo(false)}
              className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none">✕</button>

            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-1">
                {s.howto_title || 'Cara Klaim Reward'}
              </h2>
              <p className="text-sm text-gray-500">
                {s.howto_subtitle || 'Ikuti 3 langkah mudah untuk mendapatkan reward Anda'}
              </p>
            </div>

            <div className="space-y-4 mb-8">
              {steps.map((item, index) => (
                <div key={item.step} className="flex items-start gap-4">
                  <div className="flex-shrink-0 w-10 h-10 rounded-full gradient-bmu text-white text-sm font-bold flex items-center justify-center">
                    {item.step}
                  </div>
                  <div className="flex-1 pt-1">
                    <div className="flex items-center gap-2 mb-0.5">
                      <span className="text-xl">{item.icon}</span>
                      <h3 className="font-semibold text-gray-900">{item.title}</h3>
                    </div>
                    <p className="text-sm text-gray-500">{item.desc}</p>
                  </div>
                  {index < steps.length - 1 && (
                    <div className="absolute left-9 mt-10 w-0.5 h-4 bg-gray-200" />
                  )}
                </div>
              ))}
            </div>

            <Link href={ctaHref} onClick={() => setShowHowTo(false)}
              className="flex items-center justify-center gap-2 w-full gradient-bmu text-white font-bold py-3.5 rounded-xl shadow-bmu hover:opacity-90 transition">
              <Gift className="h-5 w-5" />
              {s.hero_cta_text || 'Klaim Reward Sekarang'}
              <ChevronRight className="h-5 w-5" />
            </Link>
          </div>
        </div>
      )}

      {/* ── Header ── */}
      <header className="sticky top-0 z-50 glass-card">
        <div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 gradient-bmu rounded-lg flex items-center justify-center">
              <Gift className="w-5 h-5 text-white" />
            </div>
            <span className="text-xl font-bold text-gradient-bmu">{siteName}</span>
          </div>
          {loggedUser ? (
            <div className="flex items-center gap-2">
              <Link
                href="/dashboard"
                className="flex items-center gap-1.5 px-4 py-2 text-sm font-semibold text-sky-700 hover:bg-sky-50 rounded-lg transition"
              >
                <User className="w-4 h-4" />
                {loggedUser.full_name}
              </Link>
              <button
                onClick={handleLogout}
                className="flex items-center gap-1.5 px-4 py-2 text-sm font-semibold text-red-500 hover:bg-red-50 rounded-lg transition"
              >
                <LogOut className="w-4 h-4" />
                Keluar
              </button>
            </div>
          ) : (
            <Link
              href="/login"
              className="px-5 py-2 text-sm font-semibold border-2 border-sky-600 text-sky-700 rounded-lg hover:bg-sky-50 transition"
            >
              Masuk
            </Link>
          )}
        </div>
      </header>

      {/* ── Hero ── */}
      <section className="relative overflow-hidden">
        <div className="max-w-6xl mx-auto px-4 py-12 md:py-20">
          <div className="grid gap-10 lg:grid-cols-2 lg:items-center">

            {/* Hero Content */}
            <div className="space-y-6 animate-slide-up order-last lg:order-first">
              <div className="inline-flex items-center gap-2 rounded-full bg-sky-100 px-4 py-2 text-sm font-semibold text-sky-700">
                <Sparkles className="h-4 w-4" />
                {s.hero_badge || 'Program Reward Eksklusif'}
              </div>
              <h1 className="text-4xl font-extrabold leading-tight tracking-tight md:text-5xl lg:text-6xl">
                <span className="text-gradient-bmu">
                  {s.hero_title || 'Dapatkan Reward Untuk Setiap Pembelian'}
                </span>
              </h1>
              <p className="max-w-lg text-lg text-gray-500">
                {s.hero_subtitle || 'Beli handphone Samsung terbaru, daftarkan device Anda, dan nikmati voucher reward menarik! Proses mudah dan cepat.'}
              </p>
              <div className="flex flex-col sm:flex-row gap-3">
                <Link
                  href={ctaHref}
                  onClick={handleCtaClick}
                  className="inline-flex items-center justify-center gap-2 px-7 py-3.5 gradient-bmu text-white font-bold rounded-xl shadow-bmu hover:opacity-90 transition group"
                >
                  <Gift className="h-5 w-5" />
                  {s.hero_cta_text || 'Klaim Reward Sekarang'}
                  <ChevronRight className="h-5 w-5 transition-transform group-hover:translate-x-1" />
                </Link>
              </div>
              <div className="flex flex-wrap items-center gap-6 pt-2 text-sm text-gray-500">
                <span className="flex items-center gap-1.5">
                  <Gift className="h-4 w-4 text-amber-400" />
                  {s.hero_stat_text || '10,000+ Rewards Diklaim'}
                </span>
                <span className="flex items-center gap-1.5">
                  <Star className="h-4 w-4 text-sky-600 fill-sky-600" />
                  {s.hero_partner_text || 'Official Samsung Partner'}
                </span>
              </div>
            </div>

            {/* Hero Image */}
            <div className="relative animate-fade-in flex justify-center order-first lg:order-last">
              <div className="relative max-w-md w-full">
                <div className="absolute -inset-4 rounded-3xl bg-gradient-to-r from-sky-300/30 to-blue-500/30 blur-2xl" />
                {s.hero_image ? (
                  <img
                    src={s.hero_image}
                    alt="Hero"
                    className="relative rounded-3xl shadow-bmu animate-float w-full object-cover"
                  />
                ) : (
                  <div className="relative rounded-3xl shadow-bmu animate-float bg-gradient-to-br from-sky-100 to-blue-200 h-72 flex items-center justify-center">
                    <Phone className="w-32 h-32 text-sky-400 opacity-60" />
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ── Products ── */}
      <section className="py-14 px-4 bg-white">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-10">
            <h2 className="text-3xl font-bold text-gray-900 mb-3">
              {s.products_title || 'Samsung Terbaru'}
            </h2>
            <p className="text-gray-500">
              {s.products_subtitle || 'Beli salah satu produk Samsung dan dapatkan reward menarik'}
            </p>
          </div>

          {loading ? (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-5">
              {[1, 2, 3, 4].map((i) => (
                <div key={i} className="bg-gray-100 rounded-2xl p-4 animate-pulse h-64" />
              ))}
            </div>
          ) : visibleProducts.length > 0 ? (
            <>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-5">
                {visibleProducts.map((p, index) => (
                  <div
                    key={p.id}
                    className="group relative overflow-hidden rounded-2xl bg-white border border-gray-100 shadow-sm hover:shadow-bmu hover:-translate-y-2 transition-all duration-300"
                    style={{ animationDelay: `${index * 100}ms` }}
                  >
                    <div className="bg-gradient-to-br from-sky-50 to-blue-50 h-44 flex items-center justify-center overflow-hidden">
                      {p.image_url
                        ? <img src={p.image_url} alt={p.name} className="h-full w-full object-cover" />
                        : <Phone className="h-16 w-16 text-sky-400" />
                      }
                    </div>
                    <div className="p-4">
                      <div className="inline-flex items-center gap-1 text-xs font-semibold text-sky-600 mb-2">
                        <Gift className="h-3 w-3" />
                        Reward tersedia
                      </div>
                      <h3 className="font-semibold text-gray-800 text-sm leading-tight">{p.name}</h3>
                      <p className="text-sky-700 font-bold text-sm mt-1">{formatPrice(p.price)}</p>
                    </div>
                  </div>
                ))}
              </div>
              {totalPages > 1 && (
                <div className="flex justify-center items-center gap-3 mt-8">
                  <button
                    onClick={() => setProductPage((prev) => Math.max(0, prev - 1))}
                    disabled={productPage === 0}
                    className="px-4 py-2 rounded-lg border border-gray-200 text-sm font-medium disabled:opacity-40 hover:bg-gray-50 transition"
                  >
                    ← Prev
                  </button>
                  <span className="text-sm text-gray-500">{productPage + 1} / {totalPages}</span>
                  <button
                    onClick={() => setProductPage((prev) => Math.min(totalPages - 1, prev + 1))}
                    disabled={productPage === totalPages - 1}
                    className="px-4 py-2 rounded-lg border border-gray-200 text-sm font-medium disabled:opacity-40 hover:bg-gray-50 transition"
                  >
                    Next →
                  </button>
                </div>
              )}
            </>
          ) : (
            /* Fallback static phones when no data */
            <div className="grid grid-cols-2 md:grid-cols-4 gap-5">
              {['Galaxy S25 Ultra', 'Galaxy S25+', 'Galaxy S25', 'Galaxy Z Fold6'].map((name, index) => (
                <div
                  key={name}
                  className="group relative overflow-hidden rounded-2xl bg-white border border-gray-100 shadow-sm hover:shadow-bmu hover:-translate-y-2 transition-all duration-300"
                >
                  <div className="bg-gradient-to-br from-sky-50 to-blue-50 h-44 flex items-center justify-center">
                    <Phone className="h-16 w-16 text-sky-400" />
                  </div>
                  <div className="p-4">
                    <div className="inline-flex items-center gap-1 text-xs font-semibold text-sky-600 mb-2">
                      <Gift className="h-3 w-3" />
                      Reward tersedia
                    </div>
                    <h3 className="font-semibold text-gray-800 text-sm">{name}</h3>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* ── Promotions ── */}
      {(data?.promotions ?? []).length > 0 && (
        <section className="py-14 px-4 bg-gradient-to-br from-sky-50 via-white to-blue-50">
          <div className="max-w-6xl mx-auto">
            <div className="text-center mb-10">
              <h2 className="text-3xl font-bold text-gray-900 mb-3">
                {s.promotions_title || 'Promo Aktif'}
              </h2>
              <p className="text-gray-500">
                {s.promotions_subtitle || 'Ikuti promo berikut dan dapatkan reward menarik'}
              </p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-5">
              {(data?.promotions ?? []).map((promo) => (
                <div
                  key={promo.id}
                  className="group rounded-2xl bg-white border border-gray-100 shadow-sm hover:shadow-bmu hover:-translate-y-1 transition-all duration-300 overflow-hidden cursor-pointer"
                  onClick={() => setSelectedPromo(promo)}
                >
                  <div className="bg-gradient-to-br from-sky-50 to-blue-100 aspect-square flex items-center justify-center overflow-hidden">
                    {promo.banner_image
                      ? <img src={promo.banner_image} alt={promo.name} className="h-full w-full object-cover" />
                      : <Gift className="h-14 w-14 text-sky-400 opacity-60" />
                    }
                  </div>
                  <div className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${methodColor[promo.reward_method] ?? 'bg-gray-100 text-gray-600'}`}>
                        {methodLabel[promo.reward_method] ?? promo.reward_method}
                      </span>
                      <span className="text-xs text-gray-400">
                        s/d {formatPromoEnd(promo.end_date, promo.end_datetime)}
                      </span>
                    </div>
                    <h3 className="font-semibold text-gray-800 text-sm leading-tight">{promo.name}</h3>
                    {promo.description && (
                      <p className="text-xs text-gray-500 mt-1 line-clamp-2">{promo.description}</p>
                    )}
                    <span className="mt-3 inline-flex items-center gap-1 text-xs font-semibold text-sky-600">
                      <Gift className="h-3 w-3" /> Lihat Detail
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ── Promo Detail Modal ── */}
      {selectedPromo && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4"
          onClick={() => setSelectedPromo(null)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="relative aspect-square bg-gradient-to-br from-sky-50 to-blue-100 flex items-center justify-center overflow-hidden">
              {selectedPromo.banner_image
                ? <img src={selectedPromo.banner_image} alt={selectedPromo.name} className="h-full w-full object-contain" />
                : <Gift className="h-20 w-20 text-sky-400 opacity-50" />
              }
              <button
                onClick={() => setSelectedPromo(null)}
                className="absolute top-3 right-3 bg-black/40 hover:bg-black/60 text-white rounded-full p-1.5 transition"
              >
                <X className="w-4 h-4" />
              </button>
              <span className={`absolute top-3 left-3 text-xs px-2.5 py-1 rounded-full font-semibold ${methodColor[selectedPromo.reward_method] ?? 'bg-gray-100 text-gray-600'}`}>
                {methodLabel[selectedPromo.reward_method] ?? selectedPromo.reward_method}
              </span>
            </div>
            <div className="p-5">
              <h2 className="text-lg font-bold text-gray-900 mb-2">{selectedPromo.name}</h2>
              <div className="flex items-center gap-1.5 text-xs text-gray-500 mb-3">
                <Calendar className="w-3.5 h-3.5" />
                {formatPromoPeriod(selectedPromo.start_date, selectedPromo.end_date, selectedPromo.start_datetime, selectedPromo.end_datetime)}
              </div>
              {selectedPromo.description && (
                <p className="text-sm text-gray-600 leading-relaxed mb-5">{selectedPromo.description}</p>
              )}
              <Link
                href={loggedUser ? `/dashboard/claim?promotion_id=${selectedPromo.id}` : `/register?promotion_id=${selectedPromo.id}`}
                className="w-full inline-flex items-center justify-center gap-2 gradient-bmu text-white font-bold py-3 rounded-xl hover:opacity-90 transition"
                onClick={() => setSelectedPromo(null)}
              >
                <Gift className="h-4 w-4" />
                Ikuti Promo
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* ── Reward Section — hidden ── */}
      {false && (
      <section className="py-14 px-4 bg-gradient-to-br from-sky-50 via-white to-violet-50">
        <div className="max-w-6xl mx-auto">
          <div className="grid gap-10 lg:grid-cols-2 lg:items-center">

            {/* Voucher Image */}
            <div className="relative order-2 lg:order-1 flex justify-center">
              <div className="absolute -inset-4 rounded-3xl gradient-reward opacity-10 blur-3xl" />
              {s.reward_image ? (
                <img
                  src={s.reward_image}
                  alt="Reward Voucher"
                  className="relative max-w-sm w-full rounded-3xl shadow-reward animate-float"
                />
              ) : (
                <div className="relative max-w-sm w-full rounded-3xl shadow-reward animate-float bg-gradient-to-br from-amber-100 to-orange-200 h-64 flex items-center justify-center">
                  <Gift className="w-24 h-24 text-amber-500 opacity-60" />
                </div>
              )}
            </div>

            {/* Reward Content */}
            <div className="space-y-6 order-1 lg:order-2">
              <div className="inline-flex items-center gap-2 rounded-full gradient-reward px-4 py-2 text-sm font-bold text-white">
                <Star className="h-4 w-4" />
                {s.reward_badge || 'Exclusive Rewards'}
              </div>
              <h2 className="text-3xl font-bold text-gray-900 md:text-4xl">
                {s.reward_title || 'Voucher Reward Menarik Menanti Anda!'}
              </h2>
              <p className="text-lg text-gray-500">
                {rewardSubtitle}
              </p>
              <ul className="space-y-3">
                {rewardBullets.map((b, i) => (
                  <li key={i} className="flex items-center gap-3">
                    <CheckCircle2 className="h-5 w-5 text-sky-600 flex-shrink-0" />
                    <span className="text-gray-700">{b}</span>
                  </li>
                ))}
              </ul>
              <Link
                href={ctaHref}
                onClick={handleCtaClick}
                className="inline-flex items-center gap-2 gradient-reward text-white font-bold px-6 py-3 rounded-xl shadow-reward hover:opacity-90 transition"
              >
                <Gift className="h-5 w-5" />
                {s.reward_cta_text || 'Klaim Sekarang'}
              </Link>
            </div>
          </div>
        </div>
      </section>
      )}

      {/* ── CTA Section ── */}
      <section className="py-14 px-4">
        <div className="max-w-6xl mx-auto">
          <div className="relative overflow-hidden rounded-3xl gradient-bmu p-10 md:p-16 text-center">
            <div className="absolute inset-0 opacity-10 bg-gradient-to-br from-white to-transparent" />
            <div className="relative">
              <Sparkles className="h-12 w-12 text-white/70 mx-auto mb-6" />
              <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">
                {s.cta_title || 'Siap Dapatkan Reward Anda?'}
              </h2>
              <p className="text-lg text-white/75 mb-8 max-w-xl mx-auto">
                {s.cta_subtitle || 'Jangan lewatkan kesempatan untuk mendapatkan voucher reward menarik dari pembelian handphone Samsung Anda!'}
              </p>
              <Link
                href={ctaHref}
                onClick={handleCtaClick}
                className="inline-flex items-center gap-2 bg-white/20 border border-white/30 text-white font-bold px-8 py-3.5 rounded-xl hover:bg-white/30 transition"
              >
                <Gift className="h-5 w-5" />
                {s.cta_button_text || 'Mulai Sekarang'}
                <ChevronRight className="h-5 w-5" />
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* ── Footer ── */}
      <footer className="border-t border-gray-100 bg-white py-8 px-4">
        <div className="max-w-6xl mx-auto flex flex-col items-center gap-3 md:flex-row md:justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 gradient-bmu rounded-lg flex items-center justify-center">
              <Gift className="w-4 h-4 text-white" />
            </div>
            <span className="font-semibold text-gray-800">{siteName}</span>
          </div>
          <p className="text-sm text-gray-400 text-center">
            {s.footer_copyright || `© ${new Date().getFullYear()} ${siteName}. All rights reserved. Official Samsung Partner.`}
          </p>
        </div>
      </footer>
    </div>
  );
}
