import { notFound } from "next/navigation";
import Link from "next/link";
import { Card, PageHeader, buttonClass } from "@/components/ui";
import { AuthError } from "@/lib/authz/errors";
import { getInsightsInfo } from "@/lib/services/insights";
import { reportsStart, type ReportsKind } from "./reports-shared";

/** "Insights": visitor analytics. This platform does not collect traffic, so this page points at the configured provider. */
export async function ReportsInsightsScreen({ kind }: { kind: ReportsKind }) {
  const s = await reportsStart(kind, "Insights");
  if (s.siteId === null) return s.empty;
  let info;
  try { info = await getInsightsInfo(s.siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const name = info.provider === "ga4" ? "Google Analytics 4" : info.provider === "plausible" ? "Plausible" : null;
  return (
    <>
      <PageHeader title="Insights" description={`${info.siteName} · visitor traffic, sources and top pages`} />
      <Card className="max-w-2xl p-5">
        {name && info.url ? (
          <>
            <h2 className="text-sm font-semibold">Analytics provider: {name}</h2>
            <p className="mt-2 text-sm text-muted-foreground">Visitor statistics for this website are collected by {name} (ID <code>{info.id}</code>) and are viewed there. This CMS does not copy or store visitor traffic.</p>
            <a href={info.url} target="_blank" rel="noopener noreferrer" className={`${buttonClass("primary")} mt-4`}>Open {name}<span className="sr-only"> (opens in a new tab)</span></a>
          </>
        ) : (
          <>
            <h2 className="text-sm font-semibold">No analytics provider connected</h2>
            <p className="mt-2 text-sm text-muted-foreground">This platform does not collect visitor traffic itself, so there is nothing to show yet. Choose Google Analytics 4 or Plausible under SEO &amp; settings and the public website will start reporting to it.</p>
            <Link href={`/dashboard/${kind}/seo`} className={`${buttonClass("primary")} mt-4`}>Go to SEO &amp; settings</Link>
          </>
        )}
      </Card>
    </>
  );
}
