import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { getBrand } from "@/lib/api";
import BrandProducts from "@/components/BrandProducts";
import { BRAND_HTML } from "@/content/brandIndex";
import MarketingRuntime from "@/components/MarketingRuntime";

export const revalidate = 300;

/** Same header on every brand page (bespoke or plain): logo, name, count and a jump to the products. */
function BrandBar({ name, logo, count, h1 = true }: { name: string; logo?: string | null; count: number; h1?: boolean }) {
  const mono = name.split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() || "").join("");
  return (
    <section className="pb-brandbar">
      <div className="pb-shell pb-brandbar-in">
        <div className="pb-brandbar-logo">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          {logo ? <img src={logo} alt={`${name} logo`} /> : <span>{mono}</span>}
        </div>
        <div className="pb-brandbar-copy">
          <nav className="pb-crumbs" aria-label="Breadcrumb">
            <Link href="/portal">Home</Link><span>/</span>
            <Link href="/portal/brands">Brands</Link><span>/</span>
            <span className="pb-crumbs-current">{name}</span>
          </nav>
          {h1 ? <h1>{name}</h1> : <div className="pb-brandbar-title">{name}</div>}
          <p>{count} {count === 1 ? "product" : "products"} available for wholesale across the UAE</p>
        </div>
        {count > 0 && (
          <a href="#brand-products" className="pb-btn pb-btn--primary">Shop the range ↓</a>
        )}
      </div>
    </section>
  );
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const data = await getBrand(slug);
  const name = data?.brand.name || "Brand";
  const n = data?.products.length ?? 0;
  return {
    title: `${name} Wholesale UAE — ${n} Products | Awafi Drugstore`,
    description: `Shop ${n} ${name} products wholesale on the Awafi B2B portal — trade pricing and delivery to pharmacies and clinics across the UAE.`,
    alternates: { canonical: `/portal/brand/${slug}` },
  };
}

export default async function PortalBrandPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;

  // Bespoke animated brand design — rendered INSIDE the portal chrome so the
  // visitor stays in the e-commerce portal (breadcrumb/back-links repointed to
  // the portal brands index).
  const bespoke = BRAND_HTML[slug];
  if (bespoke) {
    const html = bespoke.split('href="/brands"').join('href="/portal/brands"');
    const data = await getBrand(slug);
    const products = data?.products ?? [];
    return (
      <>
        <BrandBar name={data?.brand.name ?? slug} logo={data?.brand.logo} count={products.length} h1={false} />
        <link rel="stylesheet" href="/css/pages/brand-products.css" />
        <link rel="stylesheet" href="/css/pages/product-modal.css" />
        <link rel="stylesheet" href={`/css/pages/${slug}.css`} />
        <MarketingRuntime html={html} scriptSrc={`/js/page-brand--${slug}.js`} />
        <BrandProducts products={products} brandName={data?.brand.name ?? slug} />
        <div className="pb-section-spacer" />
      </>
    );
  }

  const data = await getBrand(slug);
  if (!data) notFound();
  const { brand, products } = data;
  const storyParas = (brand.story || "")
    .split(/\n{2,}|\r\n\r\n/)
    .map((s) => s.trim())
    .filter(Boolean);

  return (
    <>
      <BrandBar name={brand.name} logo={brand.logo} count={products.length} />

      {storyParas.length > 0 && (
        <section className="pb-brandstory">
          <div className="pb-shell">
            <div className="pb-brandstory-in">
              <div className="pb-brandstory-head">
                {brand.story_headline && <h2>{brand.story_headline}</h2>}
              </div>
              <div className="pb-brandstory-body">
                {storyParas.map((para, i) => (
                  <p key={i}>{para}</p>
                ))}
              </div>
            </div>
          </div>
        </section>
      )}

      {products.length > 0 ? (
        <BrandProducts products={products} brandName={brand.name} />
      ) : (
        <div className="pb-shell">
          <div className="pb-empty"><p>No products listed for {brand.name} yet. Please check back soon.</p></div>
        </div>
      )}

      <div className="pb-section-spacer" />
    </>
  );
}
