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

export const dynamic = "force-dynamic";

const BUILD_VERSION = process.env.NEXT_PUBLIC_BUILD_VERSION || "v2.0.0";

async function loadStats() {
  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, events, srcs] = await Promise.all([
    sb.from("wp_imported_posts").select("wp_id", { count: "exact", head: true }).eq("status", "published"),
    sb.from("ai_rewritten_articles").select("id", { count: "exact", head: true }).eq("status", "published"),
    sb.from("events").select("id", { count: "exact", head: true }).in("status", ["confirmed", "tentative"]),
    sb.from("wp_imported_posts").select("author_name").not("author_name", "is", null).limit(1000),
  ]);

  const articleCount = (wp.count || 0) + (ai.count || 0);
  const eventCount = events.count || 0;
  const sourceSet = new Set<string>();
  for (const r of (srcs.data || []) as any[]) {
    if (r.author_name) sourceSet.add(String(r.author_name).slice(0, 40));
  }

  return {
    articles: articleCount,
    events: eventCount,
    sources: sourceSet.size,
  };
}

export default async function SystemStatusBar() {
  let stats = { articles: 0, events: 0, sources: 0 };
  try {
    stats = await loadStats();
  } catch {
    // serve zeros on failure, don't break the bar
  }
  return (
    <div
      className="w-full bg-[var(--color-background-secondary,#111)] border-b border-[#DCE6F2]"
      role="status"
      aria-label="System status"
    >
      <div className="max-w-container mx-auto px-4 h-[28px] flex items-center justify-between text-[10px] font-mono uppercase tracking-wider text-[var(--color-text-tertiary,#6b7280)]">
        <div className="flex items-center gap-5">
          <span>{stats.articles.toLocaleString()} articles indexed</span>
          <span>{stats.events} events tracked</span>
        </div>
        <span className="text-[var(--color-text-info,#60a5fa)]">[{BUILD_VERSION}]</span>
      </div>
    </div>
  );
}
