import Link from "next/link";
import { getProducts, getBrands, getCategories, getHome } from "@/lib/api";
import { brandHref } from "@/lib/brands";
import OfferCard from "@/components/OfferCard";
import ProductCard from "@/components/ProductCard";
import AutoRail from "@/components/AutoRail";
import PortalHero from "@/components/PortalHero";

function mono(name: string) {
  return name.split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() || "").join("");
}

const BLOGS = [
  { slug: "managing-diabetes-in-everyday-life", title: "Managing Diabetes in Everyday Life", cat: "Chronic Care", img: "/images/blog/managing-diabetes.jpg" },
  { slug: "continuous-glucose-monitoring-explained", title: "Continuous Glucose Monitoring, Explained", cat: "Medical Devices", img: "/images/blog/cgm.jpg" },
  { slug: "skincare-routine-for-a-hot-humid-climate", title: "A Skincare Routine for a Hot, Humid Climate", cat: "Skincare", img: "/images/blog/skincare.jpg" },
];

// Curated subcategories for the "Shop by category" circles — chosen for
// relevance + product coverage, spanning skincare, sun, hair, oral care,
// cosmetics and supplements. Each links to /portal/{parent}/{sub}.
const SHOP_SUBS: { sub: string; label: string }[] = [
  { sub: "skin-care-face-cleanser", label: "Cleansers" },
  { sub: "skin-care-moisturizer", label: "Moisturizers" },
  { sub: "skin-care-anti-aging", label: "Anti-Aging" },
  { sub: "sun-care-sun-protection", label: "Sun Protection" },
  { sub: "hair-care-hair-color", label: "Hair Color" },
  { sub: "dental-tooth-paste", label: "Toothpaste" },
  { sub: "cosmetics-make-up", label: "Makeup" },
  { sub: "food-supplement-omega-3", label: "Omega 3" },
];

const TESTIMONIALS = [
  { n: "Aisha R.", r: "Green Crescent Pharmacy · Dubai", t: "Ordering is effortless and delivery is genuinely same-day. Our shelves are never empty now.", tone: "blush" },
  { n: "Mohammed K.", r: "Al Noor Clinic · Abu Dhabi", t: "Authentic stock at real prices. The account manager knows exactly what we need each month.", tone: "sage" },
  { n: "Priya S.", r: "Wellness Plus · Sharjah", t: "The brand range is excellent and the portal makes reordering our bestsellers a two-minute job.", tone: "lilac" },
];

export const revalidate = 300;

export default async function PortalHome() {
  const [featured, brands, categories, home] = await Promise.all([
    getProducts({ limit: 14 }),
    getBrands(),
    getCategories(),
    getHome(),
  ]);

  // The API resolves the admin's category display image (category_image),
  // then its menu image. Never substitute unrelated static artwork or the
  // first product returned by catalogue sorting for the saved thumbnail.
  const shopCats = SHOP_SUBS.flatMap((s) => {
    const category = categories.find((c) => c.slug === s.sub);
    const parent = categories.find((c) => c.id === category?.parent_id);
    if (!category || !parent) return [];
    return [{ ...s, img: category.image, href: `/portal/${parent.slug}/${category.slug}` }];
  });

  const hasSales = home.bestsellers.products.length >= 4;
  const railProducts = hasSales ? home.bestsellers.products : home.featured.length ? home.featured : featured;

  // Testimonials: admin-managed via /home, falling back to the built-in set.
  const reviewTones = ["blush", "sage", "lilac", "sky", "sand"];
  const reviews = home.testimonials.length
    ? home.testimonials.map((t, i) => ({ n: t.name || "", r: t.role || "", t: t.text || "", tone: reviewTones[i % reviewTones.length] }))
    : TESTIMONIALS;

  return (
    <>
      {/* Hero — rotating brand banners (admin-managed via /home, with fallback) */}
      <PortalHero banners={home.banners} />

      {/* Benefits */}
      <section className="pb-benefits">
        <div className="pb-shell pb-benefits-in">
          {[
            ["Same-day dispatch", "Across all seven emirates"],
            ["100% authentic", "Direct from manufacturers"],
            ["Great pricing", "Volume & recurring discounts"],
            ["Dedicated support", "Your own account manager"],
          ].map(([t, s]) => (
            <div className="pb-benefit" key={t}>
              <span className="pb-benefit-ic"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M12 3l7 3v6c0 5-3 7.5-7 9-4-1.5-7-4-7-9V6l7-3Z" /><path d="m9 12 2 2 4-4" strokeLinecap="round" strokeLinejoin="round" /></svg></span>
              <div><strong>{t}</strong><span>{s}</span></div>
            </div>
          ))}
        </div>
      </section>

      {/* Trade offers strip — admin-managed (Trade Offers), with countdowns */}
      {home.offers.length > 0 && (
        <section className="pb-section pb-offers-strip">
          <div className="pb-shell">
            <div className="pb-section-head pb-section-head--row">
              <div>
                <span className="pb-section-kicker">Trade offers</span>
                <h2>{home.offers.find((o) => o.campaign)?.campaign || "This month's trade offers"}</h2>
              </div>
              <Link href="/portal/offers" className="pb-btn pb-btn--ghost">All offers →</Link>
            </div>
            <div className="pb-offers-row">
              {home.offers.map((o) => <OfferCard o={o} key={o.slug} />)}
            </div>
          </div>
        </section>
      )}

      {/* Shop by category — curated subcategories */}
      <section className="pb-section pb-section--tint" id="categories">
        <div className="pb-shell">
          <div className="pb-section-head">
            <span className="pb-section-kicker">Categories</span>
            <h2>Shop by category</h2>
            <p>Popular picks across skincare, sun care, hair, oral care and supplements.</p>
          </div>
        </div>
        <div className="pb-shell">
          <div className="pb-catcircles pb-catcircles--row">
            {shopCats.map((c) => (
              <Link
                href={c.href}
                className="pb-catcircle"
                key={c.sub}
              >
                <span className="pb-catcircle-img">
                  {c.img ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={c.img} alt={c.label} width={170} height={170} loading="lazy" />
                  ) : (
                    <span className="pb-catcircle-placeholder" aria-hidden="true">{mono(c.label)}</span>
                  )}
                </span>
                <strong>{c.label}</strong>
                <span className="pb-catcircle-sub">Shop now</span>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* Bestsellers — auto-sliding product rail */}
      <section className="pb-section">
        <div className="pb-shell">
          {/* Real sales data only: the "Bestsellers" heading is used only when there
              are enough orders to rank; otherwise this rail is honestly labelled. */}
          <div className="pb-section-head">
            <span className="pb-section-kicker">{hasSales ? "Trending now" : "Featured"}</span>
            <h2>{hasSales ? (home.bestsellers.days <= 30 ? "Bestsellers this month" : "Bestsellers this quarter") : "Featured products"}</h2>
            <p>{hasSales ? "Ranked by units ordered by our trade partners." : "A selection from across our brands."}</p>
          </div>
        </div>
        <div className="pb-shell">
          <AutoRail speed={28}>
            {railProducts.map((p) => (
              <ProductCard p={p} key={p.id} />
            ))}
          </AutoRail>
        </div>
      </section>

      {/* Brands — with logos */}
      <section className="pb-section pb-section--tint" id="offers">
        <div className="pb-shell">
          <div className="pb-section-head">
            <span className="pb-section-kicker">Authorised distribution</span>
            <h2>Brands we carry</h2>
            <p>Trusted global names, sourced direct — with more added every season.</p>
          </div>
          <div className="pb-brandstrip">
            {brands.slice(0, 18).map((b) => (
              <Link href={brandHref(b.slug)} className="pb-brandstrip-item" title={b.name} key={b.slug}>
                {b.logo ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img className="pb-brandstrip-logo" src={b.logo} alt={b.name} loading="lazy" />
                ) : (
                  <>
                    <span className="pb-brandstrip-mono">{mono(b.name)}</span>
                    <span className="pb-brandstrip-name">{b.name}</span>
                  </>
                )}
              </Link>
            ))}
          </div>
          <div style={{ textAlign: "center", marginTop: 32 }}>
            <Link href="/portal/brands" className="pb-btn pb-btn--ghost">View all brands</Link>
          </div>
        </div>
      </section>

      {/* From the journal — 3 blogs */}
      <section className="pb-section">
        <div className="pb-shell">
          <div className="pb-section-head">
            <span className="pb-section-kicker">Health journal</span>
            <h2>Advice from our pharmacists</h2>
            <p>Practical, evidence-based reads for you and your customers.</p>
          </div>
          <div className="pb-bloglist">
            {BLOGS.map((b) => (
              <Link href={`/blog/${b.slug}`} className="pb-blogcard" key={b.slug}>
                <span className="pb-blogcard-media">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={b.img} alt={b.title} loading="lazy" />
                </span>
                <span className="pb-blogcard-body">
                  <span className="pb-blogcard-cat">{b.cat}</span>
                  <strong className="pb-blogcard-title">{b.title}</strong>
                  <span className="pb-blogcard-link">Read article →</span>
                </span>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* Testimonials */}
      <section className="pb-section pb-section--tint">
        <div className="pb-shell">
          <div className="pb-section-head">
            <span className="pb-section-kicker">Loved by our customers</span>
            <h2>Trusted by pharmacies UAE-wide</h2>
            <p>Why partners across the Emirates reorder with Awafi.</p>
          </div>
          <div className="pb-reviews">
            {reviews.map((tm) => (
              <figure className="pb-review" key={tm.n}>
                <div className="pb-review-stars" aria-label="Rated 5 out of 5">
                  {Array.from({ length: 5 }).map((_, s) => (
                    <svg key={s} viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M12 2.5l2.9 5.9 6.5.9-4.7 4.6 1.1 6.5L12 17.8 6.2 20.9l1.1-6.5L2.6 9.8l6.5-.9L12 2.5z" /></svg>
                  ))}
                </div>
                <blockquote>“{tm.t}”</blockquote>
                <figcaption>
                  <span className={`pb-review-avatar pb-tone-${tm.tone}`}>{tm.n.slice(0, 1)}</span>
                  <span className="pb-review-who"><strong>{tm.n}</strong><span>{tm.r}</span></span>
                </figcaption>
              </figure>
            ))}
          </div>
        </div>
      </section>

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