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

export const revalidate = 1800;

export const metadata: Metadata = {
  title: "AV Integration Manufacturers — AV Beat",
  description:
    "Browse the AV industry — pro AV, display, signage, live-production, and integration manufacturers exhibiting at InfoComm, CEDIA Expo, ISE, DSE, and more. Vendor profiles, booth numbers, product categories, and the latest news from each company.",
  alternates: { canonical: "/manufacturers" },
  openGraph: {
    title: "AV Integration Manufacturers — AV Beat",
    description:
      "Comprehensive directory of pro AV, display, and integration manufacturers, exhibitors, and vendors.",
    type: "website",
    url: "https://avbeat.com/manufacturers",
  },
};

type ManufacturerRow = {
  slug: string;
  company_name: string;
  bio: string | null;
  logo_url: string | null;
  categories: string[] | null;
  exhibits_nab: boolean;
  exhibits_ibc: boolean;
  shows_attending: string[] | null;
  mention_count: number;
  featured: boolean;
};

export type ShowOption = {
  slug: string;
  short_name: string | null;
  name: string;
  start_date: string;
  end_date: string;
  status: string;
};

export default async function ManufacturersIndex() {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("tracked_companies")
    .select(
      "slug, company_name, bio, logo_url, categories, exhibits_nab, exhibits_ibc, shows_attending, mention_count, featured"
    )
    .eq("directory_visible", true)
    .not("slug", "is", null)
    .order("featured", { ascending: false })
    .order("mention_count", { ascending: false })
    .order("company_name", { ascending: true })
    .limit(2000);

  // Every confirmed/tentative event from bb.events. Each event's slug
  // (e.g. 'nab-show-2026') maps to tracked_companies.shows_attending so
  // we can filter the directory by show.
  const { data: eventsData } = await supabase
    .from("events")
    .select("slug, short_name, name, start_date, end_date, status")
    .in("status", ["confirmed", "tentative"])
    .order("start_date", { ascending: true });

  const list = (data || []) as ManufacturerRow[];
  const events = (eventsData || []) as ShowOption[];
  // Per-show exhibitor counts pulled from the same shows_attending array
  // the DirectoryClient uses for its filter chips. Lets the intro line
  // surface the BIGGEST show counts dynamically rather than hardcoding
  // any particular event.
  const showCounts = list.reduce<Record<string, number>>((m, row) => {
    for (const s of row.shows_attending || []) m[s] = (m[s] || 0) + 1;
    return m;
  }, {});
  const topShows = events
    .map((e) => ({ event: e, count: showCounts[e.slug] || 0 }))
    .filter((x) => x.count > 0)
    .sort((a, b) => b.count - a.count)
    .slice(0, 3);

  return (
    <div className="min-h-screen bg-[#F8FAFC]">
      <Header />
      <div className="max-w-6xl mx-auto px-4 py-10">
        <header className="mb-8">
          <h1 className="text-3xl md:text-4xl font-display font-bold text-[#0F172A] mb-2">
            AV Integration Manufacturers
          </h1>
          <p className="text-[#475569] text-base max-w-3xl">
            {list.length.toLocaleString()} pro AV, display, signage, and integration manufacturers
            {topShows.map(({ event, count }) => (
              <span key={event.slug}> · {count.toLocaleString()} at {event.short_name || event.name}</span>
            ))}.
          </p>
          {error && (
            <p className="text-sm text-red-600 mt-2">
              Note: error loading directory ({error.message})
            </p>
          )}
        </header>

        <ManufacturerDirectoryClient manufacturers={list} shows={events} />

        <section className="mt-16 border-t border-[#DCE6F2] pt-8 text-sm text-[#888] leading-relaxed">
          <p>
            Sources: 2026 NAB Show exhibitor list (Map Your Show), IBC exhibitor list,
            manufacturer-direct press releases, and reporting tracked on AV Beat.
            New manufacturers and updates land here as our crawlers detect them.
          </p>
          <p className="mt-2">
            Are you a manufacturer and want to update your listing?{" "}
            <a href="mailto:editors@avbeat.com?subject=Manufacturer%20Directory%20Update" className="text-[#1D4ED8] hover:underline">
              Contact our editors
            </a>
            .
          </p>
        </section>
      </div>
      <Footer />
    </div>
  );
}
