import Link from "next/link";
import { formatDateTime, formatRelativeAge } from "@/lib/utils";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import {
  BadgeCheck,
  CheckCircle2,
  ChevronRight,
  CircleDollarSign,
  Flame,
  Link2,
  Play,
  Recycle,
  Repeat,
  Ruler,
  Shield,
  Waves,
  type LucideIcon,
} from "lucide-react";

import { catalogApi } from "@/lib/api/catalog";
import { ApiException } from "@/lib/api/client";
import type { ApiProductDetail, ApiProductReference } from "@/lib/api/types";
import SafeImage from "@/components/ui/SafeImage";
import ProductGallery from "@/components/products/ProductGallery";
import ProductTabs, { type ProductTab } from "@/components/products/ProductTabs";
import ProductRfqBuilder from "@/components/products/ProductRfqBuilder";
import PriceTrendChart, { MIN_TREND_POINTS } from "@/components/products/PriceTrendChart";
import ForPriceForm from "@/components/products/ForPriceForm";
import ExPriceBreakup from "@/components/products/ExPriceBreakup";
import RfqModeTabs from "@/components/products/RfqModeTabs";
import WatchlistButton from "@/components/products/WatchlistButton";
import SpecTable from "@/components/products/SpecTable";
import { formatAmount, formatPrice, priceHeadline } from "@/lib/pricing/forPrice";
import { PRICE_DISCLAIMER } from "@/lib/static/productDetail";

type Props = {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ city?: string; state?: string; qty?: string; offer?: string }>;
};

/** Icons for a family's feature keys (B11); unknown keys get a check. */
const FEATURE_ICONS: Record<string, LucideIcon> = {
  strength: Shield,
  ductility: Waves,
  weld: Flame,
  cost: CircleDollarSign,
  recycle: Recycle,
  precision: Ruler,
  bend: Repeat,
};

/** For payloads cached before `reference` shipped. */
const EMPTY_REFERENCE: ApiProductReference = {
  family: "generic",
  label: "Product",
  standard: null,
  overview: "Specifications as listed by the seller. Ask for the mill test certificate with your quote.",
  features: [],
  quick_specs: [],
  sections: [],
  applications: [],
  packaging: [],
  certifications: [],
};

/** Section nav built from what this product's family actually has. */
function buildTabs(reference: ApiProductReference): ProductTab[] {
  return [
    { id: "overview", label: "Overview" },
    { id: "variants", label: "Variants & RFQ" },
    ...reference.sections.map((section) => ({
      id: section.id,
      label: section.id === "specifications" ? "Specifications" : section.title,
    })),
    ...(reference.applications.length ? [{ id: "applications", label: "Applications" }] : []),
    { id: "packaging-delivery", label: "Packaging & Delivery" },
    ...(reference.certifications.length ? [{ id: "certifications", label: "Certifications" }] : []),
  ];
}

/**
 * `revalidate` rather than `no-store`: this is called twice per request — once
 * from `generateMetadata` and once from the page — and only a cacheable fetch
 * lets Next collapse the pair into a single upstream call. 60s matches the
 * window already used for the /prices listing.
 *
 * Tagged as well as timed, because `revalidatePath` cannot reach this: the page
 * is rendered per `?offer=` / `?city=` combination and that call ignores search
 * params, so a seller changing what their listing publishes would have waited
 * out the 60s on every variant. `revalidateTag` drops them all at once.
 */
async function loadProduct(slug: string, city?: string, state?: string, offer?: number) {
  try {
    return await catalogApi.product(
      slug,
      { city, state, offer },
      { next: { revalidate: 60, tags: [`product-${slug}`] } }
    );
  } catch (err) {
    if (err instanceof ApiException && err.status === 404) return null;
    throw err;
  }
}

async function loadSimilar(product: ApiProductDetail) {
  try {
    const res = await catalogApi.products(
      { category_id: product.category?.id, per_page: 5 },
      { next: { revalidate: 300 } }
    );
    return res.data.filter((item) => item.id !== product.id).slice(0, 4);
  } catch {
    return [];
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const product = await loadProduct(slug);
  if (!product) return { title: "Product Not Found – Biznie" };
  return {
    title: `${product.name} – Biznie`,
    description:
      product.description?.slice(0, 160) || `Buy ${product.name} at best B2B prices on Biznie.`,
  };
}

export default async function ProductDetailPage({ params, searchParams }: Props) {
  const { slug } = await params;
  const { city, state, qty, offer: offerParam } = await searchParams;

  const product = await loadProduct(
    slug,
    city,
    state,
    offerParam ? Number(offerParam) : undefined
  );
  if (!product) notFound();

  const similar = await loadSimilar(product);
  // Specs for this product's family — TMT reads IS 1786, pipes IS 4923 (B11).
  const reference = product.reference ?? EMPTY_REFERENCE;

  const categoryName = product.category?.name || "General";
  const unitName = product.unit?.name || "Ton";
  const pricing = product.pricing;
  const offer = product.offer;

  // The seller decides which of the three prices this listing publishes;
  // `priceHeadline` holds that rule so the offers grid names the same listing's
  // price the same way. Defaulted for payloads cached before `display` shipped.
  const display = product.display ?? {
    show_basic_price: false,
    show_ex_price: true,
    show_for_price: true,
    show_fob_price: false,
    for_price_city: null,
  };
  const {
    show_ex_price: showEx,
    show_for_price: showFor,
    show_basic_price: showBasic = false,
  } = display;

  // The city the goods load from: names the Ex-Works/Basic price, and is shown
  // as the city of manufacturing in the spec strip.
  const originCity = offer?.loading_city ?? null;

  const headline = priceHeadline(
    product.display,
    {
      exWorks: pricing?.ex_works_price ?? null,
      forPrice: pricing?.for_price ?? null,
      basic: pricing?.base_price ?? null,
    },
    originCity,
    pricing?.price_mode
  );
  // Ex-Works until the buyer picks a delivery city (B08): no freight, no F.O.R.
  const exWorksMode = pricing?.price_mode === "ex_works";
  const showForNow = showFor && !exWorksMode;

  // The breakup is the F.O.R build-up; with both its ends hidden there is
  // nothing left in it worth a border and a heading.
  const showBreakup = Boolean(pricing) && (showEx || showFor || showBasic);

  const gallery = product.thumbnail
    ? [product.thumbnail, ...product.images.filter((img) => img && img !== product.thumbnail)]
    : product.images;
  const resolvedGallery = gallery.length > 0 ? gallery : ["/logo.png"];

  // "8 MM" etc. — the seller's first live variation is what the page prices by
  // default, so it is the size the numbers above belong to.
  const defaultVariation = product.variations.find(
    (variation) => variation.is_selected === 1 && variation.is_brand_selling === 1
  );
  const defaultSizeEntry = defaultVariation?.value?.[0];
  const defaultSize = defaultSizeEntry
    ? [defaultSizeEntry.value, defaultSizeEntry.unit?.short_name].filter(Boolean).join(" ")
    : null;

  const quickSpecs: { label: string; value: string }[] = [
    ...(defaultSize ? [{ label: "Default Size", value: defaultSize }] : []),
    ...(product.min_order_qty > 0
      ? [{ label: "Min. Order", value: `${product.min_order_qty} ${unitName}` }]
      : []),
    ...reference.quick_specs.slice(0, 3),
    ...(originCity ? [{ label: "City of Manufacturing", value: originCity }] : []),
  ];

  const priceHistory = product.price_history.map((point) => ({
    label: point.label,
    value: point.price,
  }));

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
        {/* Breadcrumb */}
        <nav className="mb-5 flex flex-wrap items-center gap-1.5 text-xs text-gray-400">
          <Link href="/" className="hover:text-[#CC1414]">
            Home
          </Link>
          <ChevronRight size={12} />
          <Link href="/products" className="hover:text-[#CC1414]">
            Products
          </Link>
          <ChevronRight size={12} />
          <span>{categoryName}</span>
          {product.sub_category?.name && (
            <>
              <ChevronRight size={12} />
              <span>{product.sub_category.name}</span>
            </>
          )}
          <ChevronRight size={12} />
          <Link href={`/products/${product.slug}/sellers`} className="hover:text-[#CC1414]">
            {product.name}
          </Link>
          <ChevronRight size={12} />
          <span className="font-medium text-gray-600">
            {offer?.brand?.name || offer?.seller?.name || "Details"}
          </span>
        </nav>

        {/* Hero: gallery + summary + price card */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-12">
          <div className="lg:col-span-4">
            <ProductGallery
              images={resolvedGallery}
              alt={product.name}
              videoPoster={resolvedGallery[0]}
            />
          </div>

          <div className="lg:col-span-5">
            <div className="mb-3 flex items-start justify-between gap-3">
              <h1 className="text-2xl font-black text-gray-900 md:text-3xl">{product.name}</h1>
              {/* A bookmark is keyed on the seller listing, so the button only
                  exists while an offer is being shown. */}
              {offer && (
                <WatchlistButton
                  commodityProductId={product.id}
                  sellerProductId={offer.seller_product_id}
                  returnTo={`/products/${product.slug}`}
                />
              )}
            </div>

            <div className="mb-4 flex flex-wrap items-center gap-2">
              {product.hsn_code && (
                <span className="rounded-md bg-gray-100 px-2.5 py-1 text-xs font-semibold text-gray-600">
                  HSN {product.hsn_code}
                </span>
              )}
              {offer?.brand?.name && (
                <span className="rounded-md bg-gray-100 px-2.5 py-1 text-xs font-semibold text-gray-600">
                  {offer.brand.name}
                </span>
              )}
              <span className="inline-flex items-center gap-1 rounded-md bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700">
                <BadgeCheck size={13} /> Verified Product
              </span>
            </div>

            <p className="mb-6 whitespace-pre-line text-sm leading-relaxed text-gray-500">
              {/* The family's own uses, not one line for every product (B11). */}
              {product.description ||
                (reference.applications.length
                  ? `${product.name}${reference.standard && reference.standard !== "Lot analysis" ? ` (${reference.standard})` : ""} — used for ${reference.applications
                      .slice(0, 3)
                      .map((a) => a.charAt(0).toLowerCase() + a.slice(1))
                      .join(", ")}.`
                  : reference.overview)}
            </p>

            {/* Default size leads, then MOQ and the dimensional specs, and the
                city the goods are manufactured in closes the strip. */}
            <div className="mb-5 grid grid-cols-2 gap-4 border-y border-gray-200 py-4 sm:grid-cols-3">
              {quickSpecs.map((spec) => (
                <div key={spec.label}>
                  <div className="mb-1 text-xs text-gray-400">{spec.label}</div>
                  <div className="text-sm font-semibold text-gray-900">{spec.value}</div>
                </div>
              ))}
            </div>

            <div className="mb-6 flex flex-wrap gap-x-5 gap-y-2">
              {reference.features.slice(0, 3).map((feature) => (
                <span key={feature.key} className="flex items-center gap-1.5 text-xs text-gray-500">
                  <Link2 size={13} className="text-[#CC1414]" />
                  {feature.label}
                </span>
              ))}
            </div>

            {/* The variant builder is the RFQ path whenever a seller offer is
                live; without one there is nothing to price, so the CTA falls
                back to the manual enquiry form. */}
            <div className="flex flex-wrap gap-3">
              <a
                href={pricing ? "#variants" : `/rfq/new?product_id=${product.id}`}
                className="rounded-lg bg-[#CC1414] px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-[#a30f0f]"
              >
                Get Best Price (RFQ)
              </a>
              <a
                href="#get-best-price"
                className="rounded-lg border border-[#CC1414] bg-white px-6 py-2.5 text-sm font-semibold text-[#CC1414] transition hover:bg-red-50"
              >
                Check F.O.R Price
              </a>
            </div>
          </div>

          {/* Best F.O.R price */}
          <div className="lg:col-span-3">
            <div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
              <p className="mb-3 text-center text-xs font-semibold text-gray-500">
                {headline.label}
              </p>

              {pricing && headline.amount !== null ? (
                <>
                  <p className="text-center text-2xl font-black text-emerald-600">
                    {formatPrice(headline.amount)}
                    <span className="text-sm font-medium text-gray-400"> / {unitName}</span>
                  </p>
                  {/* Only the F.O.R number depends on where it is going. Until
                      the buyer names a city the price is quoted to the seller's
                      first city, so say which rather than let the heading imply
                      it is theirs. */}
                  {exWorksMode ? (
                    <p className="mt-2 text-center text-xs text-gray-500">
                      Price at the seller&apos;s gate — select your delivery city for the F.O.R (doorstep) price
                    </p>
                  ) : (
                    showFor && (
                      <p className="mt-2 text-center text-xs text-gray-500">
                        Delivery City: {product.delivery.city ?? display.for_price_city}
                      </p>
                    )
                  )}
                  {(pricing.price_updated_at || pricing.last_updated) && (
                    <p className="text-center text-[11px] text-gray-400">
                      Updated {pricing.price_updated_at ? formatRelativeAge(pricing.price_updated_at) : pricing.last_updated}
                      {pricing.valid_till && <> · Valid till {formatDateTime(pricing.valid_till)}</>}
                    </p>
                  )}
                </>
              ) : (
                <>
                  <p className="text-center text-2xl font-black text-gray-900">On Request</p>
                  <p className="mt-2 text-center text-xs text-gray-500">
                    {pricing
                      ? "This seller has not published a price for this product."
                      : "No live seller offer for this product right now."}
                  </p>
                  {/* No valid offer: never show a stale price as live — only the
                      way to get a fresh one (B09). */}
                  <Link
                    href={`/rfq/new?product_id=${product.id}`}
                    className="mt-3 block rounded-lg bg-[#CC1414] px-4 py-2 text-center text-sm font-semibold text-white hover:bg-[#a30f0f]"
                  >
                    Get quote
                  </Link>
                  <p className="mt-2 text-center text-[11px] text-gray-400">
                    Verified sellers quote within 30 minutes.
                  </p>
                </>
              )}

              {showBreakup && pricing && (
                <div className="mt-4 border-t border-gray-100 pt-4">
                  <p className="mb-3 text-xs font-semibold text-gray-700">
                    Price Breakup{" "}
                    <span className="font-normal text-gray-400">(Per {unitName})</span>
                  </p>
                  <dl className="space-y-2 text-xs">
                    {showBasic && (
                      <div className="flex justify-between">
                        <dt className="text-gray-500">
                          Basic Price{originCity ? ` (${originCity})` : ""}
                        </dt>
                        <dd className="font-medium text-gray-900">
                          {formatAmount(pricing.base_price)}
                        </dd>
                      </div>
                    )}
                    {showEx && (
                      <ExPriceBreakup pricing={pricing} unit={unitName} originCity={originCity} />
                    )}
                    {/* F.O.R = Ex-Works + freight. The extra charges are already
                        inside the Ex-Works price above; listing them again here
                        made the rows add up to more than the total. */}
                    {showForNow && (
                      <>
                        <div className="flex justify-between">
                          <dt className="text-gray-500">Freight to {display.for_price_city ?? product.delivery.city}</dt>
                          <dd className="font-medium text-gray-900">
                            {formatAmount(pricing.freight_charges)}
                          </dd>
                        </div>
                        <div className="flex justify-between border-t border-gray-100 pt-2">
                          <dt className="font-semibold text-emerald-600">
                            F.O.R Price (All Inclusive)
                            {display.for_price_city ? ` — ${display.for_price_city}` : ""}
                          </dt>
                          <dd className="font-bold text-emerald-600">
                            {formatAmount(pricing.for_price)}
                          </dd>
                        </div>
                      </>
                    )}
                  </dl>

                  <p className="mt-3 text-[11px] text-gray-400">
                    Includes GST {pricing.gst}% ({formatAmount(pricing.tax_amount)}), loading and
                    insurance.
                  </p>
                </div>
              )}

              {offer && offer.sellers_count > 1 && (
                <Link
                  href={`/products/${product.slug}/sellers`}
                  className="mt-3 flex items-center justify-center gap-1 text-xs font-semibold text-[#CC1414] hover:underline"
                >
                  Compare all {offer.sellers_count} offers
                  <ChevronRight size={12} />
                </Link>
              )}
            </div>
          </div>
        </div>

        {/* Section navigation */}
        <div className="mt-8">
          <ProductTabs tabs={buildTabs(reference)} />
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          {/* Left column */}
          <div className="space-y-6 lg:col-span-2">
            <section
              id="overview"
              className="scroll-mt-28 rounded-2xl border border-gray-100 bg-white p-6 shadow-sm"
            >
              <h2 className="mb-3 font-bold text-gray-900">Product Overview</h2>
              <p className="mb-6 text-sm leading-relaxed text-gray-500">
                {product.description || reference.overview}
              </p>
              {reference.features.length > 0 && (
                <div className="grid grid-cols-2 gap-4 sm:grid-cols-5">
                  {reference.features.map(({ key, label }) => {
                    const Icon = FEATURE_ICONS[key] ?? CheckCircle2;
                    return (
                      <div key={key} className="text-center">
                        <Icon size={22} className="mx-auto mb-2 text-[#CC1414]" strokeWidth={1.5} />
                        <span className="text-xs text-gray-600">{label}</span>
                      </div>
                    );
                  })}
                </div>
              )}
            </section>

            {/* Variant selection sits in the wide column: it carries a
                quantity table that will not fit the sidebar, and it is the
                entry point to the RFQ. */}
            <section
              id="variants"
              className="scroll-mt-28 rounded-2xl border border-gray-100 bg-white p-6 shadow-sm"
            >
              <h2 className="mb-1 font-bold text-gray-900">Select Variants &amp; Request Quote</h2>
              <p className="mb-4 text-xs text-gray-500">
                Pick quality, packaging and one or more sizes with quantities — we&apos;ll take the
                selection into your RFQ.
              </p>
              {pricing ? (
                <RfqModeTabs
                  defaultMode={qty || city ? "total" : "variants"}
                  totalQuantity={
                    <div className="rounded-xl border border-gray-100 bg-gray-50 p-4">
                      <h3 className="mb-1 font-bold text-[#CC1414]">Ready to Get Best Price?</h3>
                      <p className="mb-4 text-xs text-gray-500">
                        Book the whole quantity when the sizes are not confirmed yet — enter your
                        requirement and get the best F.O.R price from multiple sellers.
                      </p>
                      <ForPriceForm
                        slug={product.slug}
                        unit={unitName}
                        destinations={product.delivery.destinations}
                        currentCity={product.delivery.city}
                        quantity={qty ?? ""}
                        productId={product.id}
                        minOrderQty={product.min_order_qty}
                      />
                    </div>
                  }
                  variants={
                    <ProductRfqBuilder
                      productId={product.id}
                      slug={product.slug}
                      name={product.name}
                      thumbnail={product.thumbnail}
                      minOrderQty={product.min_order_qty}
                      unit={unitName}
                      brand={offer?.brand ?? null}
                      originCity={originCity}
                      deliveryCity={product.delivery.city}
                      variations={product.variations}
                      quality={product.quality}
                      packaging={product.packaging}
                      pricing={pricing}
                      display={display}
                    />
                  }
                />
              ) : (
                <div className="space-y-3">
                  <p className="text-xs text-gray-400">
                    Variants will be listed once a seller publishes a live offer.
                  </p>
                  <Link
                    href={`/rfq/new?product_id=${product.id}`}
                    className="inline-block rounded-lg bg-[#CC1414] px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-[#a30f0f]"
                  >
                    Raise an RFQ
                  </Link>
                </div>
              )}
            </section>

            {reference.sections.map((section) => (
              <section
                key={section.id}
                id={section.id}
                className="scroll-mt-28 rounded-2xl border border-gray-100 bg-white p-6 shadow-sm"
              >
                <h2 className="mb-4 font-bold text-gray-900">
                  {section.title}
                  {section.subtitle && <span className="font-normal text-gray-400"> ({section.subtitle})</span>}
                </h2>
                <SpecTable
                  columns={section.columns}
                  rows={section.rows}
                  minWidth={section.columns.length <= 2 ? 360 : section.columns.length === 3 ? 440 : 520}
                />
                {section.note && <p className="mt-3 text-xs text-gray-400">{section.note}</p>}
              </section>
            ))}

            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <section
                id="packaging-delivery"
                className="scroll-mt-28 rounded-2xl border border-gray-100 bg-white p-6 shadow-sm"
              >
                <h2 className="mb-4 font-bold text-gray-900">Packaging &amp; Dispatch</h2>
                <ul className="space-y-2.5">
                  {product.packaging.length > 0 && (
                    <li className="flex gap-2 text-xs leading-relaxed text-gray-600">
                      <span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-gray-400" />
                      Packaging:{" "}
                      {product.packaging
                        .map((item) => (item.charge > 0 ? `${item.name} (+${item.charge})` : item.name))
                        .join(" / ")}
                    </li>
                  )}
                  {/* The listing's own packaging, when it has any, replaces the family default. */}
                  {reference.packaging
                    .filter((point) => !(product.packaging.length > 0 && point.startsWith("Packaging:")))
                    .map((point) => (
                    <li key={point} className="flex gap-2 text-xs leading-relaxed text-gray-600">
                      <span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-gray-400" />
                      {point}
                    </li>
                  ))}
                </ul>
              </section>

              <section
                id="certifications"
                className="scroll-mt-28 rounded-2xl border border-gray-100 bg-white p-6 shadow-sm"
              >
                <h2 className="mb-4 font-bold text-gray-900">Certifications &amp; Quality</h2>
                <ul className="space-y-2.5">
                  {reference.certifications.map((point) => (
                    <li key={point} className="flex gap-2 text-xs leading-relaxed text-gray-600">
                      <span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-gray-400" />
                      {point}
                    </li>
                  ))}
                </ul>
              </section>
            </div>

          </div>

          {/* Right column */}
          <div className="space-y-6">
            {/* Only the product's own video — every page used to show an
                HR-sheet video title over the product photo. */}
            {product.video_url && (
              <a
                href={product.video_url}
                target="_blank"
                rel="noopener noreferrer"
                className="block rounded-2xl border border-gray-100 bg-white p-5 shadow-sm transition hover:border-[#CC1414]/30"
              >
                <h3 className="mb-3 font-bold text-gray-900">Product Video</h3>
                <div className="relative aspect-video overflow-hidden rounded-xl bg-gray-900">
                  <SafeImage
                    src={resolvedGallery[0]}
                    alt={`${product.name} video`}
                    fill
                    sizes="(min-width: 1024px) 30vw, 100vw"
                    className="object-cover opacity-70"
                  />
                  <span className="absolute inset-0 flex items-center justify-center">
                    <span className="flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow">
                      <Play size={18} className="ml-0.5 fill-gray-900 text-gray-900" />
                    </span>
                  </span>
                </div>
                <p className="mt-3 text-xs font-medium text-gray-700">Watch: {product.name}</p>
              </a>
            )}

            {priceHistory.length >= MIN_TREND_POINTS && (
              <PriceTrendChart
                points={priceHistory}
                unit={unitName}
                title="Price Trend (Last 30 Days)"
                subtitle={`Seller base price, ₹/${unitName}`}
              />
            )}

            {reference.applications.length > 0 && (
            <section
              id="applications"
              className="scroll-mt-28 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm"
            >
              <h3 className="mb-4 font-bold text-gray-900">Applications</h3>
              <div className="flex gap-4">
                <ul className="flex-1 space-y-2.5">
                  {reference.applications.map((application) => (
                    <li key={application} className="flex items-start gap-2 text-xs text-gray-600">
                      <CheckCircle2 size={13} className="mt-0.5 shrink-0 text-emerald-600" />
                      {application}
                    </li>
                  ))}
                </ul>
                <div className="relative hidden aspect-square w-32 shrink-0 overflow-hidden rounded-xl bg-gray-50 sm:block">
                  <SafeImage
                    src={resolvedGallery[1] || resolvedGallery[0]}
                    alt=""
                    fill
                    sizes="128px"
                    className="object-contain"
                  />
                </div>
              </div>
            </section>
            )}
          </div>
        </div>

        {/* Similar products */}
        {similar.length > 0 && (
          <div className="mt-10">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="font-bold text-gray-900">Similar Products You May Like</h2>
              <Link
                href="/products"
                className="flex items-center gap-1 text-xs font-medium text-gray-500 hover:text-[#CC1414]"
              >
                View All Products <ChevronRight size={13} />
              </Link>
            </div>

            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {similar.map((item) => (
                <div
                  key={item.id}
                  className="flex gap-3 rounded-2xl border border-gray-100 bg-white p-3 shadow-sm"
                >
                  <div className="relative h-20 w-20 shrink-0 overflow-hidden rounded-xl bg-gray-50">
                    <SafeImage
                      src={item.thumbnail || "/logo.png"}
                      alt={item.name}
                      fill
                      sizes="80px"
                      className="object-contain"
                    />
                  </div>
                  <div className="flex min-w-0 flex-1 flex-col">
                    <h3 className="truncate text-sm font-semibold text-gray-900">{item.name}</h3>
                    <p className="mb-2 text-xs text-gray-400">
                      {item.category?.name || categoryName}
                    </p>
                    <p className="text-xs text-gray-500">
                      From{" "}
                      <span className="font-bold text-gray-900">
                        {formatPrice(item.base_price)}
                      </span>{" "}
                      / {item.unit?.name || unitName}
                    </p>
                    <Link
                      href={`/products/${item.slug || item.id}/sellers`}
                      className="mt-auto rounded-lg border border-gray-200 py-1.5 text-center text-xs font-medium text-gray-700 transition hover:bg-gray-50"
                    >
                      View Details
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        <p className="mt-8 text-center text-[11px] text-gray-400">{PRICE_DISCLAIMER}</p>
      </div>
    </div>
  );
}
