import Link from "next/link";
import { ArrowRight, Boxes, CreditCard, PackageCheck, Settings, ShieldCheck } from "lucide-react";
import { ProductCard } from "@/components/ProductCard";
import { ProductVisual } from "@/components/ProductVisual";
import { prisma } from "@/lib/prisma";
import { getBestRecommendation, getRecommendationLeaderboard, type RecommendationProduct } from "@/lib/recommendations";
import { currency, displayPrice } from "@/lib/utils";

const categoryCards = [
  ["Gold Bars", "Minted and cast bar formats.", "/gold?type=BAR", "GOLD", "BAR"],
  ["Gold Coins", "Recognized bullion coin issues.", "/gold?type=COIN", "GOLD", "COIN"],
  ["Silver Bars", "1 oz through bulk silver bars.", "/silver?type=BAR", "SILVER", "BAR"],
  ["Silver Coins", "Popular sovereign silver coins.", "/silver?type=COIN", "SILVER", "COIN"],
  ["Rounds", "Bullion rounds by metal and size.", "/products?type=ROUND", "SILVER", "ROUND"],
  ["Collectibles", "Premium coin and round selections.", "/products?type=COLLECTIBLE", "GOLD", "COIN"],
  ["IRA Eligible", "Products marked for IRA support.", "/products?ira=true", "GOLD", "BAR"],
  ["Sell-Back", "Request a review for metals owned.", "/sell-back", "SILVER", "COIN"]
];

const popularNow = [
  ["1 oz Gold Bar", "/products?search=1%20oz%20Gold"],
  ["Gold Krugerrand", "/products?search=Krugerrand"],
  ["Silver Maple Leaf", "/products?search=Silver%20Maple%20Leaf"],
  ["10 oz Silver Bar", "/products?search=10%20oz%20Silver"]
];

const trustItems = [
  [Boxes, "Gold & Silver Products", "Bars, coins, rounds, and eligible options"],
  [Settings, "Manual Price Updates", "Prices updated by our team"],
  [ShieldCheck, "Secure Checkout", "Payment options available"],
  [PackageCheck, "Fulfillment Review", "Orders reviewed before coordination"]
];

const featuredTabs = ["Best Sellers", "New Arrivals", "Gold Picks", "Silver Picks", "IRA Eligible"];
const promoCards = [
  ["IRA Eligible Bullion", "Browse eligible products clearly marked for support.", "/products?ira=true"],
  ["Sell-Back Review", "Request a review for gold or silver you own.", "/sell-back"],
  ["Service Fee Payment", "Pay service fees through secure checkout options.", "/service-fees"],
  ["Support Available", "Get help choosing product formats and next steps.", "/support"]
];
const weights = ["1g", "2.5g", "5g", "10g", "1 oz", "5 oz", "10 oz", "100 oz", "1 kg"];
const mints = ["Nadir", "IAR", "Atasay", "PAMP Suisse", "Valcambi", "Royal Mint", "Perth Mint", "US Mint", "Royal Canadian Mint"];

type SectionTitleProps = {
  kicker: string;
  title: string;
  copy?: string;
  href?: string;
  action?: string;
  dark?: boolean;
};

function SectionTitle({ kicker, title, copy, href, action, dark = false }: SectionTitleProps) {
  return (
    <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
      <div className="max-w-2xl">
        <p className={`border-l-4 pl-3 text-xs font-black uppercase tracking-[0.14em] ${dark ? "border-[#d4af37] text-[#d4af37]" : "border-[#b8860b] text-[#725306]"}`}>{kicker}</p>
        <h2 className={`mt-2 text-2xl font-black leading-tight md:text-3xl ${dark ? "text-white" : "text-[#111827]"}`}>{title}</h2>
        {copy ? <p className={`mt-1 text-sm leading-6 ${dark ? "text-white/70" : "text-[#5f6673]"}`}>{copy}</p> : null}
      </div>
      {href && action ? (
        <Link className={dark ? "gold-button min-h-10 px-4 text-sm" : "outline-button min-h-10 px-4 text-sm"} href={href}>
          {action}
          <ArrowRight size={16} />
        </Link>
      ) : null}
    </div>
  );
}

function pickUnique<T extends { product: { id: string } }>(items: T[], usedIds: Set<string>) {
  return items.find((item) => !usedIds.has(item.product.id)) || null;
}

type RecommendationEntry = {
  product: RecommendationProduct;
  score: number;
  reasons: string[];
};

function RecommendationCenter({
  bestRecommendation,
  topAlternatives,
  recommendationPicks,
  className = ""
}: {
  bestRecommendation: RecommendationEntry;
  topAlternatives: RecommendationEntry[];
  recommendationPicks: { label: string; entry: RecommendationEntry }[];
  className?: string;
}) {
  return (
    <section className={`home-section-band home-recommendation-section border-b border-[#d8d2c4] bg-white ${className}`}>
      <div className="container-grid">
        <div className="recommendation-center-shell overflow-hidden rounded-[24px] border border-[#d7ccb4] bg-[#fffaf0] shadow-[0_18px_44px_rgba(16,24,32,0.08)]">
          <div className="recommendation-center-header border-b border-[#e5dac3] bg-[#fbf5e8] px-5 py-4">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.14em] text-[#7a5310]">Recommendation Center</p>
                <h2 className="mt-1 text-2xl font-black text-[#171717]">Bullion Picks Ranked by Admin-Entered Data</h2>
              </div>
              <p className="max-w-xl text-sm leading-6 text-[#5f6673]">Informational product ranking for the storefront. This is not financial advice.</p>
            </div>
          </div>
          <div className="recommendation-center-main grid gap-5 p-5 lg:grid-cols-[minmax(0,0.95fr)_minmax(320px,0.7fr)] lg:items-center">
            <div>
              <div className="flex flex-wrap items-center gap-2">
                <span className="rounded-full border border-[#c9ab55] bg-[#fff3cf] px-3 py-1 text-[11px] font-black uppercase tracking-[0.14em] text-[#7a5310]">Today&apos;s Best Product</span>
                <span className="rounded-full border border-[#d4af37] bg-white px-3 py-1.5 text-xs font-black uppercase tracking-[0.12em] text-[#7a5310] shadow-sm">
                  Score {bestRecommendation.score}/100
                </span>
              </div>
              <h2 className="mt-3 text-3xl font-black leading-tight text-[#171717] md:text-4xl">{bestRecommendation.product.name}</h2>
              <p className="mt-3 max-w-3xl text-sm leading-6 text-[#5f6673] md:text-base">
                Ranked using admin-entered premium, spread, liquidity, shipping speed, IRA eligibility, stock, and price freshness data.
              </p>
              <div className="mt-4 flex flex-wrap items-center gap-2">
                <span className="rounded-full border border-[#e2d8c5] bg-white px-3 py-1.5 text-xs font-black uppercase tracking-[0.12em] text-[#5f5a52] shadow-sm">
                  {bestRecommendation.product.metalType} / {bestRecommendation.product.weight} / {bestRecommendation.product.karat || bestRecommendation.product.purity}
                </span>
              </div>
              <div className="mt-5 text-4xl font-black tracking-tight text-[#171717]">{currency(displayPrice(bestRecommendation.product))}</div>
              <ul className="mt-5 flex flex-wrap gap-2.5 text-sm text-[#5f6673]">
                {bestRecommendation.reasons.map((reason) => (
                  <li key={reason} className="rounded-full border border-[#e7dcc7] bg-white px-3.5 py-2 text-sm font-bold shadow-sm">
                    {reason}
                  </li>
                ))}
              </ul>
              <div className="mt-6 flex flex-wrap gap-3">
                <Link href={`/products/${bestRecommendation.product.slug}`} className="gold-button min-h-11 px-5">View Product <ArrowRight size={16} /></Link>
                <Link href="/products" className="outline-button min-h-11 px-5">All Products</Link>
              </div>
              <p className="mt-5 max-w-2xl text-xs leading-5 text-[#5f6673]">
                Recommendation scores are informational and based on admin-entered product data. This is not financial advice.
              </p>
            </div>
            <div className="grid gap-4">
              <div className="recommendation-center-visual grid min-h-[260px] place-items-center rounded-[22px] border border-[#dfd0b8] bg-white p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.9)]">
                <ProductVisual product={bestRecommendation.product} className="min-h-[220px]" />
              </div>
              <div className="rounded-[20px] border border-[#e7dcc7] bg-white p-4 text-sm text-[#5f6673] shadow-sm">
                <p className="text-xs font-black uppercase tracking-[0.14em] text-[#725306]">Why it surfaced</p>
                <p className="mt-2 leading-6">
                  This product currently leads the storefront recommendation score among eligible public bullion products.
                </p>
              </div>
            </div>
          </div>
        </div>
        {topAlternatives.length ? (
          <div className="recommendation-center-lower mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]">
            <div className="rounded-[22px] border border-[#dfd0b8] bg-[#fffdf8] p-4 shadow-[0_16px_34px_rgba(16,24,32,0.05)]">
              <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.14em] text-[#725306]">Top Alternatives</p>
                  <h3 className="mt-2 text-xl font-black text-[#171717]">Other high-scoring bullion picks</h3>
                  <p className="mt-1 text-sm text-[#5f6673]">Ranked using admin-entered product data. Informational only.</p>
                </div>
                <Link href="/products" className="outline-button min-h-10 px-4 text-sm">All Products</Link>
              </div>
              <div className="recommendation-alternatives-grid grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                {topAlternatives.map((entry) => (
                  <div key={entry.product.id} className="recommendation-alternative-card flex h-full flex-col rounded-[20px] border border-[#e7dcc7] bg-white p-4 shadow-sm">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <h4 className="line-clamp-2 min-h-[48px] text-base font-black leading-snug text-[#171717]" title={entry.product.name}>{entry.product.name}</h4>
                        <p className="mt-1 text-xs font-bold uppercase tracking-[0.12em] text-[#7a5310]">{entry.product.metalType} / {entry.product.weight}</p>
                        <p className="mt-1 text-xs font-bold text-[#666]">{entry.product.karat || entry.product.purity}</p>
                      </div>
                      <span className="shrink-0 rounded-full border border-[#d4af37] bg-[#fff8ea] px-2.5 py-1 text-xs font-black text-[#7a5310] shadow-sm">{entry.score}/100</span>
                    </div>
                    <div className="mt-4 text-xl font-black text-[#171717]">{currency(displayPrice(entry.product))}</div>
                    <div className="mt-3 flex flex-wrap gap-2" title={entry.reasons.join(" / ")}>
                      {entry.reasons.slice(0, 2).map((reason) => (
                        <span key={reason} className="rounded-full border border-[#ece3d1] bg-[#fbf7ee] px-2.5 py-1 text-[11px] font-bold text-[#5f5a52]">
                          {reason}
                        </span>
                      ))}
                    </div>
                    <div className="mt-auto pt-4">
                      <Link href={`/products/${entry.product.slug}`} className="outline-button min-h-10 w-full justify-center text-sm">View Product</Link>
                    </div>
                  </div>
                ))}
              </div>
              <div className="recommendation-method-panel mt-4 rounded-[18px] border border-[#dfd0b8] bg-white p-4 shadow-sm">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.14em] text-[#725306]">How These Picks Are Ranked</p>
                    <h3 className="mt-2 text-lg font-black text-[#171717]">Admin-entered recommendation factors</h3>
                  </div>
                  <span className="rounded-full border border-[#d4af37] bg-[#fff8ea] px-3 py-1 text-[11px] font-black uppercase tracking-[0.12em] text-[#7a5310]">
                    Informational
                  </span>
                </div>
                <div className="recommendation-method-grid mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
                  {[
                    "Stock availability",
                    "Premium",
                    "Spread",
                    "Liquidity",
                    "Shipping speed",
                    "IRA eligibility",
                    "Price freshness",
                  ].map((factor) => (
                    <span key={factor} className="recommendation-method-pill">
                      {factor}
                    </span>
                  ))}
                </div>
                <p className="mt-4 text-xs leading-5 text-[#5f6673]">
                  Rankings are based on storefront product data entered by the team. They are informational only and are not financial advice.
                </p>
              </div>
            </div>
            {recommendationPicks.length ? (
              <div className="recommendation-picks-panel rounded-[22px] border border-[#223246] bg-[#101820] p-4 text-white shadow-[0_16px_34px_rgba(16,24,32,0.16)]">
                <p className="text-xs font-black uppercase tracking-[0.14em] text-[#d4af37]">Recommendation Picks</p>
                <div className="mt-4 grid gap-3">
                  {recommendationPicks.map(({ label, entry }) => (
                    <div key={label} className="rounded-[18px] border border-white/10 bg-white/5 p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.06)]">
                      <p className="text-[11px] font-black uppercase tracking-[0.12em] text-[#d4af37]">{label}</p>
                      <h4 className="mt-2 text-sm font-black">{entry.product.name}</h4>
                      <p className="mt-1 text-xs font-bold text-white/70">{entry.product.metalType} / {entry.product.weight} / {entry.product.karat || entry.product.purity}</p>
                      <div className="mt-2 flex items-center justify-between gap-2">
                        <span className="text-sm font-black">{currency(displayPrice(entry.product))}</span>
                        <span className="rounded-full border border-[#d4af37]/50 bg-white/10 px-2.5 py-1 text-[11px] font-black text-[#f3e7c4]">{entry.score}/100</span>
                      </div>
                      <div className="mt-2 flex flex-wrap gap-1.5" title={entry.reasons.join(" / ")}>
                        {entry.reasons.slice(0, 2).map((reason) => (
                          <span key={reason} className="rounded-full border border-white/10 bg-white/10 px-2 py-1 text-[11px] font-bold text-white/80">
                            {reason}
                          </span>
                        ))}
                      </div>
                      <Link href={`/products/${entry.product.slug}`} className="gold-button mt-3 min-h-10 w-full justify-center text-sm">View Product</Link>
                    </div>
                  ))}
                </div>
                <p className="mt-4 text-xs leading-5 text-white/65">Ranked using admin-entered product data. Informational only. This is not financial advice.</p>
              </div>
            ) : null}
          </div>
        ) : null}
      </div>
    </section>
  );
}

function MobileRecommendationSummary({
  bestRecommendation,
  topAlternatives,
  className = ""
}: {
  bestRecommendation: RecommendationEntry;
  topAlternatives: RecommendationEntry[];
  className?: string;
}) {
  return (
    <section className={`mobile-recommendation-summary border-b border-[#d8d2c4] bg-white ${className}`}>
      <div className="container-grid">
        <div className="rounded-[18px] border border-[#d7ccb4] bg-[#fffaf0] p-3 shadow-[0_12px_28px_rgba(16,24,32,0.08)]">
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0">
              <p className="text-[11px] font-black uppercase tracking-[0.14em] text-[#7a5310]">Recommendation Center</p>
              <h2 className="mt-1 text-lg font-black leading-tight text-[#171717]">Today&apos;s Best Product</h2>
            </div>
            <span className="shrink-0 rounded-full border border-[#d4af37] bg-white px-2.5 py-1 text-[11px] font-black text-[#7a5310]">
              {bestRecommendation.score}/100
            </span>
          </div>

          <div className="mt-3 rounded-[14px] border border-[#e7dcc7] bg-white p-3">
            <h3 className="line-clamp-2 text-base font-black leading-snug text-[#111827]">{bestRecommendation.product.name}</h3>
            <p className="mt-1 text-[11px] font-black uppercase tracking-[0.1em] text-[#725306]">
              {bestRecommendation.product.metalType} / {bestRecommendation.product.weight} / {bestRecommendation.product.karat || bestRecommendation.product.purity}
            </p>
            <div className="mt-2 text-2xl font-black text-[#171717]">{currency(displayPrice(bestRecommendation.product))}</div>
            <div className="mt-2 flex flex-wrap gap-1.5">
              {bestRecommendation.reasons.slice(0, 3).map((reason) => (
                <span key={reason} className="rounded-full border border-[#ece3d1] bg-[#fbf7ee] px-2 py-1 text-[11px] font-bold text-[#5f5a52]">
                  {reason}
                </span>
              ))}
            </div>
            <div className="mt-3 grid grid-cols-2 gap-2">
              <Link href={`/products/${bestRecommendation.product.slug}`} className="gold-button min-h-10 justify-center px-3 text-sm">View Product</Link>
              <Link href="/products" className="outline-button min-h-10 justify-center px-3 text-sm">All Products</Link>
            </div>
          </div>

          {topAlternatives.length ? (
            <div className="mt-3">
              <div className="flex items-center justify-between gap-2">
                <p className="text-xs font-black uppercase tracking-[0.12em] text-[#725306]">Top Alternatives</p>
                <Link href="/products" className="text-xs font-black text-[#725306] underline underline-offset-4">Browse all</Link>
              </div>
              <div className="mobile-alternatives-scroll mt-2 flex gap-2 overflow-x-auto pb-1">
                {topAlternatives.slice(0, 3).map((entry) => (
                  <Link key={entry.product.id} href={`/products/${entry.product.slug}`} className="min-w-[190px] rounded-[14px] border border-[#e7dcc7] bg-white p-3 text-[#111827]">
                    <div className="flex items-start justify-between gap-2">
                      <h4 className="line-clamp-2 text-sm font-black leading-snug">{entry.product.name}</h4>
                      <span className="shrink-0 rounded-full bg-[#fff8ea] px-2 py-0.5 text-[10px] font-black text-[#7a5310]">{entry.score}</span>
                    </div>
                    <p className="mt-1 text-[11px] font-bold uppercase tracking-[0.08em] text-[#725306]">{entry.product.metalType} / {entry.product.weight}</p>
                    <p className="mt-2 text-sm font-black">{currency(displayPrice(entry.product))}</p>
                  </Link>
                ))}
              </div>
            </div>
          ) : null}

          <p className="mt-3 text-[11px] leading-5 text-[#5f6673]">
            Recommendation scores are informational and based on admin-entered product data. This is not financial advice.
          </p>
        </div>
      </div>
    </section>
  );
}

export default async function HomePage() {
  const [products, featured, gold, silver, valuePicks, recommendationCandidates] = await Promise.all([
    prisma.product.findMany({ where: { itemKind: "PHYSICAL_BULLION", isPublicProduct: true }, take: 24, orderBy: [{ isFeatured: "desc" }, { createdAt: "desc" }] }),
    prisma.product.findMany({ where: { isFeatured: true, itemKind: "PHYSICAL_BULLION", isPublicProduct: true }, take: 8, orderBy: [{ stockStatus: "asc" }, { createdAt: "desc" }] }),
    prisma.product.findMany({ where: { metalType: "GOLD", itemKind: "PHYSICAL_BULLION", isPublicProduct: true }, take: 4, orderBy: [{ isFeatured: "desc" }, { createdAt: "desc" }] }),
    prisma.product.findMany({ where: { metalType: "SILVER", itemKind: "PHYSICAL_BULLION", isPublicProduct: true }, take: 4, orderBy: [{ isFeatured: "desc" }, { createdAt: "desc" }] }),
    prisma.product.findMany({ where: { itemKind: "PHYSICAL_BULLION", isPublicProduct: true }, take: 4, orderBy: [{ customerPrice: "asc" }, { createdAt: "desc" }] }),
    prisma.product.findMany({ where: { itemKind: "PHYSICAL_BULLION", isPublicProduct: true } })
  ]);

  const heroGoldPick = gold[0] ?? featured[0] ?? products[0];
  const heroSilverPick = silver[0] ?? featured.find((product) => product.metalType === "SILVER") ?? products.find((product) => product.metalType === "SILVER");
  const featuredProducts = products.length ? products : featured;
  const bestRecommendation = getBestRecommendation(recommendationCandidates);
  const recommendationLeaderboard = getRecommendationLeaderboard(recommendationCandidates);
  const topAlternatives = bestRecommendation
    ? recommendationLeaderboard.filter((entry) => entry.product.id !== bestRecommendation.product.id).slice(0, 3)
    : [];

  const usedRecommendationIds = new Set([
    bestRecommendation?.product.id,
    ...topAlternatives.map((entry) => entry.product.id)
  ].filter(Boolean) as string[]);

  const iraCandidates = recommendationLeaderboard.filter((entry) => entry.product.isIraEligible);
  const bestIraPick = pickUnique(iraCandidates, usedRecommendationIds) || iraCandidates[0] || null;
  if (bestIraPick) usedRecommendationIds.add(bestIraPick.product.id);

  const lowestPremiumCandidates = recommendationLeaderboard
    .filter((entry) => Number.isFinite(Number(entry.product.premiumPercent ?? NaN)))
    .map((entry) => ({
      ...entry,
      reasons: [`Premium ${Number(entry.product.premiumPercent ?? 0).toFixed(2)}%`, ...entry.reasons.filter((reason) => reason !== "Low entered premium").slice(0, 1)]
    }))
    .sort((a, b) => Number(a.product.premiumPercent ?? 0) - Number(b.product.premiumPercent ?? 0) || b.score - a.score);
  const lowestPremiumPick = pickUnique(lowestPremiumCandidates, usedRecommendationIds) || lowestPremiumCandidates[0] || null;
  if (lowestPremiumPick) usedRecommendationIds.add(lowestPremiumPick.product.id);

  const fastShippingCandidates = recommendationLeaderboard
    .map((entry) => ({
      ...entry,
      reasons: [`Shipping score ${Number(entry.product.shippingSpeedScore ?? 0)}/5`, ...entry.reasons.filter((reason) => reason !== "Fast shipping score").slice(0, 1)]
    }))
    .sort((a, b) => Number(b.product.shippingSpeedScore ?? 0) - Number(a.product.shippingSpeedScore ?? 0) || b.score - a.score);
  const fastShippingPick = pickUnique(fastShippingCandidates, usedRecommendationIds) || fastShippingCandidates[0] || null;

  const recommendationPicks = [
    bestIraPick ? { label: "Best IRA Option", entry: bestIraPick } : null,
    lowestPremiumPick ? { label: "Lowest Premium Pick", entry: lowestPremiumPick } : null,
    fastShippingPick ? { label: "Fast Shipping Pick", entry: fastShippingPick } : null
  ].filter(Boolean) as { label: string; entry: { product: typeof recommendationCandidates[number]; score: number; reasons: string[] } }[];

  return (
    <main className="storefront-page home-storefront-page text-[#111827]">
      <section className="home-hero-section border-b border-[#d8d2c4]">
        <div className="container-grid py-4 md:py-5">
          <div className="home-hero-panel overflow-hidden">
            <div className="grid gap-0 lg:grid-cols-[minmax(0,0.8fr)_minmax(520px,1.2fr)]">
              <div className="home-hero-copy bg-white p-5 md:p-6">
                <p className="text-xs font-black uppercase tracking-[0.16em] text-[#725306]">Precious Metals Store</p>
                <h1 className="mt-2 max-w-xl text-3xl font-black leading-tight text-[#111827] md:text-5xl">Buy Gold & Silver Bullion Online</h1>
                <p className="mt-3 max-w-xl text-sm leading-6 text-[#5f6673] md:text-base">
                  Shop physical bullion products with clear details, manual price updates, secure checkout, and fulfillment review.
                </p>
                <div className="home-hero-actions mt-5 flex flex-wrap gap-2">
                  <Link className="gold-button min-h-11 px-4" href="/gold">Shop Gold <ArrowRight size={17} /></Link>
                  <Link className="dark-button min-h-11 px-4" href="/silver">Shop Silver</Link>
                  <Link className="outline-button min-h-11 px-4" href="/products">View All Products</Link>
                </div>
              </div>

              <div className="home-hero-dashboard hidden bg-[#101820] p-4 md:p-5 lg:block">
                <div className="home-hero-dashboard-grid grid gap-3 md:grid-cols-[0.92fr_1.08fr]">
                  <Link href={heroGoldPick?.slug ? `/products/${heroGoldPick.slug}` : "/gold"} className="home-hero-pick home-hero-pick-primary">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <p className="text-xs font-black uppercase text-[#725306]">Featured Gold Pick</p>
                        <h2 className="mt-1 text-lg font-black text-[#111827]">{heroGoldPick?.name ?? "Gold bullion bars"}</h2>
                        <p className="mt-1 text-xs font-bold text-[#5f6673]">{heroGoldPick?.weight ?? "1 oz"} / {heroGoldPick?.purity ?? "24k"} / Price updated</p>
                      </div>
                      <ArrowRight className="text-[#b8860b]" size={18} />
                    </div>
                    <div className="home-hero-primary-visual mt-3 grid min-h-[118px] place-items-center rounded border border-[#d8d2c4] bg-[#fbf7ee]">
                      <ProductVisual product={heroGoldPick ?? { name: "1 oz Gold Bar", metalType: "GOLD", productType: "BAR", weight: "1 oz" }} compact />
                    </div>
                  </Link>

                  <div className="home-hero-secondary grid gap-3">
                    <div className="home-market-mini">
                      <p className="text-xs font-black uppercase text-[#d4af37]">Market Reference</p>
                      <div className="mt-2 grid gap-1.5 text-sm">
                        <span><b>Gold</b><strong>$4,100.00</strong></span>
                        <span><b>Silver</b><strong>$60.00</strong></span>
                        <span><b>Platinum</b><strong>$1,640.00</strong></span>
                      </div>
                    </div>
                    <Link href={heroSilverPick?.slug ? `/products/${heroSilverPick.slug}` : "/silver"} className="home-hero-pick">
                      <div className="flex items-center gap-3">
                        <div className="home-hero-pick-thumb grid h-16 w-16 shrink-0 place-items-center overflow-hidden rounded border border-[#d8d2c4] bg-[#fbf7ee]">
                          <ProductVisual product={heroSilverPick ?? { name: "Silver coin selection", metalType: "SILVER", productType: "COIN", weight: "1 oz" }} className="h-full" compact />
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-black uppercase text-[#725306]">Featured Silver Pick</p>
                          <h3 className="mt-1 line-clamp-2 text-sm font-black text-[#111827]">{heroSilverPick?.name ?? "Silver coin selection"}</h3>
                        </div>
                      </div>
                    </Link>
                  </div>
                </div>

                <div className="mt-3 hidden rounded border border-white/10 bg-black/20 p-3 lg:block">
                  <p className="text-xs font-black uppercase text-[#d4af37]">Popular Now</p>
                  <div className="home-popular-grid mt-2 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
                    {popularNow.map(([item, href]) => (
                      <Link key={item} href={href} className="rounded border border-white/15 bg-white/10 px-3 py-2 text-sm font-black text-white transition hover:border-[#d4af37] hover:bg-white/15">
                        {item}
                      </Link>
                    ))}
                  </div>
                </div>
              </div>
            </div>
            <div className="home-category-rail">
              {categoryCards.map(([title, , href, metal]) => (
                <Link key={title} href={href}>
                  <span>{metal === "SILVER" ? "Ag" : "Au"}</span>
                  {title}
                </Link>
              ))}
            </div>
          </div>
        </div>
      </section>

      <div className="home-content-flow flex flex-col">
        <section className="mobile-home-signal-strip order-1 border-b border-[#d8d2c4] bg-[#fbf7ee] lg:hidden">
          <div className="container-grid grid gap-2 py-3">
            <div className="mobile-market-strip rounded-[14px] border border-[#d7ccb4] bg-[#101820] p-3 text-white">
              <p className="text-[11px] font-black uppercase tracking-[0.14em] text-[#d4af37]">Market Reference</p>
              <div className="mt-2 grid grid-cols-3 gap-1.5">
                <span><b>Gold</b>$4,100</span>
                <span><b>Silver</b>$60</span>
                <span><b>Platinum</b>$1,640</span>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-2">
              <div className="mobile-signal-card">
                <ShieldCheck size={16} />
                <span>Secure checkout</span>
              </div>
              <div className="mobile-signal-card">
                <Settings size={16} />
                <span>Manual prices</span>
              </div>
              <div className="mobile-signal-card">
                <PackageCheck size={16} />
                <span>Fulfillment review</span>
              </div>
            </div>
          </div>
        </section>

        {bestRecommendation ? (
          <>
            <MobileRecommendationSummary
              bestRecommendation={bestRecommendation}
              topAlternatives={topAlternatives}
              className="order-2 lg:hidden"
            />
            <RecommendationCenter
              bestRecommendation={bestRecommendation}
              topAlternatives={topAlternatives}
              recommendationPicks={recommendationPicks}
              className="hidden lg:order-6 lg:block"
            />
          </>
        ) : null}

        <section className="home-trust-section hidden border-b border-[#d8d2c4] bg-white lg:order-1 lg:block">
          <div className="container-grid grid gap-2 py-3 md:grid-cols-4">
            {trustItems.map(([Icon, title, copy]) => (
              <div key={title as string} className="home-trust-tile">
                <Icon className="text-[#b8860b]" size={21} />
                <div>
                  <strong>{title as string}</strong>
                  <span>{copy as string}</span>
                </div>
              </div>
            ))}
          </div>
        </section>

        <section className="home-section-band home-category-section order-3 bg-[#fbf7ee] lg:order-2">
          <div className="container-grid">
            <SectionTitle kicker="Shop by Category" title="Find Bullion by Metal and Format" href="/products" action="All Products" />
            <div className="home-category-grid">
              {categoryCards.map(([title, text, href, metal]) => (
                <Link key={title} href={href} className="home-category-card">
                  <span className="home-category-mark">{metal === "SILVER" ? "Ag" : "Au"}</span>
                  <div>
                    <h3>{title}</h3>
                    <p>{text}</p>
                  </div>
                  <ArrowRight size={16} />
                </Link>
              ))}
            </div>
            <div className="home-merchandising-row">
              <div className="home-merch-banner">
                <div>
                  <p>Storefront Catalog</p>
                  <h2>Shop physical bullion by metal, format, weight, and mint.</h2>
                </div>
                <Link href="/products" className="gold-button min-h-10 px-4 text-sm">Browse Catalog <ArrowRight size={16} /></Link>
              </div>
              <div className="home-side-promos">
                {promoCards.map(([title, copy, href]) => (
                  <Link key={title} href={href} className="home-side-promo-card">
                    <strong>{title}</strong>
                    <span>{copy}</span>
                  </Link>
                ))}
              </div>
            </div>
          </div>
        </section>

        <section className="home-section-band home-featured-section order-4 border-y border-[#d8d2c4] bg-[#f6f3ec] lg:order-3">
          <div className="container-grid">
            <div className="home-store-module">
              <div className="home-module-heading">
                <div>
                  <p>Featured Bullion</p>
                  <h2>Popular Gold & Silver Products</h2>
                </div>
                <Link href="/products" className="outline-button min-h-10 px-4 text-sm">View All Products <ArrowRight size={16} /></Link>
              </div>
              <div className="home-featured-tabs" aria-label="Featured product groups">
                {featuredTabs.map((tab, index) => (
                  <span key={tab} className={index === 0 ? "home-featured-tab-active" : ""}>{tab}</span>
                ))}
              </div>
              <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                {featuredProducts.slice(0, 4).map((product) => <ProductCard key={product.id} product={product} />)}
              </div>
            </div>
          </div>
        </section>

        <section className="home-section-band home-metal-shelves hidden bg-white lg:order-4 lg:block">
          <div className="container-grid grid gap-5 lg:grid-cols-2">
            <div className="home-shelf-module">
              <SectionTitle kicker="Gold Bullion" title="Gold Products" href="/gold" action="View Gold" />
              <div className="grid gap-3 sm:grid-cols-2">{gold.map((product) => <ProductCard key={product.id} product={product} />)}</div>
            </div>
            <div className="home-shelf-module">
              <SectionTitle kicker="Silver Bullion" title="Silver Products" href="/silver" action="View Silver" />
              <div className="grid gap-3 sm:grid-cols-2">{silver.map((product) => <ProductCard key={product.id} product={product} />)}</div>
            </div>
          </div>
        </section>

        <section className="home-section-band home-rails-section order-6 border-y border-[#d8d2c4] bg-[#fbf7ee] lg:order-5">
          <div className="container-grid grid gap-4 lg:grid-cols-2">
            <div className="home-rail-module">
              <SectionTitle kicker="Shop by Weight" title="Common Bullion Sizes" />
              <div className="home-chip-rail">
                {weights.map((weight) => (
                  <Link key={weight} href={`/products?search=${encodeURIComponent(weight)}`}>{weight}</Link>
                ))}
              </div>
            </div>
            <div className="home-rail-module">
              <SectionTitle kicker="Shop by Mint" title="Recognized Mints" />
              <div className="home-chip-rail">
                {mints.map((mint) => (
                  <Link key={mint} href={`/products?search=${encodeURIComponent(mint)}`}>{mint}</Link>
                ))}
              </div>
            </div>
          </div>
        </section>

        <section className="home-value-picks-section order-7 relative overflow-hidden border-y border-[#18222f] bg-[#101820] py-8 lg:order-7">
          <div className="container-grid relative">
            <SectionTitle kicker="Value Picks" title="Popular Value Picks" copy="Browse lower-priced physical bullion selections without promotional discount claims." href="/products?sort=price-asc" action="Browse Value Picks" dark />
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {valuePicks.map((product) => <ProductCard key={product.id} product={product} />)}
            </div>
          </div>
        </section>

        <section className="home-section-band home-support-section order-8 bg-[#f6f3ec] lg:order-8">
          <div className="container-grid grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
            <div className="home-support-module">
              <SectionTitle kicker="How It Works" title="Simple Order Flow" copy="This website does not provide trading or investment advice." />
              <div className="grid gap-2 sm:grid-cols-5">
                {["Select product", "Review details", "Checkout securely", "Order reviewed", "Fulfillment coordinated"].map((step, index) => (
                  <div key={step} className="home-step-card">
                    <span>{index + 1}</span>
                    <p>{step}</p>
                  </div>
                ))}
              </div>
            </div>

            <div className="home-support-module">
              <SectionTitle kicker="Support" title="Services & Questions" />
              <div className="grid gap-2 sm:grid-cols-2">
                {[
                  ["IRA / Trust Support", "/ira-trust"],
                  ["Vault Coordination", "/vault-storage"],
                  ["Sell-Back Request", "/sell-back"],
                  ["Service Fee Payment", "/service-fees"]
                ].map(([title, href]) => (
                  <Link key={title} href={href} className="home-service-link">
                    <CreditCard size={18} />
                    <span>{title}</span>
                  </Link>
                ))}
              </div>
              <div className="mt-3 grid gap-2 text-sm">
                {[
                  ["Are prices live market prices?", "No. Product prices are updated manually by our team."],
                  ["What happens after checkout?", "Orders are reviewed by our fulfillment team."],
                  ["Is this investment advice?", "No. This website does not provide trading or investment advice."]
                ].map(([question, answer]) => (
                  <details key={question} className="home-faq-row">
                    <summary>{question}</summary>
                    <p>{answer}</p>
                  </details>
                ))}
              </div>
            </div>
          </div>
        </section>
      </div>
    </main>
  );
}
