"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { formatCountryLabel } from "@/lib/countries";
import { formatInteger } from "@/lib/utils";
import { ClmDashboardFilters } from "@/components/clm/clm-dashboard-filters";
import { ClmDashboardCharts } from "@/components/clm/clm-dashboard-charts";

type ClmApiPayload = {
  activeScope: string;
  data: any;
  workbookSnapshot: any;
};

const clmResponseCache = new Map<string, ClmApiPayload>();

function monthLabel(value: string) {
  return new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric" }).format(
    new Date(`${value}-01T00:00:00Z`),
  );
}

function KpiHighlights({
  totalCalls,
  callsUsingClm,
  callsWithoutClm,
}: {
  totalCalls: number;
  callsUsingClm: number;
  callsWithoutClm: number;
}) {
  const clmUsageRate = totalCalls > 0 ? (callsUsingClm / totalCalls) * 100 : 0;

  return (
    <section className="grid w-full gap-2.5 xl:grid-cols-3">
      <Card className="enter-fade-up min-h-[116px] border-[#db822c] !bg-[linear-gradient(155deg,#f7a043_0%,#f28f32_56%,#e58124_100%)] p-3 text-white shadow-[0_20px_32px_-22px_rgba(189,101,26,0.9)]">
        <p className="caption text-[10px] uppercase tracking-[0.2em] text-white">Total Calls</p>
        <p className="mt-1 text-[58px] font-black leading-[0.85] tracking-tight text-white">{formatInteger(totalCalls)}</p>
      </Card>
      <Card className="enter-fade-up min-h-[116px] border-[#d8e4f3] bg-[linear-gradient(150deg,#ffffff_0%,#f2f8ff_100%)] p-3" style={{ ["--enter-delay" as string]: "40ms" }}>
        <p className="caption text-[10px] uppercase tracking-[0.2em] text-slate-500">Calls Using CLM</p>
        <div className="mt-1 flex flex-wrap items-end gap-x-3 gap-y-1">
          <p className="min-w-0 text-[58px] font-black leading-[0.85] tracking-tight text-slate-900">{formatInteger(callsUsingClm)}</p>
          <p className="mb-1 inline-flex shrink-0 whitespace-nowrap rounded-full bg-[#fff4e8] px-2 py-0.5 text-sm font-semibold text-[#d9852c]">{clmUsageRate.toFixed(1)}%</p>
        </div>
      </Card>
      <Card className="enter-fade-up min-h-[116px] border-[#d8e4f3] bg-[linear-gradient(150deg,#ffffff_0%,#f2f8ff_100%)] p-3" style={{ ["--enter-delay" as string]: "80ms" }}>
        <p className="caption text-[10px] uppercase tracking-[0.2em] text-slate-500">Calls Without CLM</p>
        <p className="mt-1 text-[58px] font-black leading-[0.85] tracking-tight text-slate-900">{formatInteger(callsWithoutClm)}</p>
      </Card>
    </section>
  );
}

function KpiCards({
  clmRecords,
  uniquePresentations,
  uniqueKeyMessages,
  averageDeckRecordsPerCall,
}: {
  clmRecords: number;
  uniquePresentations: number;
  uniqueKeyMessages: number;
  averageDeckRecordsPerCall: number;
}) {
  const cards = [
    { label: "CLM Records", value: clmRecords, accent: "#F7993A" },
    { label: "Unique Presentations", value: uniquePresentations, accent: "#2663AC" },
    {
      label: "Key Messages",
      value: uniqueKeyMessages,
      accent: "#F7993A",
      subLabel: `${averageDeckRecordsPerCall.toFixed(1)} avg rec/call`,
    },
  ];

  return (
    <section className="grid gap-2.5 sm:grid-cols-2 xl:grid-cols-3">
      {cards.map((card, index) => (
        <Card
          key={card.label}
          className="enter-fade-up group relative min-h-[102px] overflow-hidden border-[#d8e4f3] bg-[linear-gradient(145deg,#ffffff_0%,#f6fbff_82%)] p-3"
          style={{ ["--enter-delay" as string]: `${120 + index * 40}ms` }}
        >
          <div className="pointer-events-none absolute -right-10 -top-10 h-20 w-20 rounded-full opacity-20 blur-2xl" style={{ backgroundColor: card.accent }} />
          <div className="absolute left-0 top-0 h-1 w-full" style={{ backgroundColor: card.accent }} />
          <p className="caption text-[10px] uppercase tracking-[0.18em] text-slate-500">{card.label}</p>
          {"subLabel" in card ? (
            <div className="mt-1 flex flex-wrap items-end gap-x-3 gap-y-1">
              <p className="min-w-0 text-[52px] font-black leading-[0.86] tracking-tight text-slate-900">
                {formatInteger(card.value)}
              </p>
              <p className="mb-1 inline-flex shrink-0 whitespace-nowrap rounded-full bg-[#fff4e8] px-2 py-0.5 text-xs font-semibold text-[#d9852c] sm:text-sm">
                {card.subLabel}
              </p>
            </div>
          ) : (
            <p className="mt-1 text-[52px] font-black leading-[0.86] tracking-tight text-slate-900">{formatInteger(card.value)}</p>
          )}
        </Card>
      ))}
    </section>
  );
}

function PageLoading() {
  return (
    <div className="space-y-4">
      <Card>
        <div className="flex items-center gap-3">
          <span
            className="h-4 w-4 animate-spin rounded-full border-2 border-[#2663AC]/30 border-t-[#2663AC]"
            aria-hidden="true"
          />
          <p className="text-sm font-semibold text-slate-700">Loading CLM dashboard...</p>
        </div>
      </Card>
    </div>
  );
}

export function ClmDashboardPageClient({
  initialQuery = "",
  initialPayload = null,
}: {
  initialQuery?: string;
  initialPayload?: ClmApiPayload | null;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const query = searchParams.toString();
  const seededPayload =
    clmResponseCache.get(query) ?? (query === initialQuery ? initialPayload ?? null : null);
  const [payload, setPayload] = useState<ClmApiPayload | null>(seededPayload);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(!seededPayload);

  useEffect(() => {
    if (query !== initialQuery || !initialPayload) return;
    clmResponseCache.set(query, initialPayload);
    setPayload(initialPayload);
    setError(null);
    setLoading(false);
  }, [initialPayload, initialQuery, query]);

  useEffect(() => {
    let active = true;
    const cached = clmResponseCache.get(query);
    if (cached) {
      setPayload(cached);
      setError(null);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    fetch(`/api/clm-dashboard-data${query ? `?${query}` : ""}`, {
      credentials: "same-origin",
      cache: "no-store",
    })
      .then(async (response) => {
        if (!response.ok) throw new Error(`CLM dashboard request failed (${response.status})`);
        return (await response.json()) as ClmApiPayload;
      })
      .then((nextPayload) => {
        if (!active) return;
        clmResponseCache.set(query, nextPayload);
        setPayload(nextPayload);
        setLoading(false);
      })
      .catch((nextError: Error) => {
        if (!active) return;
        setError(nextError.message);
        setLoading(false);
      });

    return () => {
      active = false;
    };
  }, [query]);

  if (!payload && loading) return <PageLoading />;
  if (!payload) {
    return (
      <Card>
        <p className="text-sm text-rose-600">{error ?? "Could not load CLM dashboard data."}</p>
      </Card>
    );
  }

  const { activeScope, data, workbookSnapshot } = payload;
  const totalDeckRecords = workbookSnapshot.deckSlides.reduce(
    (sum: number, row: { totalRecords: number }) => sum + Number(row.totalRecords ?? 0),
    0,
  );
  const totalDeckCalls = workbookSnapshot.deckSlides.reduce(
    (sum: number, row: { uniqueCalls: number }) => sum + Number(row.uniqueCalls ?? 0),
    0,
  );
  const averageDeckRecordsPerCall = totalDeckCalls > 0 ? totalDeckRecords / totalDeckCalls : 0;
  const activePresentation = data.selectedFilters.presentation || "";
  const rankedDecks = [...workbookSnapshot.deckSlides]
    .filter((row: any) => Number(row.uniqueCalls ?? 0) > 0)
    .sort(
      (a: any, b: any) =>
        Number(b.uniqueCalls ?? 0) - Number(a.uniqueCalls ?? 0) ||
        Number(b.totalRecords ?? 0) - Number(a.totalRecords ?? 0) ||
        String(a.presentation ?? "").localeCompare(String(b.presentation ?? "")),
    );
  const topDecks = rankedDecks.slice(0, 6);
  const lowestDecks = [...rankedDecks].reverse().slice(0, Math.min(6, rankedDecks.length));

  function applyPresentationFilter(presentation: string) {
    const next = new URLSearchParams(searchParams.toString());
    if (presentation && presentation !== activePresentation) next.set("presentation", presentation);
    else next.delete("presentation");
    const query = next.toString();
    router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
  }

  return (
    <>
      <ClmDashboardFilters
        selected={{ ...data.selectedFilters, scope: activeScope }}
        availableCountries={data.availableCountries}
        availableProducts={data.availableProducts}
        availableMonths={data.availableMonths}
      />

      <section className="grid gap-2.5 sm:grid-cols-2 xl:grid-cols-6">
        {[
          { label: "Total Calls", value: workbookSnapshot.summary.totalCalls, tone: "hero", sub: undefined },
          {
            label: "Calls with presentations",
            value: workbookSnapshot.summary.callsWithPresentation,
            tone: "standard",
            sub:
              workbookSnapshot.summary.totalCalls > 0
                ? `${((workbookSnapshot.summary.callsWithPresentation / workbookSnapshot.summary.totalCalls) * 100).toFixed(1)}% of all calls`
                : undefined,
          },
          { label: "Calls without presentations", value: workbookSnapshot.summary.callsWithoutPresentation, tone: "standard", sub: undefined },
          { label: "CLM Records", value: workbookSnapshot.summary.totalRows, tone: "standard", sub: undefined },
          { label: "Presentations", value: workbookSnapshot.summary.uniquePresentations, tone: "standard", sub: undefined },
          { label: "Key Messages", value: workbookSnapshot.summary.uniqueKeyMessages, tone: "standard", sub: `${averageDeckRecordsPerCall.toFixed(1)} avg rec/call` },
        ].map((card, index) => (
          <Card
            key={card.label}
            className={cn(
              "enter-fade-up relative overflow-hidden p-3 transition duration-300 hover:-translate-y-0.5",
              card.tone === "hero"
                ? "border-[#db822c] !bg-[linear-gradient(155deg,#f7a043_0%,#f28f32_56%,#e58124_100%)] text-white shadow-[0_20px_32px_-22px_rgba(189,101,26,0.9)]"
                : "border-[#d8e4f3] bg-[linear-gradient(145deg,#ffffff_0%,#f6fbff_82%)]",
            )}
            style={{ ["--enter-delay" as string]: `${index * 40}ms` }}
          >
            {card.tone !== "hero" ? <div className="absolute left-0 top-0 h-1 w-full bg-[#2663AC]" /> : null}
            <p className={cn("caption text-[10px] uppercase tracking-[0.18em]", card.tone === "hero" ? "text-white" : "text-slate-500")}>
              {card.label}
            </p>
            <div className="mt-1 flex flex-wrap items-end gap-x-2 gap-y-1">
              <p className={cn("text-[36px] font-black leading-[0.86] tracking-tight sm:text-[40px]", card.tone === "hero" ? "text-white" : "text-slate-900")}>
                {formatInteger(card.value)}
              </p>
              {card.sub ? (
                <p className={cn("mb-1 inline-flex shrink-0 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-semibold", card.tone === "hero" ? "bg-white/20 text-white" : "bg-[#fff4e8] text-[#d9852c]")}>
                  {card.sub}
                </p>
              ) : null}
            </div>
          </Card>
        ))}
      </section>

      <div
        className="enter-fade-up overflow-hidden rounded-2xl border border-[#c8d8ee] bg-[linear-gradient(165deg,#f0f7ff_0%,#e8f2fc_100%)] shadow-[0_12px_24px_-18px_rgba(38,99,172,0.22),inset_0_1px_0_rgba(255,255,255,0.7)]"
        style={{ ["--enter-delay" as string]: "80ms" }}
      >
        <div className="flex items-stretch">
          <div className="w-1 shrink-0 rounded-l-2xl bg-[linear-gradient(180deg,#2663AC_0%,#4a88cc_100%)]" />
          <div className="flex items-start gap-3 px-4 py-4">
            <div className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[#2663AC]/15 text-[#2663AC]">
              <svg viewBox="0 0 20 20" className="h-3.5 w-3.5 fill-current" aria-hidden="true">
                <path fillRule="evenodd" d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-7-4a1 1 0 1 1-2 0 1 1 0 0 1 2 0ZM9 9a.75.75 0 0 0 0 1.5h.253a.25.25 0 0 1 .244.304l-.459 2.066A1.75 1.75 0 0 0 10.747 15H11a.75.75 0 0 0 0-1.5h-.253a.25.25 0 0 1-.244-.304l.459-2.066A1.75 1.75 0 0 0 9.253 9H9Z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="min-w-0">
              <p className="text-sm font-semibold text-[#1a4a82]">How the CLM usage rate is calculated</p>
              <p className="mt-1.5 text-xs leading-relaxed text-slate-600">
                This dashboard counts CLM usage across <strong className="font-semibold text-slate-800">all unique calls</strong> in the Veeva export. The Otsuka scorecard applies additional filters not available in this export — narrowing to submitted calls, in-person or video channel, Sales Rep or Manager only, and promotional interactions. That narrower base produces a higher usage rate (~52%). The figures here will differ; this view covers the full export as received.
              </p>
            </div>
          </div>
        </div>
      </div>

      {data.selectedFilters.month ? (
        <section className="enter-fade-up rounded-2xl border border-[#f1cfaa] bg-[linear-gradient(165deg,#fff8f0_0%,#fff1e2_100%)] px-4 py-3 shadow-[0_16px_24px_-20px_rgba(199,110,33,0.62)]">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div>
              <p className="caption text-[10px] uppercase tracking-[0.16em] text-[#b46820]">Month Focus</p>
              <p className="text-base font-semibold text-slate-900">Showing {monthLabel(data.selectedFilters.month)}</p>
            </div>
            <p className="text-xs font-medium text-[#9f5b1d]">
              Monthly trend charts are based on clickstream timestamps from the Call Clickstream export.
            </p>
          </div>
        </section>
      ) : null}

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-4 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "180ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f2f8ff_0%,#eaf2fd_100%)] px-4 py-3.5 text-sm font-semibold text-slate-900 shadow-[inset_0_1px_0_rgba(255,255,255,0.8)] transition hover:border-[#c5d9ef] hover:bg-[linear-gradient(120deg,#edf6ff_0%,#e3eefb_100%)]">
          Monthly Trend View
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="mt-4 overflow-hidden transition duration-300 group-open:opacity-100">
          <div className="mb-4 rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f8fbff_0%,#eef5ff_100%)] px-4 py-3 text-sm text-slate-600">
            {activePresentation ? (
              <div className="flex flex-wrap items-center justify-between gap-3">
                <p>
                  Monthly breakdown for <span className="font-semibold text-slate-900">{activePresentation}</span>.
                </p>
                <button
                  type="button"
                  onClick={() => applyPresentationFilter("")}
                  className="rounded-lg border border-[#d7e3f2] bg-white px-3 py-1.5 text-xs font-semibold text-[#2663AC] transition hover:bg-[#f5faff]"
                >
                  Clear deck filter
                </button>
              </div>
            ) : (
              <p>Click a deck below to turn these charts into a month-by-month breakdown for that presentation.</p>
            )}
          </div>
          {data.monthlySeries.length > 0 ? (
            <ClmDashboardCharts rows={data.monthlySeries} />
          ) : (
            <div className="rounded-2xl border border-dashed border-slate-300 bg-white/80 px-4 py-5 text-sm text-slate-500">
              No clickstream timestamp data is available for the current filter range.
            </div>
          )}
        </div>
      </details>

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-4 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "220ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f2f8ff_0%,#eaf2fd_100%)] px-4 py-3.5 text-sm font-semibold text-slate-900 shadow-[inset_0_1px_0_rgba(255,255,255,0.8)] transition hover:border-[#c5d9ef] hover:bg-[linear-gradient(120deg,#edf6ff_0%,#e3eefb_100%)]">
          CLM Deck Performance
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="mt-4 space-y-4">
          <div className="rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f8fbff_0%,#eef5ff_100%)] px-4 py-3 text-sm text-slate-600">
            Highest and lowest decks are ranked by unique calls in the current filter range. Click any presentation to update the monthly charts above.
          </div>
          <div className="grid gap-4 xl:grid-cols-2">
            <Card className="overflow-hidden bg-[linear-gradient(160deg,#ffffff_0%,#f6fbff_76%,#fff9f2_100%)] p-4">
              <div className="flex items-center justify-between gap-3">
                <h3 className="text-sm font-semibold text-slate-900">Highest used CLM decks</h3>
                <span className="caption rounded-full border border-[#2663AC]/15 bg-[#2663AC]/10 px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[#2663AC]">Top</span>
              </div>
              <div className="mt-4 grid gap-2">
                {topDecks.map((row: any, index: number) => (
                  <button
                    key={`top-deck-${row.presentation}-${index}`}
                    type="button"
                    onClick={() => applyPresentationFilter(row.presentation)}
                    className={`rounded-2xl border bg-white px-3 py-3 text-left shadow-[0_18px_30px_-26px_rgba(38,99,172,0.65)] transition hover:border-[#2663AC] hover:bg-[#f8fbff] ${
                      activePresentation === row.presentation ? "border-[#2663AC] bg-[#f8fbff]" : "border-[#dbe7f5]"
                    }`}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="text-sm font-semibold text-slate-900">{row.presentation}</p>
                        <p className="mt-1 text-xs text-slate-500">
                          {row.product || "Unspecified product"} • {formatInteger(row.totalRecords)} records • {row.averageRecordsPerCall.toFixed(1)} avg rec/call
                        </p>
                      </div>
                      <span className="rounded-full bg-[#eef5ff] px-2.5 py-1 text-xs font-semibold text-[#2663AC]">
                        {formatInteger(row.uniqueCalls)} calls
                      </span>
                    </div>
                  </button>
                ))}
              </div>
            </Card>

            <Card className="overflow-hidden bg-[linear-gradient(160deg,#ffffff_0%,#f6fbff_76%,#fff9f2_100%)] p-4">
              <div className="flex items-center justify-between gap-3">
                <h3 className="text-sm font-semibold text-slate-900">Lowest used CLM decks</h3>
                <span className="caption rounded-full border border-[#F7993A]/20 bg-[#F7993A]/12 px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[#d9852c]">Low</span>
              </div>
              <div className="mt-4 grid gap-2">
                {lowestDecks.map((row: any, index: number) => (
                  <button
                    key={`low-deck-${row.presentation}-${index}`}
                    type="button"
                    onClick={() => applyPresentationFilter(row.presentation)}
                    className={`rounded-2xl border bg-white px-3 py-3 text-left shadow-[0_18px_30px_-26px_rgba(163,92,28,0.28)] transition hover:border-[#d9852c] hover:bg-[#fffaf4] ${
                      activePresentation === row.presentation ? "border-[#d9852c] bg-[#fffaf4]" : "border-[#ecdcc9]"
                    }`}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="text-sm font-semibold text-slate-900">{row.presentation}</p>
                        <p className="mt-1 text-xs text-slate-500">
                          {row.product || "Unspecified product"} • {formatInteger(row.totalRecords)} records • {row.averageRecordsPerCall.toFixed(1)} avg rec/call
                        </p>
                      </div>
                      <span className="rounded-full bg-[#fff4e8] px-2.5 py-1 text-xs font-semibold text-[#d9852c]">
                        {formatInteger(row.uniqueCalls)} calls
                      </span>
                    </div>
                  </button>
                ))}
              </div>
            </Card>
          </div>
        </div>
      </details>

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-4 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "260ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f2f8ff_0%,#eaf2fd_100%)] px-4 py-3.5 text-sm font-semibold text-slate-900 shadow-[inset_0_1px_0_rgba(255,255,255,0.8)] transition hover:border-[#c5d9ef] hover:bg-[linear-gradient(120deg,#edf6ff_0%,#e3eefb_100%)]">
          Breakdown Explorer
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="mt-4 space-y-4">
          <div className="rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f8fbff_0%,#eef5ff_100%)] px-4 py-3 text-sm text-slate-600">
            Use this section after the monthly views and deck rankings to inspect country and product composition in more detail.
          </div>
          <div className="grid gap-4 xl:grid-cols-2">
          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Country Breakdown</h3>
            </div>
            <div className="max-h-[420px] overflow-auto">
              <table className="w-full text-left text-sm">
                <thead className="sticky top-0 bg-[linear-gradient(120deg,#eef5ff_0%,#f6faff_70%,#fff7ed_100%)] text-[11px] uppercase tracking-[0.16em] text-slate-500">
                  <tr>
                    <th className="px-4 py-3">Country</th>
                    <th className="px-4 py-3">Events</th>
                    <th className="px-4 py-3">CLM Linked</th>
                    <th className="px-4 py-3">Calls</th>
                    <th className="px-4 py-3">Presentations</th>
                  </tr>
                </thead>
                <tbody>
                  {data.countryBreakdown.map((row: any) => (
                    <tr key={row.country_code} className="border-t border-[#e2ebf7] text-sm transition duration-200 hover:bg-[#f3f9ff]">
                      <td className="px-4 py-3 text-slate-800">{row.country_code === "UNSPECIFIED" ? "Unspecified" : formatCountryLabel(row.country_code)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.total_clickstream_events)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.linked_events)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.unique_calls)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.unique_presentations)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Product Breakdown</h3>
            </div>
            <div className="max-h-[420px] overflow-auto">
              <table className="w-full text-left text-sm">
                <thead className="sticky top-0 bg-[linear-gradient(120deg,#eef5ff_0%,#f6faff_70%,#fff7ed_100%)] text-[11px] uppercase tracking-[0.16em] text-slate-500">
                  <tr>
                    <th className="px-4 py-3">Product</th>
                    <th className="px-4 py-3">Events</th>
                    <th className="px-4 py-3">CLM Linked</th>
                    <th className="px-4 py-3">Calls</th>
                    <th className="px-4 py-3">Presentations</th>
                  </tr>
                </thead>
                <tbody>
                  {data.productBreakdown.map((row: any) => (
                    <tr key={row.product} className="border-t border-[#e2ebf7] text-sm transition duration-200 hover:bg-[#f3f9ff]">
                      <td className="px-4 py-3 text-slate-800">{row.product}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.total_clickstream_events)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.linked_events)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.unique_calls)}</td>
                      <td className="px-4 py-3 text-slate-800">{formatInteger(row.unique_presentations)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
          </div>
        </div>
      </details>

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-0 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "300ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between border-b border-slate-200 px-4 py-4 text-sm font-semibold text-slate-900">
          CLM Activity Library
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="grid gap-4 p-4 xl:grid-cols-2">
          <Card className="overflow-hidden p-0">
            <div className="flex items-center justify-end border-b border-[#dbe7f5] px-5 py-3">
              <p className="caption rounded-full border border-[#2663AC]/15 bg-[#2663AC]/10 px-2.5 py-1 text-[10px] uppercase tracking-[0.18em] text-[#2663AC]">
                {data.recentClickstreamRows.length} records
              </p>
            </div>
            <div className="max-h-[520px] overflow-auto">
              <table className="w-full text-left">
                <thead className="sticky top-0 z-10 bg-[linear-gradient(120deg,#eef5ff_0%,#f6faff_70%,#fff7ed_100%)] text-[11px] uppercase tracking-[0.16em] text-slate-500">
                  <tr>
                    <th className="px-4 py-3">Call</th>
                    <th className="px-4 py-3">Country</th>
                    <th className="px-4 py-3">Product</th>
                    <th className="px-4 py-3">Track Element</th>
                    <th className="px-4 py-3">CLM</th>
                  </tr>
                </thead>
                <tbody>
                  {data.recentClickstreamRows.map((row: any) => (
                    <tr key={row.clickstreamName} className="border-t border-[#e2ebf7] text-sm transition duration-200 hover:bg-[#f3f9ff]">
                      <td className="px-4 py-3 align-top">
                        <p className="font-medium text-slate-800">{row.callName || row.clickstreamName}</p>
                        <p className="text-xs text-slate-500">{row.presentationId || row.keyMessage || "No presentation id"}</p>
                      </td>
                      <td className="px-4 py-3 text-slate-800">{row.countryCode ? formatCountryLabel(row.countryCode) : "N/A"}</td>
                      <td className="px-4 py-3 text-slate-800">{row.product || "Unspecified"}</td>
                      <td className="px-4 py-3 text-slate-800">{row.trackElementDescription || row.trackElementId || "N/A"}</td>
                      <td className="px-4 py-3 text-slate-800">{row.hasClm ? "Yes" : "No"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          <Card className="overflow-hidden p-0">
            <div className="flex items-center justify-end border-b border-[#dbe7f5] px-5 py-3">
              <p className="caption rounded-full border border-[#2663AC]/15 bg-[#2663AC]/10 px-2.5 py-1 text-[10px] uppercase tracking-[0.18em] text-[#2663AC]">
                {data.clmRows.length} records
              </p>
            </div>
            <div className="max-h-[520px] overflow-auto">
              <table className="w-full text-left">
                <thead className="sticky top-0 z-10 bg-[linear-gradient(120deg,#eef5ff_0%,#f6faff_70%,#fff7ed_100%)] text-[11px] uppercase tracking-[0.16em] text-slate-500">
                  <tr>
                    <th className="px-4 py-3">Call</th>
                    <th className="px-4 py-3">Product</th>
                    <th className="px-4 py-3">Presentation</th>
                    <th className="px-4 py-3">Key Message</th>
                  </tr>
                </thead>
                <tbody>
                  {data.clmRows.map((row: any, index: number) => (
                    <tr key={`${row.callName}-${row.presentationName}-${index}`} className="border-t border-[#e2ebf7] text-sm transition duration-200 hover:bg-[#f3f9ff]">
                      <td className="px-4 py-3 text-slate-800">{row.callName}</td>
                      <td className="px-4 py-3 text-slate-800">{row.product || row.presentationProduct || row.keyMessageProduct || "Unspecified"}</td>
                      <td className="px-4 py-3 text-slate-800">{row.presentationName || "N/A"}</td>
                      <td className="px-4 py-3 text-slate-800">{row.keyMessage || "N/A"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </div>
      </details>
    </>
  );
}
