import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { createClient } from "@/lib/supabase/server";
import BackLink from "./BackLink";

export const revalidate = 1800;

type Params = { slug: string };

const LOGO_OVERRIDES: Record<string, string> = {
  "blackmagic-design": "/img/partners/blackmagic-design.png",
};

function resolveLogoUrl(slug: string, logoUrl: string | null | undefined): string | null {
  return LOGO_OVERRIDES[slug] || logoUrl || null;
}

// Known show date ranges. Booth numbers only render when the show is
// upcoming within 90 days; otherwise the row is shown without a booth.
const SHOW_DATES: Record<string, { start: string; end: string }> = {
  "NAB Show:2026": { start: "2026-04-11", end: "2026-04-16" },
  "NAB Show NY:2026": { start: "2026-10-21", end: "2026-10-23" },
  "IBC:2026": { start: "2026-09-11", end: "2026-09-14" },
  "NAB Show:2027": { start: "2027-04-17", end: "2027-04-22" },
};

function normaliseShowName(raw: string | null | undefined): string {
  const s = (raw || "").trim();
  if (!s) return s;
  if (/^nab(\s*show)?$/i.test(s)) return "NAB Show";
  if (/^nab\s*(show\s*)?(ny|new\s*york)$/i.test(s)) return "NAB Show NY";
  if (/^ibc(\s*show)?$/i.test(s)) return "IBC";
  return s;
}

function shouldShowBooth(show: string, year: number | null): boolean {
  if (!year) return false;
  const dates = SHOW_DATES[`${show}:${year}`];
  if (!dates) return false;
  const today = new Date();
  const start = new Date(dates.start + "T00:00:00Z");
  const end = new Date(dates.end + "T23:59:59Z");
  if (today > end) return false;
  const daysUntilStart = (start.getTime() - today.getTime()) / 86_400_000;
  return daysUntilStart <= 90;
}

async function loadManufacturer(slug: string) {
  const supabase = await createClient();
  const { data } = await supabase
    .from("tracked_companies")
    .select(
      "id, slug, company_name, bio, bio_source, logo_url, company_website, contact_email, contact_url, phone, hq_address, hq_city, hq_country, linkedin_url, twitter_handle, youtube_url, press_url, categories, exhibits_nab, exhibits_ibc, mention_count, last_mentioned, featured, ad_status"
    )
    .eq("slug", slug)
    .eq("directory_visible", true)
    .maybeSingle();
  if (!data) return null;

  const { data: shows } = await supabase
    .from("trade_show_exhibitors")
    .select("show, show_year, booth, description, url, website")
    .eq("exhibitor_name", data.company_name)
    .order("show_year", { ascending: false });

  const { data: pressReleases } = await supabase
    .from("press_releases")
    .select("title, slug, published_at, source_url")
    .eq("manufacturer_id", data.id)
    .order("published_at", { ascending: false })
    .limit(10);

  const { data: executives } = await supabase
    .from("manufacturer_executives")
    .select("id, name, title, photo_url, linkedin_url, bio")
    .eq("company_id", data.id)
    .order("sort_order")
    .order("name");

  // Recent stories: title contains the company name. The same heuristic the
  // article auto-linker and the hover card use — keeps the directory in sync
  // with the editorial coverage even when manufacturer_id isn't backfilled.
  const needle = String(data.company_name || "").trim();
  let recentStories: any[] = [];
  if (needle.length >= 3) {
    const { data: stories } = await supabase
      .from("wp_imported_posts")
      .select("wp_slug, title, excerpt, featured_image, wp_published_at, category")
      .eq("status", "published")
      .ilike("title", `%${needle.replace(/[%_]/g, "")}%`)
      .order("wp_published_at", { ascending: false, nullsFirst: false })
      .limit(12);
    recentStories = stories || [];
  }

  return {
    company: data,
    shows: shows || [],
    pressReleases: pressReleases || [],
    executives: executives || [],
    recentStories,
  };
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  const result = await loadManufacturer(slug);
  if (!result) {
    return { title: "Manufacturer not found — AV Beat" };
  }
  const { company } = result;
  const title = `${company.company_name} — Manufacturer Profile | AV Beat`;
  const description =
    (company.bio || "").slice(0, 200) ||
    `${company.company_name} is a broadcast industry manufacturer covered by AV Beat.`;
  return {
    title,
    description,
    alternates: { canonical: `/manufacturers/${slug}` },
    openGraph: {
      title,
      description,
      url: `https://avbeat.com/manufacturers/${slug}`,
      type: "profile",
      ...(company.logo_url ? { images: [{ url: company.logo_url }] } : {}),
    },
  };
}

export default async function ManufacturerProfile({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  const result = await loadManufacturer(slug);
  if (!result) notFound();
  const { company, shows, pressReleases, executives, recentStories } = result;

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Organization",
    name: company.company_name,
    description: company.bio || undefined,
    url: company.company_website || undefined,
    logo: company.logo_url || undefined,
    sameAs: [
      company.linkedin_url,
      company.twitter_handle ? `https://twitter.com/${company.twitter_handle}` : null,
      company.youtube_url,
    ].filter(Boolean),
    address:
      company.hq_city || company.hq_country
        ? {
            "@type": "PostalAddress",
            addressLocality: company.hq_city || undefined,
            addressCountry: company.hq_country || undefined,
          }
        : undefined,
  };

  return (
    <div className="min-h-screen bg-[#F8FAFC]">
      <Header />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <article className="max-w-4xl mx-auto px-4 py-10">
        <nav className="text-xs text-[#888] mb-6">
          <BackLink />
        </nav>

        <header className="flex flex-col sm:flex-row gap-6 mb-8 pb-8 border-b border-[#DCE6F2]">
          <div className="w-24 h-24 rounded-xl bg-[#FFFFFF] flex items-center justify-center overflow-hidden flex-shrink-0">
            {resolveLogoUrl(slug, company.logo_url) ? (
              /* eslint-disable-next-line @next/next/no-img-element */
              <img
                src={resolveLogoUrl(slug, company.logo_url)!}
                alt={`${company.company_name} logo`}
                className="w-full h-full object-contain p-1"
              />
            ) : (
              <span className="text-[#666] text-3xl font-bold">
                {(company.company_name || "?").trim().charAt(0).toUpperCase()}
              </span>
            )}
          </div>
          <div className="min-w-0 flex-1">
            <h1 className="text-3xl md:text-4xl font-display font-bold text-[#0F172A] mb-1">
              {company.company_name}
            </h1>
            <div className="flex items-center gap-2 flex-wrap text-xs">
              {company.exhibits_nab && (
                <span className="bg-amber-50 text-amber-700 px-2 py-0.5 rounded font-semibold uppercase tracking-wider">
                  2026 NAB Show
                </span>
              )}
              {company.exhibits_ibc && (
                <span className="bg-blue-50 text-blue-700 px-2 py-0.5 rounded font-semibold uppercase tracking-wider">
                  IBC 2026
                </span>
              )}
              {(company.hq_city || company.hq_country) && (
                <span className="text-[#888]">
                  {[company.hq_city, company.hq_country].filter(Boolean).join(", ")}
                </span>
              )}
              {company.phone && (
                <a href={`tel:${company.phone.replace(/[^\d+]/g, '')}`} className="text-[#888] hover:text-[#1D4ED8]">
                  {company.phone}
                </a>
              )}
            </div>
            <div className="mt-3 flex flex-wrap gap-3 text-sm">
              {company.company_website && (
                <a
                  href={company.company_website}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#1D4ED8] hover:underline"
                >
                  Website ↗
                </a>
              )}
              {company.press_url && (
                <a
                  href={company.press_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#1D4ED8] hover:underline"
                >
                  Newsroom ↗
                </a>
              )}
              {company.contact_url && (
                <a
                  href={company.contact_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#1D4ED8] hover:underline"
                >
                  Contact ↗
                </a>
              )}
              {company.linkedin_url && (
                <a
                  href={company.linkedin_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#888] hover:text-[#1D4ED8]"
                >
                  LinkedIn
                </a>
              )}
              {company.twitter_handle && (
                <a
                  href={`https://twitter.com/${company.twitter_handle}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#888] hover:text-[#1D4ED8]"
                >
                  X / Twitter
                </a>
              )}
            </div>
          </div>
        </header>

        {company.bio && (
          <section className="mb-10">
            <h2 className="text-lg font-display font-bold text-[#0F172A] mb-2">About</h2>
            <div className="text-[#475569] leading-relaxed space-y-4 whitespace-pre-line">{company.bio}</div>
            {company.bio_source && (
              <p className="text-xs text-[#666] mt-2">
                Source: {company.bio_source}
              </p>
            )}
          </section>
        )}

        {executives.length > 0 && (
          <section className="mb-10">
            <h2 className="text-lg font-display font-bold text-[#0F172A] mb-4">Executive leadership</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {executives.map((e: any) => (
                <div key={e.id} className="bg-white border border-[#DCE6F2] rounded-lg p-4 flex gap-3">
                  {e.photo_url ? (
                    /* eslint-disable-next-line @next/next/no-img-element */
                    <img
                      src={e.photo_url}
                      alt={e.name}
                      className="w-16 h-16 rounded-full object-cover bg-[#FFFFFF] flex-shrink-0"
                      loading="lazy"
                    />
                  ) : (
                    <div className="w-16 h-16 rounded-full bg-[#FFFFFF] flex items-center justify-center text-[#666] font-bold flex-shrink-0">
                      {(e.name || "?").trim().charAt(0).toUpperCase()}
                    </div>
                  )}
                  <div className="min-w-0">
                    <div className="font-semibold text-[#0F172A] truncate">{e.name}</div>
                    {e.title && <div className="text-xs text-[#888] mb-1">{e.title}</div>}
                    {e.bio && <p className="text-xs text-[#64748B] line-clamp-3 mb-1">{e.bio}</p>}
                    {e.linkedin_url && (
                      <a
                        href={e.linkedin_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-[11px] text-[#1D4ED8] hover:underline"
                      >
                        LinkedIn ↗
                      </a>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}

        {(company.hq_address || company.phone || company.contact_email) && (
          <section className="mb-10">
            <h2 className="text-lg font-display font-bold text-[#0F172A] mb-2">Headquarters</h2>
            <address className="not-italic text-[#475569] text-sm leading-relaxed">
              {company.hq_address && <div>{company.hq_address}</div>}
              {(company.hq_city || company.hq_country) && (
                <div>{[company.hq_city, company.hq_country].filter(Boolean).join(", ")}</div>
              )}
              {company.phone && (
                <div className="mt-1">
                  <a href={`tel:${company.phone.replace(/[^\d+]/g, '')}`} className="text-[#1D4ED8] hover:underline">
                    {company.phone}
                  </a>
                </div>
              )}
              {company.contact_email && (
                <div>
                  <a href={`mailto:${company.contact_email}`} className="text-[#1D4ED8] hover:underline">
                    {company.contact_email}
                  </a>
                </div>
              )}
            </address>
          </section>
        )}

        {(() => {
          const cleanCategories = (company.categories || []).filter(
            (c: string) => typeof c === "string" && c.trim().length >= 2
          );
          if (cleanCategories.length === 0) return null;
          return (
            <section className="mb-10">
              <h2 className="text-lg font-display font-bold text-[#0F172A] mb-2">Categories</h2>
              <div className="flex flex-wrap gap-2">
                {cleanCategories.map((c: string) => (
                  <span
                    key={c}
                    className="text-xs bg-[#EEF2F6] text-[#475569] px-2.5 py-1 rounded-full border border-[#DCE6F2]"
                  >
                    {c}
                  </span>
                ))}
              </div>
            </section>
          );
        })()}

        {shows.length > 0 && (
          <section className="mb-10">
            <h2 className="text-lg font-display font-bold text-[#0F172A] mb-3">
              Trade-show appearances
            </h2>
            <ul className="space-y-2">
              {shows.map((s) => {
                const showName = normaliseShowName(s.show);
                const label = showName === "NAB Show"
                  ? `${s.show_year} NAB Show`
                  : `${showName} ${s.show_year}`;
                const cleanBooth = (s.booth || "").replace(/randomstring\s*$/i, "").trim();
                const renderBooth = cleanBooth && shouldShowBooth(showName, s.show_year);
                return (
                  <li
                    key={`${s.show}-${s.show_year}-${s.booth || "?"}`}
                    className="bg-white border border-[#DCE6F2] rounded-md px-4 py-3 flex items-center justify-between gap-4"
                  >
                    <div className="min-w-0">
                      <span className="font-semibold text-[#0F172A]">{label}</span>
                      {renderBooth && (
                        <span className="ml-3 text-sm text-[#888]">Booth {cleanBooth}</span>
                      )}
                    </div>
                  </li>
                );
              })}
            </ul>
          </section>
        )}

        {recentStories.length > 0 && (
          <section className="mb-10">
            <header className="flex items-baseline justify-between mb-3">
              <h2 className="text-lg font-display font-bold text-[#0F172A]">Recent coverage</h2>
              <Link href={`/news?search=${encodeURIComponent(company.company_name)}`} className="text-xs text-[#1D4ED8] hover:underline">
                All stories →
              </Link>
            </header>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
              {recentStories.slice(0, 6).map((r: any) => (
                <Link
                  key={r.wp_slug}
                  href={`/news/${r.wp_slug}`}
                  className="group bg-white border border-[#DCE6F2] rounded-md p-3 hover:border-[#1D4ED8] hover:shadow-sm transition-all flex gap-3"
                >
                  {/* Image fallback cascade — Ryan rule: never show an empty
                      gray box on a coverage card. Falls through:
                      article featured_image → company logo → static placeholder. */}
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={r.featured_image || resolveLogoUrl(slug, company.logo_url) || '/assets/images/article-placeholder-v2.svg'}
                    alt=""
                    className="w-20 h-14 rounded object-cover bg-[#FFFFFF] flex-shrink-0"
                    loading="lazy"
                  />
                  <div className="min-w-0">
                    <h3 className="text-xs font-semibold text-[#0F172A] leading-snug group-hover:text-[#1D4ED8] line-clamp-3">
                      {r.title}
                    </h3>
                    {r.wp_published_at && (
                      <p className="text-[10px] text-[#888] mt-1">
                        {new Date(r.wp_published_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                      </p>
                    )}
                  </div>
                </Link>
              ))}
            </div>
          </section>
        )}

        {pressReleases.length > 0 && (
          <section className="mb-10">
            <h2 className="text-lg font-display font-bold text-[#0F172A] mb-3">Press releases</h2>
            <ul className="space-y-2">
              {pressReleases.map((p) => (
                <li key={p.slug || p.source_url} className="text-sm">
                  {p.slug ? (
                    <Link
                      href={`/news/${p.slug}`}
                      className="text-[#1D4ED8] hover:underline"
                    >
                      {p.title}
                    </Link>
                  ) : (
                    <span className="text-[#475569]">{p.title}</span>
                  )}
                  {p.published_at && (
                    <span className="text-[#888] text-xs ml-2">
                      {new Date(p.published_at).toISOString().slice(0, 10)}
                    </span>
                  )}
                </li>
              ))}
            </ul>
          </section>
        )}

        <footer className="text-xs text-[#666] mt-12 pt-6 border-t border-[#DCE6F2]">
          Listing maintained by AV Beat editorial.
          {company.last_mentioned && (
            <> Last mentioned in coverage on {new Date(company.last_mentioned).toISOString().slice(0, 10)}.</>
          )}
        </footer>
      </article>
      <Footer />
    </div>
  );
}
