"use client";

import {
  ArrowRight,
  BadgeCheck,
  Banknote,
  Box,
  Check,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  CircleUserRound,
  CreditCard,
  Gamepad2,
  Gift,
  Headphones,
  Heart,
  Home,
  Laptop,
  MapPin,
  Menu,
  Minus,
  PackageCheck,
  Plane,
  Plus,
  Refrigerator,
  Search,
  ShieldCheck,
  Shirt,
  ShoppingBag,
  ShoppingCart,
  Smartphone,
  Sparkles,
  Star,
  Store,
  Trash2,
  Truck,
  X,
  Zap,
} from "lucide-react";
import { FormEvent, useEffect, useMemo, useRef, useState } from "react";
import LanguageSwitcher from "@/components/language-switcher";
import { useTenant } from "@/components/tenant-provider";
import VoiceOtpPanel from "@/components/voice-otp-panel";
import { categories, products as catalogueProducts, type Product } from "@/lib/catalog";

type CartLine = Product & { quantity: number };
type CheckoutStep = "cart" | "details" | "payment" | "success";
type PlacedOrder = { orderNumber: string; trackingId: string; invoiceNumber?: string };
type CheckoutPayload = {
  customerName: string;
  email: string;
  phone: string;
  address: string;
  city: string;
  pincode: string;
  paymentMethod: "card" | "cod";
  items: Array<{ productId: string; quantity: number }>;
};

const categoryIcons: Record<string, React.ElementType> = {
  grocery: ShoppingBag,
  mobile: Smartphone,
  fashion: Shirt,
  electronics: Laptop,
  home: Home,
  appliances: Refrigerator,
  beauty: Sparkles,
  toys: Gamepad2,
  travel: Plane,
};

const heroImage =
  "https://images.pexels.com/photos/5868134/pexels-photo-5868134.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800";

export default function Storefront() {
  const { tenant, language, t, formatMoney } = useTenant();
  const [cart, setCart] = useState<CartLine[]>([]);
  const [query, setQuery] = useState("");
  const [activeCategory, setActiveCategory] = useState("All");
  const [cartOpen, setCartOpen] = useState(false);
  const [mobileMenu, setMobileMenu] = useState(false);
  const [step, setStep] = useState<CheckoutStep>("cart");
  const [paymentMethod, setPaymentMethod] = useState<"card" | "cod">("card");
  const [submitting, setSubmitting] = useState(false);
  const [placedOrder, setPlacedOrder] = useState<PlacedOrder | null>(null);
  const [notice, setNotice] = useState("");
  const [allProducts, setAllProducts] = useState<Product[]>(catalogueProducts);
  const [pendingOrder, setPendingOrder] = useState<CheckoutPayload | null>(null);
  const [otpOpen, setOtpOpen] = useState(false);
  const dealsRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const saved = window.localStorage.getItem(`cart:${tenant.slug}`);
    if (saved) {
      try {
        setCart(JSON.parse(saved) as CartLine[]);
      } catch {
        window.localStorage.removeItem(`cart:${tenant.slug}`);
      }
    }
  }, [tenant.slug]);

  useEffect(() => {
    window.localStorage.setItem(`cart:${tenant.slug}`, JSON.stringify(cart));
  }, [cart, tenant.slug]);

  useEffect(() => {
    async function loadMarketplaceProducts() {
      try {
        const response = await fetch("/api/products");
        const data = (await response.json()) as {
          products?: Array<{
            id: number;
            title: string;
            category: string;
            seller: string;
            price: string;
            originalPrice: string;
            image: string;
            rating: string;
          }>;
        };
        if (!data.products?.length) return;
        const vendorProducts: Product[] = data.products.map((product) => ({
          id: `db-${product.id}`,
          name: product.title,
          category: product.category,
          seller: product.seller,
          price: Number(product.price),
          originalPrice: Number(product.originalPrice),
          rating: Number(product.rating),
          reviews: "New",
          image: product.image,
          badge: "Marketplace",
          delivery: "In 3 days",
        }));
        setAllProducts([...vendorProducts, ...catalogueProducts]);
      } catch {
        // The curated catalogue remains available when vendor inventory is offline.
      }
    }
    void loadMarketplaceProducts();
  }, []);

  useEffect(() => {
    if (!notice) return;
    const timer = window.setTimeout(() => setNotice(""), 2500);
    return () => window.clearTimeout(timer);
  }, [notice]);

  const filteredProducts = useMemo(() => {
    const term = query.trim().toLowerCase();
    return allProducts.filter((product) => {
      const categoryMatch = activeCategory === "All" || product.category === activeCategory;
      const searchMatch =
        !term ||
        product.name.toLowerCase().includes(term) ||
        product.category.toLowerCase().includes(term) ||
        product.seller.toLowerCase().includes(term);
      return categoryMatch && searchMatch;
    });
  }, [query, activeCategory, allProducts]);

  const itemCount = cart.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const mrpTotal = cart.reduce((sum, item) => sum + item.originalPrice * item.quantity, 0);
  const discount = mrpTotal - subtotal;

  function showNotice(message: string) {
    setNotice(message);
  }

  function addToCart(product: Product) {
    setCart((current) => {
      const exists = current.find((item) => item.id === product.id);
      if (exists) {
        return current.map((item) =>
          item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item,
        );
      }
      return [...current, { ...product, quantity: 1 }];
    });
    showNotice(`${product.name} added to your cart`);
  }

  function updateQuantity(id: string, amount: number) {
    setCart((current) =>
      current
        .map((item) =>
          item.id === id ? { ...item, quantity: Math.max(0, item.quantity + amount) } : item,
        )
        .filter((item) => item.quantity > 0),
    );
  }

  function openCart() {
    setStep("cart");
    setCartOpen(true);
  }

  function selectCategory(name: string) {
    setActiveCategory(name === activeCategory ? "All" : name);
    requestAnimationFrame(() => dealsRef.current?.scrollIntoView({ behavior: "smooth" }));
  }

  function placeOrder(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const payload: CheckoutPayload = {
      customerName: String(form.get("customerName") ?? ""),
      email: String(form.get("email") ?? ""),
      phone: String(form.get("phone") ?? ""),
      address: String(form.get("address") ?? ""),
      city: String(form.get("city") ?? ""),
      pincode: String(form.get("pincode") ?? ""),
      paymentMethod,
      items: cart.map(({ id, quantity }) => ({ productId: id, quantity })),
    };
    setPendingOrder(payload);
    setOtpOpen(true);
  }

  async function submitVerifiedOrder(payload: CheckoutPayload, verificationToken: string) {
    setSubmitting(true);
    try {
      const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...payload, verificationToken }),
      });
      const data = (await response.json()) as PlacedOrder & { error?: string };
      if (!response.ok) throw new Error(data.error || "Order could not be placed");
      setPlacedOrder(data);
      setCart([]);
      setOtpOpen(false);
      setPendingOrder(null);
      setStep("success");
    } catch (reason) {
      showNotice(reason instanceof Error ? reason.message : "We could not place your order. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="min-h-screen bg-[#f4f6f8] text-[#16213c]">
      <div className="bg-[var(--navy)] px-4 py-2 text-center text-[11px] font-semibold tracking-wide text-white sm:text-xs">
        <span className="mr-2 inline-block rounded-full bg-[var(--sun)] px-2 py-0.5 text-[9px] font-black text-[var(--navy)]">
          NEW
        </span>
        {t("freeDeliveryBanner")}
        <a href="#deals" className="ml-3 border-b border-white/70">{t("shopNow")}</a>
      </div>

      <header className="sticky top-0 z-40 border-b border-slate-200 bg-white/95 shadow-[0_3px_14px_rgba(20,40,80,0.06)] backdrop-blur">
        <div className="mx-auto flex h-[70px] max-w-[1440px] items-center gap-4 px-4 sm:px-6 lg:gap-8 lg:px-10">
          <button
            className="rounded-lg p-2 text-[#123f94] lg:hidden"
            onClick={() => setMobileMenu((value) => !value)}
            aria-label="Open menu"
          >
            <Menu size={23} />
          </button>
          <a href="#top" className="flex shrink-0 items-center gap-2.5" aria-label={`${tenant.brandName} home`}>
            {tenant.logoUrl ? <img src={tenant.logoUrl} alt={tenant.brandName} className="h-10 max-w-36 object-contain" /> : <><span className="grid h-9 w-9 -rotate-3 place-items-center rounded-xl bg-[var(--brand)] text-xl font-black italic text-white shadow-lg">{tenant.brandName.charAt(0).toUpperCase()}</span><span><span className="block text-[22px] font-black leading-5 tracking-[-0.04em] text-[var(--brand)]">{tenant.brandName}</span><span className="ml-0.5 text-[8px] font-bold uppercase tracking-[0.18em] text-[var(--sun)]">{tenant.tagline}</span></span></>}
          </a>
          <div className="ml-auto sm:hidden"><LanguageSwitcher compact /></div>

          <form
            className="relative hidden max-w-2xl flex-1 md:block"
            onSubmit={(event) => {
              event.preventDefault();
              dealsRef.current?.scrollIntoView({ behavior: "smooth" });
            }}
          >
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-[#155ee9]" size={20} />
            <input
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              className="h-11 w-full rounded-xl border border-[#dae5f8] bg-[#f3f7ff] pl-12 pr-4 text-sm outline-none transition focus:border-[#155ee9] focus:bg-white focus:ring-4 focus:ring-blue-100"
              placeholder={t("search")}
              aria-label={t("search")}
            />
          </form>

          <nav className="ml-auto hidden items-center gap-5 text-sm font-semibold text-slate-700 lg:flex">
            <a href="/seller" className="flex items-center gap-2 whitespace-nowrap hover:text-[var(--brand)]"><Store size={18} /> {t("becomeSeller")}</a>
            <a href="/affiliate" className="whitespace-nowrap hover:text-[var(--brand)]">{t("affiliate")}</a>
            <a href="/track" className="whitespace-nowrap hover:text-[var(--brand)]">{t("trackOrder")}</a>
          </nav>
          <div className="hidden xl:block"><LanguageSwitcher compact /></div>
          <a href="/signup" className="hidden items-center gap-2 rounded-xl px-2 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 sm:flex">
            <CircleUserRound size={20} /> <span className="hidden xl:inline">{t("signUp")}</span><ChevronDown size={14} />
          </a>
          <button
            onClick={openCart}
            className="relative flex items-center gap-2 rounded-xl bg-[var(--brand)] px-3.5 py-2.5 text-sm font-bold text-white shadow-lg transition hover:opacity-90"
          >
            <ShoppingCart size={19} /> <span className="hidden sm:inline">{t("cart")}</span>
            {itemCount > 0 && (
              <span className="absolute -right-2 -top-2 grid h-5 min-w-5 place-items-center rounded-full bg-[#ffb019] px-1 text-[10px] font-black text-[#18213b] ring-2 ring-white">
                {itemCount}
              </span>
            )}
          </button>
        </div>

        <div className="border-t border-slate-100 px-4 py-3 md:hidden">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#155ee9]" size={18} />
            <input
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              className="h-10 w-full rounded-lg bg-[#f3f7ff] pl-10 pr-3 text-sm outline-none"
              placeholder={t("searchMobile")}
            />
          </div>
        </div>

        {mobileMenu && (
          <div className="absolute left-3 top-[62px] z-50 w-64 rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl lg:hidden">
            {[
              ["Download mobile app", "/app-download"],
              ["Create customer account", "/signup"],
              ["Seller centre", "/seller"],
              ["Affiliate program", "/affiliate"],
              ["Track your order", "/track"],
              ["Admin portal", "/admin"],
              ["Enterprise suite", "/enterprise"],
              ["Delivery partner", "/delivery"],
            ].map(([label, href]) => (
              <a key={label} href={href} className="block rounded-xl px-4 py-3 text-sm font-semibold hover:bg-blue-50 hover:text-blue-700">{label}</a>
            ))}
          </div>
        )}
      </header>

      <main id="top">
        <section className="border-b border-slate-200 bg-white">
          <div className="scrollbar-none mx-auto flex max-w-[1320px] gap-3 overflow-x-auto px-4 py-5 sm:justify-between sm:px-8">
            {categories.map((category) => {
              const Icon = categoryIcons[category.icon];
              const active = activeCategory === category.name;
              return (
                <button
                  key={category.name}
                  onClick={() => selectCategory(category.name)}
                  className="group flex min-w-[78px] flex-col items-center gap-2"
                >
                  <span
                    className={`grid h-[54px] w-[54px] place-items-center rounded-2xl transition duration-200 group-hover:-translate-y-1 group-hover:shadow-lg ${active ? "ring-2 ring-[#155ee9] ring-offset-2" : ""}`}
                    style={{ backgroundColor: category.color }}
                  >
                    <Icon size={25} className={active ? "text-[#155ee9]" : "text-[#243552]"} strokeWidth={1.8} />
                  </span>
                  <span className={`text-xs font-bold ${active ? "text-[#155ee9]" : "text-slate-700"}`}>{category.name}</span>
                </button>
              );
            })}
          </div>
        </section>

        <section className="mx-auto max-w-[1440px] px-3 pt-4 sm:px-6 lg:px-10">
          <div className="relative min-h-[390px] overflow-hidden rounded-3xl bg-[#075cd7] shadow-[0_18px_45px_rgba(18,71,148,0.18)] sm:min-h-[420px]">
            <div className="absolute inset-0 overflow-hidden">
              <div className="absolute -left-20 -top-28 h-80 w-80 rounded-full border-[48px] border-white/5" />
              <div className="absolute bottom-[-200px] left-[35%] h-[390px] w-[390px] rounded-full bg-[#1e75eb]" />
              <div className="absolute right-[30%] top-10 h-20 w-20 rotate-12 rounded-2xl border border-white/10" />
            </div>
            <div className="relative z-10 flex min-h-[390px] items-center px-7 py-12 sm:min-h-[420px] sm:px-12 lg:px-20">
              <div className="max-w-xl text-white">
                <div className="mb-5 inline-flex items-center gap-2 rounded-full bg-[#ffd54a] px-3 py-1.5 text-xs font-black uppercase tracking-wider text-[#0b2858]">
                  <Zap size={14} fill="currentColor" /> {tenant.brandName} Big Savings Days
                </div>
                <h1 className="text-[clamp(2.45rem,5vw,5rem)] font-black leading-[0.94] tracking-[-0.055em]">
                  {language === "en" ? tenant.heroTitle : t("everything")}
                  {language !== "en" && <span className="mt-2 block text-[var(--sun)]">{t("priceLove")}</span>}
                </h1>
                <p className="mt-6 max-w-md text-sm leading-6 text-blue-100 sm:text-base">
                  {tenant.heroSubtitle}
                </p>
                <div className="mt-7 flex flex-wrap items-center gap-3">
                  <button
                    onClick={() => dealsRef.current?.scrollIntoView({ behavior: "smooth" })}
                    className="flex items-center gap-2 rounded-xl bg-white px-6 py-3.5 text-sm font-black text-[#0c50ba] shadow-xl transition hover:-translate-y-0.5"
                  >
                    {t("shopTopDeals")} <ArrowRight size={17} />
                  </button>
                  <a href="/affiliate" className="rounded-xl border border-white/30 bg-white/10 px-5 py-3.5 text-sm font-bold backdrop-blur hover:bg-white/20">
                    {t("earnWithUs")}
                  </a>
                </div>
                <div className="mt-8 flex items-center gap-5 text-xs font-semibold text-blue-100">
                  <span className="flex items-center gap-1.5"><ShieldCheck size={16} /> {t("securePayments")}</span>
                  <span className="flex items-center gap-1.5"><Truck size={16} /> {t("easyReturns")}</span>
                </div>
              </div>
            </div>
            <div className="absolute -bottom-20 right-[-38px] hidden h-[500px] w-[42%] overflow-hidden rounded-tl-[150px] bg-[#ffca38] md:block lg:right-10 lg:w-[35%] lg:rounded-t-[190px]">
              <img src={heroImage} alt={`Happy shopper using the ${tenant.brandName} app`} className="h-full w-full object-cover object-top mix-blend-multiply" />
            </div>
            <div className="absolute right-[33%] top-9 hidden rotate-6 rounded-2xl bg-white p-3 shadow-2xl lg:block">
              <div className="flex items-center gap-2">
                <span className="grid h-9 w-9 place-items-center rounded-xl bg-green-100 text-green-600"><BadgeCheck size={19} /></span>
                <div><p className="text-[10px] text-slate-400">Today&apos;s saving</p><p className="text-sm font-black text-slate-800">Up to 70% OFF</p></div>
              </div>
            </div>
            <div className="absolute bottom-10 right-[3%] hidden -rotate-3 rounded-2xl bg-white p-3 shadow-2xl xl:block">
              <div className="flex items-center gap-2">
                <span className="grid h-9 w-9 place-items-center rounded-xl bg-blue-100 text-blue-600"><PackageCheck size={19} /></span>
                <div><p className="text-[10px] text-slate-400">10 lakh+</p><p className="text-sm font-black text-slate-800">Happy shoppers</p></div>
              </div>
            </div>
          </div>
        </section>

        <section className="mx-auto max-w-[1370px] px-4 py-5 sm:px-8">
          <div className="grid grid-cols-2 divide-x divide-y divide-slate-200 rounded-2xl border border-slate-200 bg-white py-4 shadow-sm md:grid-cols-4 md:divide-y-0">
            {[
              [Truck, t("freeDelivery"), "On orders above ₹499"],
              [ShieldCheck, t("securePayment"), "100% protected checkout"],
              [PackageCheck, t("easyReturns"), "7-day return policy"],
              [Headphones, t("support"), "Support 8 AM–10 PM"],
            ].map(([Icon, title, caption], index) => {
              const TrustIcon = Icon as React.ElementType;
              return (
                <div key={String(title)} className={`flex items-center gap-3 px-4 py-3 sm:justify-center ${index > 1 ? "md:border-t-0" : ""}`}>
                  <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-blue-50 text-[#155ee9]"><TrustIcon size={18} /></span>
                  <div><p className="text-xs font-black text-slate-800 sm:text-sm">{String(title)}</p><p className="mt-0.5 text-[10px] text-slate-500 sm:text-xs">{String(caption)}</p></div>
                </div>
              );
            })}
          </div>
        </section>

        <section ref={dealsRef} id="deals" className="mx-auto max-w-[1440px] scroll-mt-28 px-4 pb-8 pt-4 sm:px-6 lg:px-10">
          <div className="mb-5 flex items-end justify-between">
            <div>
              <p className="mb-1 text-xs font-black uppercase tracking-[0.18em] text-[var(--brand)]">{t("handpicked")}</p>
              <h2 className="text-2xl font-black tracking-[-0.03em] text-[#14203a] sm:text-3xl">
                {activeCategory === "All" ? t("topDeals") : `Best in ${activeCategory}`}
              </h2>
            </div>
            <button onClick={() => { setActiveCategory("All"); setQuery(""); }} className="hidden items-center gap-1 text-sm font-bold text-[#155ee9] sm:flex">
              View all <ChevronRight size={17} />
            </button>
          </div>

          {filteredProducts.length === 0 ? (
            <div className="rounded-2xl bg-white px-6 py-16 text-center shadow-sm">
              <Search className="mx-auto mb-3 text-slate-300" size={38} />
              <h3 className="font-black">No products found</h3>
              <p className="mt-1 text-sm text-slate-500">Try another search or browse all deals.</p>
              <button onClick={() => { setQuery(""); setActiveCategory("All"); }} className="mt-4 rounded-lg bg-[#155ee9] px-4 py-2 text-sm font-bold text-white">Browse all</button>
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-3 sm:gap-5 md:grid-cols-3 lg:grid-cols-5">
              {filteredProducts.map((product) => (
                <article key={product.id} className="product-card group relative overflow-hidden rounded-2xl border border-slate-200 bg-white p-2.5 shadow-[0_6px_24px_rgba(24,49,83,0.05)] transition duration-300 hover:-translate-y-1 hover:shadow-[0_16px_35px_rgba(24,49,83,0.13)] sm:p-3">
                  <div className="relative aspect-square overflow-hidden rounded-xl bg-[#f4f6f8]">
                    <img src={product.image} alt={product.name} className="h-full w-full object-cover transition duration-500 group-hover:scale-105" />
                    {product.badge && <span className="absolute left-2 top-2 rounded-md bg-[#123f94] px-2 py-1 text-[9px] font-black uppercase tracking-wide text-white">{product.badge}</span>}
                    <button onClick={() => showNotice("Saved to your wishlist")} className="absolute right-2 top-2 grid h-8 w-8 place-items-center rounded-full bg-white/95 text-slate-500 shadow hover:text-red-500" aria-label={`Save ${product.name}`}><Heart size={16} /></button>
                  </div>
                  <div className="px-1 pb-1 pt-3">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-slate-400">{product.seller}</p>
                    <h3 className="mt-1 line-clamp-2 min-h-10 text-xs font-bold leading-5 text-slate-800 sm:text-sm">{product.name}</h3>
                    <div className="mt-2 flex items-center gap-1.5">
                      <span className="flex items-center gap-0.5 rounded bg-[#0a9a5a] px-1.5 py-0.5 text-[10px] font-black text-white">{product.rating}<Star size={9} fill="currentColor" /></span>
                      <span className="text-[10px] text-slate-400">({product.reviews})</span>
                    </div>
                    <div className="mt-2 flex flex-wrap items-baseline gap-1.5">
                      <span className="text-base font-black text-[#14203a] sm:text-lg">{formatMoney(product.price)}</span>
                      <span className="text-[10px] text-slate-400 line-through sm:text-xs">{formatMoney(product.originalPrice)}</span>
                      <span className="text-[10px] font-black text-green-600">{Math.round((1 - product.price / product.originalPrice) * 100)}% off</span>
                    </div>
                    <p className="mt-1 text-[10px] font-semibold text-slate-500">Free delivery {product.delivery.toLowerCase()}</p>
                    <button
                      onClick={() => addToCart(product)}
                      className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg bg-[#155ee9] px-2 py-2.5 text-xs font-black text-white transition hover:bg-[#0d4fc9] sm:text-sm"
                    >
                      <ShoppingCart size={15} /> {t("addToCart")}
                    </button>
                  </div>
                </article>
              ))}
            </div>
          )}
        </section>

        <section className="mx-auto max-w-[1370px] px-4 pb-12 sm:px-8">
          <div className="grid overflow-hidden rounded-3xl bg-[#0b2756] md:grid-cols-[1.15fr_0.85fr]">
            <div className="p-8 text-white sm:p-12 lg:p-16">
              <span className="inline-flex items-center gap-2 rounded-full bg-[#ffd54a] px-3 py-1.5 text-[11px] font-black uppercase tracking-wider text-[#0b2756]"><Gift size={14} /> {tenant.brandName} Affiliate</span>
              <h2 className="mt-5 max-w-lg text-3xl font-black leading-tight tracking-[-0.035em] sm:text-4xl">Turn your audience into earnings.</h2>
              <p className="mt-4 max-w-lg text-sm leading-6 text-blue-100">Creators, publishers and companies can recommend {tenant.brandName} products and earn commission on every qualified order.</p>
              <div className="mt-7 flex flex-wrap gap-3">
                <a href="/affiliate" className="flex items-center gap-2 rounded-xl bg-white px-5 py-3 text-sm font-black text-[#0b2756]">Join the program <ArrowRight size={16} /></a>
                <a href="/seller" className="rounded-xl border border-white/20 px-5 py-3 text-sm font-bold">Sell on {tenant.brandName}</a>
              </div>
            </div>
            <div className="relative min-h-[280px] bg-[#ffd54a] p-8">
              <div className="absolute inset-0 opacity-20 [background-image:radial-gradient(#0b2756_1.5px,transparent_1.5px)] [background-size:22px_22px]" />
              <div className="relative mx-auto max-w-sm rounded-3xl bg-white p-6 shadow-2xl sm:mt-4 sm:rotate-2">
                <div className="flex items-center justify-between"><p className="text-sm font-black">Partner earnings</p><span className="rounded-full bg-green-100 px-2 py-1 text-[10px] font-bold text-green-700">+18.4%</span></div>
                <p className="mt-5 text-3xl font-black">₹24,680</p>
                <p className="mt-1 text-xs text-slate-400">This month</p>
                <div className="mt-6 flex h-20 items-end gap-2">{[38, 55, 46, 72, 60, 86, 100].map((height, i) => <span key={i} className="flex-1 rounded-t bg-[#155ee9]" style={{ height: `${height}%`, opacity: 0.45 + i * 0.08 }} />)}</div>
              </div>
            </div>
          </div>
        </section>
      </main>

      <footer className="bg-[#061a3d] text-white">
        <div className="mx-auto grid max-w-[1370px] gap-10 px-6 py-12 sm:grid-cols-2 lg:grid-cols-[1.4fr_repeat(4,1fr)] lg:px-8">
          <div>
            <div className="flex items-center gap-2">{tenant.logoUrl ? <img src={tenant.logoUrl} alt={tenant.brandName} className="h-10 max-w-40 object-contain brightness-0 invert" /> : <><span className="grid h-9 w-9 place-items-center rounded-xl bg-[var(--brand)] text-xl font-black italic">{tenant.brandName.charAt(0).toUpperCase()}</span><span className="text-2xl font-black tracking-tight">{tenant.brandName}</span></>}</div>
            <p className="mt-4 max-w-xs text-sm leading-6 text-slate-400">{tenant.footerText || tenant.tagline}</p>
            <p className="mt-4 text-xs text-slate-400">{tenant.supportEmail}<br />{tenant.phonePrimary}{tenant.phoneSecondary && <><br />{tenant.phoneSecondary}</>}</p>
          </div>
          {[
            ["About", [`About ${tenant.brandName}`, "Careers", "Press", "Corporate information"]],
            ["Help", ["Download App", "Payments", "Shipping", "Cancellation", "Returns", "FAQ"]],
            ["Partner", [`Sell on ${tenant.brandName}`, "Affiliate program", "Delivery partner", "Advertise"]],
            ["Policies", ["Privacy", "Terms of use", "Security", "Sitemap"]],
          ].map(([heading, links]) => (
            <div key={String(heading)}><h3 className="text-xs font-black uppercase tracking-[0.15em] text-[#ffd54a]">{String(heading)}</h3><ul className="mt-4 space-y-2.5 text-xs text-slate-300">{(links as string[]).map((link) => <li key={link}><a href={link.includes("Affiliate") ? "/affiliate" : link.includes("Sell") ? "/seller" : link === "Download App" ? "/app-download" : link === "Payments" ? "/payment" : link === "Shipping" ? "/track" : "#"} className="hover:text-white">{link}</a></li>)}</ul></div>
          ))}
        </div>
        <div className="border-t border-white/10 px-5 py-5 text-center text-[11px] text-slate-400">© 2026 {tenant.legalName}. All rights reserved. Secure payments powered by {tenant.brandName} Pay.</div>
      </footer>

      <div className="fixed bottom-0 left-0 right-0 z-30 grid grid-cols-4 border-t border-slate-200 bg-white px-2 py-2 shadow-[0_-4px_20px_rgba(0,0,0,0.08)] md:hidden">
        <a href="#top" className="flex flex-col items-center gap-1 text-[10px] font-bold text-[#155ee9]"><Home size={19} /> Home</a>
        <button onClick={() => dealsRef.current?.scrollIntoView({ behavior: "smooth" })} className="flex flex-col items-center gap-1 text-[10px] font-bold text-slate-500"><Search size={19} /> Explore</button>
        <a href="/track" className="flex flex-col items-center gap-1 text-[10px] font-bold text-slate-500"><Box size={19} /> Orders</a>
        <button onClick={openCart} className="relative flex flex-col items-center gap-1 text-[10px] font-bold text-slate-500"><ShoppingCart size={19} /> Cart{itemCount > 0 && <span className="absolute right-[25%] top-[-3px] rounded-full bg-orange-400 px-1 text-[8px] text-white">{itemCount}</span>}</button>
      </div>

      {notice && (
        <div className="fixed bottom-20 left-1/2 z-[70] flex -translate-x-1/2 items-center gap-2 rounded-xl bg-[#101d37] px-4 py-3 text-xs font-bold text-white shadow-2xl md:bottom-7">
          <Check size={16} className="text-green-400" /> {notice}
        </div>
      )}

      {cartOpen && (
        <div className="fixed inset-0 z-[60]">
          <button className="absolute inset-0 bg-[#071a3b]/55 backdrop-blur-[2px]" onClick={() => setCartOpen(false)} aria-label="Close cart" />
          <aside className="absolute right-0 top-0 flex h-full w-full max-w-[520px] flex-col bg-[#f7f8fa] shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-200 bg-white px-5 py-5">
              <div>
                <p className="text-lg font-black tracking-tight">{step === "cart" ? "Your cart" : step === "details" ? "Delivery & payment" : step === "success" ? "Order confirmed" : "Payment"}</p>
                {step !== "success" && <p className="mt-0.5 text-xs text-slate-500">{itemCount} {itemCount === 1 ? "item" : "items"} • Safe & secure checkout</p>}
              </div>
              <button onClick={() => setCartOpen(false)} className="grid h-9 w-9 place-items-center rounded-full bg-slate-100 text-slate-600 hover:bg-slate-200"><X size={19} /></button>
            </div>

            {step === "cart" && (
              <>
                <div className="flex-1 overflow-y-auto p-4 sm:p-5">
                  {cart.length === 0 ? (
                    <div className="flex h-full flex-col items-center justify-center text-center">
                      <span className="grid h-24 w-24 place-items-center rounded-full bg-blue-50 text-[#155ee9]"><ShoppingCart size={40} /></span>
                      <h3 className="mt-5 text-xl font-black">Your cart is waiting</h3>
                      <p className="mt-2 max-w-xs text-sm leading-6 text-slate-500">Add something you love and it will show up right here.</p>
                      <button onClick={() => setCartOpen(false)} className="mt-6 rounded-xl bg-[#155ee9] px-6 py-3 text-sm font-black text-white">Start shopping</button>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      <div className="flex items-center gap-2 rounded-xl bg-green-50 px-3 py-2.5 text-xs font-bold text-green-700"><Truck size={16} /> Yay! Your order qualifies for free delivery.</div>
                      {cart.map((item) => (
                        <div key={item.id} className="flex gap-3 rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                          <img src={item.image} alt="" className="h-24 w-24 shrink-0 rounded-xl object-cover" />
                          <div className="min-w-0 flex-1">
                            <p className="line-clamp-2 text-sm font-bold leading-5">{item.name}</p>
                            <p className="mt-1 text-[10px] text-slate-400">Sold by {item.seller}</p>
                            <div className="mt-2 flex items-center gap-2"><span className="text-base font-black">{formatMoney(item.price)}</span><span className="text-xs text-slate-400 line-through">{formatMoney(item.originalPrice)}</span></div>
                            <div className="mt-2 flex items-center justify-between">
                              <div className="flex items-center rounded-lg border border-slate-200"><button onClick={() => updateQuantity(item.id, -1)} className="p-1.5"><Minus size={14} /></button><span className="w-7 text-center text-xs font-black">{item.quantity}</span><button onClick={() => updateQuantity(item.id, 1)} className="p-1.5"><Plus size={14} /></button></div>
                              <button onClick={() => setCart((current) => current.filter((line) => line.id !== item.id))} className="p-2 text-slate-400 hover:text-red-500" aria-label={`Remove ${item.name}`}><Trash2 size={16} /></button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
                {cart.length > 0 && (
                  <div className="border-t border-slate-200 bg-white p-5">
                    <div className="mb-4 space-y-2 text-sm"><div className="flex justify-between text-slate-500"><span>MRP total</span><span>{formatMoney(mrpTotal)}</span></div><div className="flex justify-between font-bold text-green-600"><span>Product discount</span><span>− {formatMoney(discount)}</span></div><div className="flex justify-between text-slate-500"><span>Delivery</span><span className="font-bold text-green-600">FREE</span></div><div className="flex justify-between border-t border-dashed border-slate-200 pt-3 text-lg font-black"><span>Total</span><span>{formatMoney(subtotal)}</span></div></div>
                    <button onClick={() => setStep("details")} className="flex w-full items-center justify-between rounded-xl bg-[#ffb21d] px-5 py-4 font-black text-[#18213b] shadow-lg hover:bg-[#ffa90a]"><span>Proceed to checkout</span><ArrowRight size={19} /></button>
                    <p className="mt-3 flex items-center justify-center gap-1 text-[10px] text-slate-400"><ShieldCheck size={13} /> Your payment information is encrypted</p>
                  </div>
                )}
              </>
            )}

            {step === "details" && (
              <form onSubmit={placeOrder} className="flex min-h-0 flex-1 flex-col">
                <div className="flex-1 overflow-y-auto p-4 sm:p-5">
                  <button type="button" onClick={() => setStep("cart")} className="mb-4 flex items-center gap-1 text-xs font-bold text-[#155ee9]"><ChevronLeft size={16} /> Back to cart</button>
                  <div className="mb-4 flex items-center gap-2"><span className="grid h-8 w-8 place-items-center rounded-full bg-blue-100 text-[#155ee9]"><MapPin size={17} /></span><h3 className="font-black">Where should we deliver?</h3></div>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <label className="input-label sm:col-span-2">Full name<input required name="customerName" placeholder="e.g. Aarav Sharma" className="checkout-input" /></label>
                    <label className="input-label">Phone number<input required name="phone" type="tel" pattern="[0-9+ ]{10,15}" placeholder="10-digit mobile" className="checkout-input" /></label>
                    <label className="input-label">Email<input required name="email" type="email" placeholder="you@example.com" className="checkout-input" /></label>
                    <label className="input-label sm:col-span-2">Complete address<textarea required name="address" rows={3} placeholder="House no., street, area and landmark" className="checkout-input resize-none" /></label>
                    <label className="input-label">City<input required name="city" placeholder="Your city" className="checkout-input" /></label>
                    <label className="input-label">PIN code<input required name="pincode" inputMode="numeric" pattern="[0-9]{6}" placeholder="6-digit PIN" className="checkout-input" /></label>
                  </div>

                  <div className="mb-3 mt-7 flex items-center gap-2"><span className="grid h-8 w-8 place-items-center rounded-full bg-blue-100 text-[#155ee9]"><CreditCard size={17} /></span><h3 className="font-black">Choose payment method</h3></div>
                  <div className="space-y-2">
                    <label className={`flex cursor-pointer items-center gap-3 rounded-xl border bg-white p-4 ${paymentMethod === "card" ? "border-[#155ee9] ring-2 ring-blue-100" : "border-slate-200"}`}>
                      <input type="radio" checked={paymentMethod === "card"} onChange={() => setPaymentMethod("card")} className="accent-[#155ee9]" />
                      <span className="grid h-9 w-9 place-items-center rounded-lg bg-blue-50 text-[#155ee9]"><CreditCard size={19} /></span>
                      <span className="flex-1"><span className="block text-sm font-black">Credit / Debit Card</span><span className="text-[10px] text-slate-400">Visa, Mastercard, RuPay</span></span>
                      <ShieldCheck size={17} className="text-green-600" />
                    </label>
                    {paymentMethod === "card" && (
                      <div className="grid gap-3 rounded-xl border border-slate-200 bg-white p-4 sm:grid-cols-2">
                        <label className="input-label sm:col-span-2">Card number<input required inputMode="numeric" pattern="[0-9 ]{15,19}" placeholder="0000 0000 0000 0000" className="checkout-input" /></label>
                        <label className="input-label">Expiry<input required placeholder="MM / YY" pattern="[0-9]{2} ?/ ?[0-9]{2}" className="checkout-input" /></label>
                        <label className="input-label">CVV<input required type="password" inputMode="numeric" pattern="[0-9]{3,4}" placeholder="•••" className="checkout-input" /></label>
                        <p className="sm:col-span-2 text-[10px] leading-4 text-slate-400">Demo checkout: card details are validated in your browser and never stored.</p>
                      </div>
                    )}
                    <label className={`flex cursor-pointer items-center gap-3 rounded-xl border bg-white p-4 ${paymentMethod === "cod" ? "border-[#155ee9] ring-2 ring-blue-100" : "border-slate-200"}`}>
                      <input type="radio" checked={paymentMethod === "cod"} onChange={() => setPaymentMethod("cod")} className="accent-[#155ee9]" />
                      <span className="grid h-9 w-9 place-items-center rounded-lg bg-orange-50 text-orange-600"><Banknote size={19} /></span>
                      <span className="flex-1"><span className="block text-sm font-black">Cash on Delivery</span><span className="text-[10px] text-slate-400">Pay when your order arrives</span></span>
                    </label>
                  </div>
                  {otpOpen && pendingOrder && (
                    <div className="mt-6">
                      <VoiceOtpPanel
                        key={`${pendingOrder.phone}-${pendingOrder.paymentMethod}`}
                        phone={pendingOrder.phone}
                        purpose="checkout"
                        compact
                        onVerified={(token) => void submitVerifiedOrder(pendingOrder, token)}
                      />
                    </div>
                  )}
                </div>
                <div className="border-t border-slate-200 bg-white p-5">
                  <div className="mb-3 flex items-center justify-between"><span className="text-xs text-slate-500">Payable amount</span><span className="text-xl font-black">{formatMoney(subtotal)}</span></div>
                  <button disabled={submitting || otpOpen} type="submit" className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#ffb21d] px-5 py-4 font-black text-[#18213b] shadow-lg disabled:opacity-60">{submitting ? "Securing your verified order…" : otpOpen ? "Complete voice verification above" : paymentMethod === "cod" ? "Verify phone & confirm order" : `Verify phone & pay ${formatMoney(subtotal)}`} <ArrowRight size={18} /></button>
                  <p className="mt-2 text-center text-[9px] text-slate-400">A verified mobile number is required for every order.</p>
                </div>
              </form>
            )}

            {step === "success" && placedOrder && (
              <div className="flex flex-1 flex-col items-center justify-center overflow-y-auto p-6 text-center">
                <div className="relative grid h-24 w-24 place-items-center rounded-full bg-green-100 text-green-600"><Check size={47} strokeWidth={3} /><span className="absolute -right-2 top-0 text-3xl">🎉</span></div>
                <p className="mt-6 text-xs font-black uppercase tracking-[0.18em] text-green-600">Order placed successfully</p>
                <h3 className="mt-2 text-3xl font-black tracking-tight">Thank you for shopping!</h3>
                <p className="mt-3 max-w-sm text-sm leading-6 text-slate-500">We&apos;ve received your order and will send you updates as it moves. Save your tracking ID.</p>
                <div className="mt-6 w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-5 text-left shadow-sm"><div className="flex justify-between border-b border-slate-100 pb-3"><span className="text-xs text-slate-400">Order number</span><span className="text-sm font-black">{placedOrder.orderNumber}</span></div><div className="flex justify-between pt-3"><span className="text-xs text-slate-400">Tracking ID</span><span className="text-sm font-black text-[#155ee9]">{placedOrder.trackingId}</span></div></div>
                <div className="mt-6 flex w-full max-w-sm gap-3"><a href={`/track?id=${placedOrder.trackingId}`} className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-[#155ee9] px-4 py-3 text-sm font-black text-white"><Truck size={17} /> Track order</a><button onClick={() => setCartOpen(false)} className="flex-1 rounded-xl border border-slate-300 px-4 py-3 text-sm font-black">Continue shopping</button></div>
              </div>
            )}
          </aside>
        </div>
      )}
    </div>
  );
}
