import type { Metadata } from "next";
import Link from "@/components/Link";
import SiteEffects from "@/components/SiteEffects";
import { channelForExpertise, repBySlug, team, type Rep } from "@/lib/channels";
import { PageJsonLd, pageMeta } from "@/lib/seo";
import { PersonCard, TeamDirectory } from "../directory";

const directoryDescription = "Meet the Advertising.net team. Find a representative who knows your category and see how our teams plan, build and support your campaigns.";
const unavailableMeta = pageMeta({ title: "Our Advertising Team", description: directoryDescription, path: "/team", noindex: true });

/** One source for the profile's metadata and its WebPage schema. */
function repMeta(rep: Rep) {
  return pageMeta({
    title: `${rep.name}, ${rep.title}`,
    description: `Connect with ${rep.name}, ${rep.title} at Advertising.net.`,
    path: `/team/${rep.slug}`,
  });
}

/** Same strip as team.php: drop anything outside [a-z0-9-]. Uppercase is removed, not lowercased. */
function sanitizeRepSlug(raw: string) {
  return raw.replace(/[^a-z0-9-]/g, "");
}

function repFromSlug(raw: string) {
  const slug = sanitizeRepSlug(raw);
  const rep = slug ? repBySlug[slug] : undefined;
  return { slug, rep: rep?.active ? rep : undefined };
}

export function generateStaticParams() {
  return team.map((rep) => ({ slug: rep.slug }));
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const { rep } = repFromSlug(slug);
  return rep ? repMeta(rep) : unavailableMeta;
}

// Awaits params in the page itself, like blog/[slug]. A Suspense boundary here (fallback null) streamed the profile
// after the footer, so the footer showed under the header until the content arrived. Every profile is prerendered
// (generateStaticParams), so the navigation may wait for it instead of painting a placeholder first; this tells
// Next's instant-navigation check that blocking here is intended.
export const instant = false;

export default async function TeamMemberPage({ params }: PageProps<"/team/[slug]">) {
  const { slug: raw } = await params;
  const { slug, rep } = repFromSlug(raw);
  if (!rep) {
    return (
      <>
        <PageJsonLd path="/team" meta={unavailableMeta} />
        <TeamDirectory unavailableSlug={slug} />
        <SiteEffects />
      </>
    );
  }

  const others = team.filter((member) => member.active && member.slug !== rep.slug).slice(0, 4);
  const paragraphs = rep.bio.length ? rep.bio : [rep.intro];

  return (
    <>
      <PageJsonLd path={`/team/${rep.slug}`} meta={repMeta(rep)} />
      <section className="an-section">
        <div className="an-wrap">
          <nav className="u-c-mb-a42c4 an-crumbs" aria-label="Breadcrumb">
            <Link href="/" className="u-c-12257">Home</Link>
            <span aria-hidden="true">/</span>
            <Link href="/team" className="u-c-12257">Our Team</Link>
            <span aria-hidden="true">/</span>
            <span aria-current="page">{rep.name}</span>
          </nav>
          <div className="an-profile">
            <div className="an-profile__photo">
              <img src={rep.photo} alt={rep.name} width={500} height={500} />
            </div>
            <div className="an-stack">
              <span className="an-eyebrow">Advertising.net sales</span>
              <h1 className="u-fs-7cdd4 an-h1">{rep.name}</h1>
              <p className="u-fs-18px an-person__title">{rep.title}</p>
              <div className="an-chips">
                {rep.expertise.map((tag) => (
                  <span key={tag} className="an-tag">{tag}</span>
                ))}
              </div>
              <div className="u-fs-17px-mw-62ch an-muted an-profile__bio">
                {paragraphs.map((paragraph) => (
                  <p key={paragraph}>{paragraph}</p>
                ))}
              </div>
              <div className="u-mt-8px an-actions">
                <Link href={`/contact?rep=${rep.slug}`} className="an-btn an-btn--primary" data-track="profile_contact_click" data-track-rep={rep.slug} data-track-location="profile_page">Connect with {rep.first}</Link>
              </div>
              <div className="u-mt-12px an-card an-card--paper">
                <h2 className="u-fs-1-05rem an-h3">Relevant channels</h2>
                <div className="an-chips">
                  {rep.expertise.map((tag) => {
                    const channel = channelForExpertise(tag);
                    return channel ? (
                      <Link key={tag} href={channel.href} className="u-td-p-9a836 an-tag an-tag--line">{channel.name}</Link>
                    ) : null;
                  })}
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      <section className="an-section an-section--paper an-section--tight">
        <div className="an-wrap">
          <div className="an-head an-head--split">
            <h2 className="an-h3">More of the team</h2>
            <Link href="/team" className="an-link">Full directory{" "}<svg className="an-ico" width="16" height="16" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M5 12h14M13 6l6 6-6 6" /></svg></Link>
          </div>
          <div className="an-team an-team--4">
            {others.map((member) => <PersonCard key={member.slug} rep={member} />)}
          </div>
        </div>
      </section>
      <SiteEffects />
    </>
  );
}
