import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Fragment, type ReactNode } from 'react';
import type { Brand, EventSummary, Testimonial } from '@/types';
import { buildPageMetadata } from '@/lib/public/page-metadata';
import { getPublicSiteSettings } from '@/lib/public/site-settings';
import { isGoldLine } from '@/lib/public/gold-lines';
import { pageImageUrl } from '@/lib/media/display-url';
import { routes } from '@/lib/routes';
import { orNull } from '@/lib/api/client';
import { getTestimonials } from '@/lib/api/services/content';
import { orderHomeTestimonials } from '@/lib/home/testimonials';
import { getCities, getUpcomingEvents } from '@/lib/api/services/events';
import { isPublicEventCity } from '@/lib/events/public-cities';
import { getHomePage } from '@/lib/api/services/pages';
import { getFeaturedInterview } from '@/lib/api/services/spotlight';
import { LongArrowRightIcon } from '@/components/icons/common';
import EventCard from '@/components/events/EventCard';
import FeatureItem from '@/components/common/FeatureItem';
import Marquee from '@/components/common/Marquee';
import LeadersCarousel from '@/components/home/LeadersCarousel';
import LogoScroll, { type LogoScrollSpeed } from '@/components/home/LogoScroll';
import PartnerLogoStrip from '@/components/home/PartnerLogoStrip';
import { slugify } from '@/mocks/slugify';

export async function generateMetadata(): Promise<Metadata> {
  const settings = await getPublicSiteSettings().catch(() => null);
  const title = settings?.defaultTitle || settings?.siteName || 'CMORoom';
  return buildPageMetadata('home', { title: { absolute: title }, description: settings?.defaultDescription });
}

const HOME_EVENTS = 6;
const PERFORMANCE_LINK_CLASS = 'text-md color-black font-family-arial-ce fw-600 text-underline lh-1-5 mb-0';

/** Partner brand domains in partnership copy → their sites (https). */
const PARTNER_DOMAIN_RE = /\b(ad\.com|search\.com|monetize\.com|publicgood\.com|public\s+good)\b/gi;

function partnerHref(match: string): string {
  const key = match.toLowerCase().replace(/\s+/g, '');
  if (key === 'publicgood' || key === 'publicgood.com') return 'https://publicgood.com';
  return `https://${key}`;
}

function withDomainLinks(text: string): ReactNode {
  const parts: ReactNode[] = [];
  let last = 0;
  let i = 0;
  for (const match of text.matchAll(PARTNER_DOMAIN_RE)) {
    const matched = match[0];
    const index = match.index ?? 0;
    if (index > last) {
      parts.push(<Fragment key={`t${i}`}>{text.slice(last, index)}</Fragment>);
      i += 1;
    }
    parts.push(
      <a key={`a${i}`} href={partnerHref(matched)} className={PERFORMANCE_LINK_CLASS}>
        {matched}
      </a>,
    );
    i += 1;
    last = index + matched.length;
  }
  if (last < text.length) parts.push(<Fragment key={`t${i}`}>{text.slice(last)}</Fragment>);
  return parts.length ? parts : text;
}

export default async function HomePage() {
  const [page, cities] = await Promise.all([getHomePage(), getCities()]);
  if (!page) notFound();

  const { hero, logos, network, going_on: goingOn, catalyst, spotlight, performance, testimonials } = page;

  // Sections can use live data (events, featured episode, testimonial catalog) instead of hand-picked items.
  const fetchTestimonialCatalog =
    testimonials.is_visible && (testimonials.use_catalog || testimonials.slides.length === 0);

  const useLiveEvents = Boolean(goingOn.is_visible && goingOn.use_live_events);

  const [liveEvents, featured, testimonialCatalog] = await Promise.all([
    useLiveEvents ? getUpcomingEvents(HOME_EVENTS) : null,
    spotlight.is_visible && spotlight.use_featured_episode ? getFeaturedInterview() : null,
    fetchTestimonialCatalog ? orNull(getTestimonials()) : null,
  ]);

  // Only the logos attached on the Home editor: none attached (or Show off) = no logo strip.
  const brands: Brand[] = logos.items.map((item) => ({ name: item.name || item.alt, logo: pageImageUrl(item.image) }));

  const resolveCardHref = (card: (typeof goingOn.cards)[number]): string => {
    const explicit = card.href?.trim();
    if (explicit) return explicit;
    const city = String((card as { city_slug?: string }).city_slug || '').trim();
    const slug = slugify(card.title || '');
    if (city && slug) return routes.event(city, slug);
    return routes.events;
  };

  const eventCards: { event: EventSummary; href?: string }[] = liveEvents
    ? liveEvents.map((event) => ({ event }))
    : goingOn.cards
        .filter((card) => {
          const city = String((card as { city_slug?: string }).city_slug || '').trim();
          const hasDate = Boolean(String(card.meta || '').trim());
          return hasDate && (!city || isPublicEventCity(city));
        })
        .map((card) => ({
          event: {
            slug: slugify(card.title) || card.title,
            citySlug: String((card as { city_slug?: string }).city_slug || ''),
            title: card.title,
            date: card.meta,
            image: pageImageUrl(card.image),
          },
          href: resolveCardHref(card),
        }));

  const spotlightCard = featured
    ? { headline: featured.headline, summary: featured.summary, image: featured.image }
    : { headline: spotlight.guest_label, summary: spotlight.summary, image: pageImageUrl(spotlight.image) };

  const manualLeaders: Testimonial[] = testimonials.slides.map((slide, i) => ({
    id: String(i + 1),
    quote: slide.quote,
    author: [slide.name, slide.company && `(${slide.company})`].filter(Boolean).join(' '),
    image: pageImageUrl(slide.image),
  }));

  const catalogLeaders = testimonialCatalog ?? [];
  const leadersSource =
    testimonials.use_catalog && catalogLeaders.length > 0
      ? catalogLeaders
      : manualLeaders.length > 0
        ? manualLeaders
        : catalogLeaders;

  const leaders = orderHomeTestimonials(leadersSource, testimonials.order);

  const networkLines = [network.line1, network.line2, network.line3];
  const performanceLines = [
    { text: performance.line1, gold: false },
    { text: performance.line2_gold, gold: true },
    { text: performance.line3, gold: false },
    { text: performance.line4_gold, gold: true },
  ].filter((line) => line.text);

  return (
    <main>
      {hero.is_visible && (
        <section className="home-hero-section" style={{ backgroundImage: `url('${pageImageUrl(hero.background_image)}')` }}>
          <div className="home-hero-overlay"></div>
          <div className="container home-hero-content text-center">
            <h1 className="home-hero-title" data-aos="fade-up">
              {hero.title}
            </h1>
            <p className="home-hero-subtitle" data-aos="fade-up">
              {hero.subtitle}
            </p>
            <Link href={hero.button_link} className="btn button-style btn-golden w-fit-content mx-auto" data-aos="fade-up">
              {hero.button_label} <LongArrowRightIcon color="white" />
            </Link>
          </div>
        </section>
      )}
      <Marquee className="pb-4 pb-md-5" />

      {logos.is_visible && brands.length > 0 && <LogoScroll brands={brands} speed={logos.scroll_speed as LogoScrollSpeed} />}

      {network.is_visible && (
        <section className="bg-color-black webContent pb-5">
          <div className="container">
            <div className="row g-3 g-md-4 align-items-start">
              <div className="col-12 col-md-5 col-xl-6">
                <h2 className="section-title mb-1">
                  {networkLines.map((line, i) =>
                    line ? (
                      <Fragment key={i}>
                        {i > 0 && <br />}
                        {isGoldLine(network.gold_lines, i) ? <span className="text-golden mb-0"> {line}</span> : line}
                      </Fragment>
                    ) : null,
                  )}
                </h2>
              </div>
              <div className="col-12 col-md-7 col-xl-6">
                {network.quote ? (
                  <p className="section-subtitle mb-4">
                    <em className="text-xl mb-0">{network.quote}</em>
                  </p>
                ) : null}
                <p className="section-subtitle mb-0">{network.right_paragraph}</p>
                {network.left_paragraph ? (
                  <p className="section-subtitle mt-4 mb-0">{network.left_paragraph}</p>
                ) : null}
              </div>
            </div>
          </div>
        </section>
      )}

      {goingOn.is_visible && (
        <section className="pb-5 overflow-hidden">
          <div className="container">
            <div className="d-flex flex-column gap-3 mb-4 mb-md-5">
              <h2 className="section-title mb-1">
                {goingOn.heading} <span className="text-golden mb-0"> {goingOn.heading_gold}</span>
              </h2>
              {/* The "All" + city filter row belongs to the live catalog; curated cards show on their own. */}
              {liveEvents && (
                <div className="library-filters d-flex flex-wrap gap-2 gap-md-3">
                  {goingOn.button_label && (
                    <Link
                      href={goingOn.button_link || routes.events}
                      className="filter-btn btn button-style border-1 bg-color-white color-black text-sm px-4"
                    >
                      {goingOn.button_label}
                    </Link>
                  )}
                  {cities.map((city) => (
                    <Link
                      key={city.slug}
                      href={routes.city(city.slug)}
                      className="filter-btn btn button-style color-white border-1 border-color-light text-sm px-4"
                    >
                      {city.name}
                    </Link>
                  ))}
                </div>
              )}
            </div>
            <div className="row g-4">
              {eventCards.map(({ event, href }, i) => (
                <EventCard key={`${event.citySlug}-${event.slug}-${i}`} event={event} href={href} />
              ))}
            </div>
          </div>
        </section>
      )}

      {catalyst.is_visible && (
        <section className="pb-5 overflow-hidden">
          <div className="container">
            <div className="row align-items-center">
              <div className="col-lg-6 mb-4 mb-lg-0">
                <img src={pageImageUrl(catalyst.section_image)} alt="Why CMOroom" className="img-fluid w-100 h-auto" />
              </div>
              <div className="col-lg-6 ps-lg-5">
                <h2 className="section-title text-uppercase">
                  {catalyst.heading_before} <span className="text-golden mb-0 text-uppercase">{catalyst.heading_gold} </span>{' '}
                  {catalyst.heading_after}
                </h2>
                <p className="section-subtitle mb-0">{catalyst.subheading}</p>
              </div>
            </div>
            <div className="row mt-4 mt-md-5">
              {catalyst.features.map((feature, i) => (
                <FeatureItem key={i}>
                  <h4 className="color-white pt-2">{feature.title}</h4>
                  <p>{feature.body}</p>
                </FeatureItem>
              ))}
            </div>
          </div>
        </section>
      )}

      {spotlight.is_visible && (
        <section className="pb-5">
          <div className="container">
            <div className="row g-4 align-items-center">
              <div className="col-lg-7">
                <h2 className="section-title pb-md-2 mb-4">
                  {spotlight.heading} <br />
                  <span className="text-golden mb-0">{spotlight.heading_gold}</span>
                </h2>
                {spotlightCard.headline && <h4 className="text-lg color-white mb-3">{spotlightCard.headline}</h4>}
                {spotlightCard.summary && <p className="pb-md-2 mb-4">{spotlightCard.summary}</p>}
                {spotlight.button_label && (
                  <Link
                    href={
                      !spotlight.button_link || spotlight.button_link === '/spotlight'
                        ? routes.spotlight
                        : spotlight.button_link
                    }
                    className="btn button-style btn-golden w-fit-content"
                  >
                    {spotlight.button_label} <LongArrowRightIcon />
                  </Link>
                )}
              </div>
              {spotlightCard.image && (
                <div className="col-lg-5">
                  <img src={spotlightCard.image} alt="Spotlight" className="w-100 h-auto" />
                </div>
              )}
            </div>
          </div>
        </section>
      )}

      {performance.is_visible && (
        <section className="w-100 py-3">
          <Marquee className="p-0" />
          <div className="bg-color-white webContent pt-5">
            <div className="container">
              <div className="row g-3 g-md-4 align-items-center pb-5">
                <div className="col-12 col-md-12 col-xl-5 home-partner-copy">
                  <h2 className="mainHeading color-black fw-700 text-uppercase mb-0">
                    {performanceLines.map((line, i) => (
                      <Fragment key={i}>
                        {i > 0 && <br />}
                        {line.gold ? (
                          <span className="text-golden mainHeading fw-700 text-uppercase mb-0">{line.text}</span>
                        ) : (
                          line.text
                        )}
                      </Fragment>
                    ))}
                  </h2>
                  {performance.logos.length > 0 && (
                    <PartnerLogoStrip
                      logos={performance.logos.map((logo) => ({
                        name: logo.alt || logo.name,
                        logo: pageImageUrl(logo.image),
                      }))}
                    />
                  )}
                </div>
                <div className="col-12 col-md-12 col-xl-7">
                  {performance.highlight && (
                    <p className="text-xl font-family-arial-black color-black lh-1-5 mb-4">{performance.highlight}</p>
                  )}
                  <p className="text-md color-black lh-1-5 mb-0">{withDomainLinks(performance.para1)}</p>
                  <p className="text-md color-black lh-1-5 mt-4 mb-0">{withDomainLinks(performance.para2)}</p>
                </div>
              </div>
            </div>
          </div>
          <Marquee className="p-0" />
        </section>
      )}

      {testimonials.is_visible && leaders.length > 0 && (
        <LeadersCarousel
          testimonials={leaders}
          autoplaySpeed={testimonials.autoplay_speed}
          showArrows={testimonials.show_arrows}
        />
      )}
    </main>
  );
}
