import Link from "next/link";
import { createClient } from "@supabase/supabase-js";

export const dynamic = "force-dynamic";

interface Item {
  slug: string;
  title: string;
  published_at: string;
  source_code: string;
}

const SOURCE_CODES: { match: RegExp; code: string }[] = [
  { match: /blackmagic|davinci/i, code: "BMD" },
  { match: /magewell/i, code: "MGW" },
  { match: /aja/i, code: "AJA" },
  { match: /sony/i, code: "SONY" },
  { match: /matrox/i, code: "MTRX" },
  { match: /telestream/i, code: "TLST" },
  { match: /grass valley/i, code: "GV" },
  { match: /lawo/i, code: "LAWO" },
  { match: /calrec/i, code: "CLRC" },
  { match: /zixi/i, code: "ZIXI" },
  { match: /liveu/i, code: "LVU" },
  { match: /netflix/i, code: "NFLX" },
  { match: /youtube/i, code: "YT" },
  { match: /amazon|aws/i, code: "AWS" },
];

function codeFor(title: string): string {
  for (const { match, code } of SOURCE_CODES) if (match.test(title)) return code;
  return "WIRE";
}

function hhmm(iso: string): string {
  const d = new Date(iso);
  const h = String(d.getUTCHours()).padStart(2, "0");
  const m = String(d.getUTCMinutes()).padStart(2, "0");
  return `${h}:${m}`;
}

export default async function LiveWireTicker() {
  const sb = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      db: { schema: (process.env.NEXT_PUBLIC_SUPABASE_SCHEMA || "av") as "public" },
      auth: { persistSession: false },
    }
  );

  const [wp, ai] = await Promise.all([
    sb
      .from("wp_imported_posts")
      .select("wp_slug, title, wp_published_at")
      .eq("status", "published")
      .order("wp_published_at", { ascending: false })
      .limit(12),
    sb
      .from("ai_rewritten_articles")
      .select("slug, title, published_at")
      .eq("status", "published")
      .order("published_at", { ascending: false, nullsFirst: false })
      .limit(6),
  ]);

  const items: Item[] = [];
  for (const r of (wp.data || []) as any[]) {
    items.push({
      slug: r.wp_slug,
      title: r.title,
      published_at: r.wp_published_at,
      source_code: codeFor(r.title || ""),
    });
  }
  for (const r of (ai.data || []) as any[]) {
    items.push({
      slug: r.slug,
      title: r.title,
      published_at: r.published_at,
      source_code: codeFor(r.title || ""),
    });
  }
  items.sort(
    (a, b) => new Date(b.published_at).getTime() - new Date(a.published_at).getTime()
  );

  const display = items.slice(0, 14);

  return (
    <div
      className="w-full bg-[var(--color-background-secondary,#111)] border-b border-[#DCE6F2] overflow-hidden"
      role="region"
      aria-label="Live wire ticker"
    >
      <div className="max-w-container mx-auto px-4 h-[36px] flex items-center gap-4 text-[12px]">
        <span className="inline-flex items-center gap-1.5 font-mono uppercase tracking-wider text-[var(--color-text-danger,#ef4444)] shrink-0">
          <span className="bb-pulse-dot bb-pulse-dot--red" /> Live wire
        </span>
        <div className="overflow-hidden flex-1">
          <div className="bb-marquee">
            {[...display, ...display].map((it, i) => (
              <Link
                key={`${it.slug}-${i}`}
                href={`/news/${it.slug}`}
                className="inline-flex items-center gap-2 px-4 text-[#d1d5db] hover:text-[var(--color-text-info,#60a5fa)] whitespace-nowrap"
              >
                <span className="font-mono text-[#6b7280]">[{hhmm(it.published_at)}]</span>
                <span className="font-mono text-[var(--color-text-info,#60a5fa)]">[{it.source_code}]</span>
                <span>{it.title}</span>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
