"use client";

import { useState } from "react";
import {
  Phone,
  FileText,
  FileCheck,
  MessageCircle,
  AlertTriangle,
  AlertCircle,
  ChevronDown,
  ChevronUp,
} from "lucide-react";
import type { SignalCenter } from "@/lib/audit/types";

// ─── Props ────────────────────────────────────────────────────────────────────

interface Props {
  signalCenter: SignalCenter | null | undefined;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function urlPath(url: string): string {
  let path = url;
  try {
    path = new URL(url).pathname || "/";
  } catch {
    /* keep original */
  }
  return path.length > 45 ? path.slice(0, 44) + "…" : path;
}

function pct(n: number, total: number): string {
  if (!total) return "0%";
  return `${((n / total) * 100).toFixed(1)}%`;
}

function fmt(n: number): string {
  return n.toLocaleString();
}

// ─── Confidence config ────────────────────────────────────────────────────────

const confidenceConfig = {
  high: {
    label: "High confidence",
    class:
      "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",
  },
  moderate: {
    label: "Moderate confidence",
    class: "bg-amber-500/20 text-amber-400 border border-amber-500/30",
  },
  low: {
    label: "Limited data",
    class: "bg-slate-500/20 text-slate-400 border border-slate-500/30",
  },
};

// ─── Shared sub-components ────────────────────────────────────────────────────

function CardShell({
  id,
  title,
  subtitle,
  children,
}: {
  id: string;
  title: string;
  subtitle: string;
  children: React.ReactNode;
}) {
  return (
    <div
      id={id}
      className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden"
    >
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">{title}</h3>
        <p className="text-xs text-slate-400 mt-0.5">{subtitle}</p>
      </div>
      {children}
    </div>
  );
}

function LowConfidenceBanner() {
  return (
    <div className="mx-6 mt-4 flex items-start gap-2 rounded-xl bg-amber-500/10 border border-amber-500/20 px-4 py-3">
      <AlertTriangle className="w-4 h-4 text-amber-400 shrink-0 mt-0.5" />
      <p className="text-xs text-amber-300 leading-relaxed">
        Limited Site Tag data available. Confidence improves as more sessions
        accumulate.
      </p>
    </div>
  );
}

// ─── 1. Top Friction Events ───────────────────────────────────────────────────

function FrictionEventsCard({
  events,
  dataConfidence,
}: {
  events: SignalCenter["topFrictionEvents"];
  dataConfidence: SignalCenter["dataConfidence"];
}) {
  const [expanded, setExpanded] = useState(false);
  const visible = expanded ? events : events.slice(0, 5);

  return (
    <CardShell
      id="signal-friction"
      title="Top Friction Events"
      subtitle="UX signals indicating visitor frustration"
    >
      {dataConfidence === "low" && <LowConfidenceBanner />}

      <div className="px-6 py-5">
        {events.length === 0 ? (
          <p className="text-sm text-slate-400 italic">
            No friction events detected in this window.
          </p>
        ) : (
          <div className="space-y-3">
            {visible.map((evt, i) => {
              const isCritical =
                evt.severity === "critical" || evt.severity === "high";
              const iconClass = isCritical
                ? "text-red-400"
                : "text-amber-400";
              const countClass = isCritical
                ? "bg-red-500/20 text-red-300 border border-red-500/30"
                : "bg-amber-500/20 text-amber-300 border border-amber-500/30";

              return (
                <div
                  key={i}
                  className="flex items-start gap-3 rounded-xl bg-white/5 border border-white/8 px-4 py-3"
                >
                  {isCritical ? (
                    <AlertCircle
                      className={`w-4 h-4 shrink-0 mt-0.5 ${iconClass}`}
                    />
                  ) : (
                    <AlertTriangle
                      className={`w-4 h-4 shrink-0 mt-0.5 ${iconClass}`}
                    />
                  )}

                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-sm font-medium text-slate-200">
                        {evt.displayName}
                      </span>
                      <span
                        className={`text-[10px] font-semibold px-2 py-0.5 rounded-full ${countClass}`}
                      >
                        {fmt(evt.count)} events
                      </span>
                      <span className="text-[10px] text-slate-500 uppercase tracking-wide">
                        {evt.severity}
                      </span>
                    </div>

                    {evt.topAffectedPages.length > 0 && (
                      <div className="mt-1.5 flex flex-wrap gap-1.5">
                        {evt.topAffectedPages.slice(0, 3).map((p, j) => (
                          <span
                            key={j}
                            className="text-[10px] font-mono text-slate-500 bg-white/5 rounded px-1.5 py-0.5"
                          >
                            {urlPath(p.url)}{" "}
                            <span className="text-slate-600">×{p.count}</span>
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}

            {events.length > 5 && (
              <button
                onClick={() => setExpanded((x) => !x)}
                className="flex items-center gap-1 text-xs text-slate-400 hover:text-slate-200 transition-colors"
              >
                {expanded ? (
                  <>
                    <ChevronUp className="w-3.5 h-3.5" /> Show less
                  </>
                ) : (
                  <>
                    <ChevronDown className="w-3.5 h-3.5" /> Show all{" "}
                    {events.length} events
                  </>
                )}
              </button>
            )}
          </div>
        )}
      </div>
    </CardShell>
  );
}

// ─── 2. Conversion Funnel ─────────────────────────────────────────────────────

function FunnelCard({
  funnel,
  dataConfidence,
}: {
  funnel: SignalCenter["conversionFunnel"];
  dataConfidence: SignalCenter["dataConfidence"];
}) {
  const stages: Array<{ label: string; pct: number; sessions: number }> = [
    { label: "Landing", pct: 100, sessions: 0 },
    {
      label: "Engagement",
      pct: funnel.engagement.percent,
      sessions: funnel.engagement.sessions,
    },
    {
      label: "Intent Signal",
      pct: funnel.intent.percent,
      sessions: funnel.intent.sessions,
    },
    {
      label: "Conversion",
      pct: funnel.conversion.percent,
      sessions: funnel.conversion.sessions,
    },
  ];

  const dropoffs = [
    funnel.engagement.dropoffFromPrior,
    funnel.intent.dropoffFromPrior,
    funnel.conversion.dropoffFromPrior,
  ];

  return (
    <CardShell
      id="signal-funnel"
      title="Conversion Funnel"
      subtitle="4-stage visitor journey from landing to conversion"
    >
      {dataConfidence === "low" && <LowConfidenceBanner />}

      <div className="px-6 py-5 space-y-6">
        {/* Funnel bars */}
        <div className="space-y-1">
          {stages.map((stage, i) => (
            <div key={stage.label}>
              <div className="flex items-center gap-3 mb-0.5">
                <span className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 w-24 shrink-0">
                  {stage.label}
                </span>
                <div className="flex-1 relative h-7 bg-white/5 rounded-lg overflow-hidden">
                  <div
                    className="h-full rounded-lg bg-gradient-to-r from-indigo-500/70 to-indigo-400/50 transition-all"
                    style={{ width: `${Math.max(stage.pct, 1)}%` }}
                  />
                  <span className="absolute inset-0 flex items-center px-3 text-xs font-semibold text-white/80">
                    {stage.pct.toFixed(1)}%
                    {stage.sessions > 0 && (
                      <span className="ml-2 text-slate-400 font-normal">
                        {fmt(stage.sessions)} sessions
                      </span>
                    )}
                  </span>
                </div>
              </div>

              {/* Drop-off between stages */}
              {i < stages.length - 1 && dropoffs[i] != null && (
                <div className="flex items-center gap-3 py-0.5">
                  <span className="w-24 shrink-0" />
                  <span className="text-[10px] font-semibold text-red-400">
                    ↓ -{dropoffs[i].toFixed(1)}% drop-off
                  </span>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Biggest drop-off callout */}
        <div className="flex items-start gap-2 rounded-xl bg-red-500/10 border border-red-500/20 px-4 py-3">
          <AlertTriangle className="w-4 h-4 text-red-400 shrink-0 mt-0.5" />
          <p className="text-xs text-red-300 leading-relaxed">
            <span className="font-semibold">Biggest drop-off:</span>{" "}
            {funnel.biggestDropoff.from} → {funnel.biggestDropoff.to} (
            {funnel.biggestDropoff.percent.toFixed(1)}% lost)
          </p>
        </div>

        {/* Top drop-off pages */}
        {funnel.topDropoffPages.length > 0 && (
          <div>
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">
              Top drop-off pages
            </p>
            <div className="space-y-1.5">
              {funnel.topDropoffPages.slice(0, 5).map((page, i) => (
                <div
                  key={i}
                  className="flex items-center gap-3 text-xs rounded-lg bg-white/4 px-3 py-2"
                >
                  <span className="font-mono text-slate-300 truncate flex-1 min-w-0">
                    {urlPath(page.url)}
                  </span>
                  <span className="text-slate-500 shrink-0">{page.stage}</span>
                  <span className="text-red-400 font-semibold shrink-0 tabular-nums">
                    -{fmt(page.sessionsLost)} sessions
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </CardShell>
  );
}

// ─── 3. Form Abandonment ──────────────────────────────────────────────────────

function FormAbandonmentCard({
  formAbandonment,
  dataConfidence,
}: {
  formAbandonment: NonNullable<SignalCenter["formAbandonment"]>;
  dataConfidence: SignalCenter["dataConfidence"];
}) {
  return (
    <CardShell
      id="signal-forms"
      title="Form Abandonment"
      subtitle="Field-level friction in conversion forms"
    >
      {dataConfidence === "low" && <LowConfidenceBanner />}

      {/* Top stats */}
      <div className="grid grid-cols-3 divide-x divide-white/10 border-b border-white/10">
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Starts
          </p>
          <div className="text-3xl font-black tabular-nums text-white leading-none">
            {fmt(formAbandonment.totalStarts)}
          </div>
        </div>
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Completes
          </p>
          <div className="text-3xl font-black tabular-nums text-white leading-none">
            {fmt(formAbandonment.totalCompletes)}
          </div>
        </div>
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Abandon rate
          </p>
          <div
            className={`text-3xl font-black tabular-nums leading-none ${
              formAbandonment.abandonRate > 60
                ? "text-red-400"
                : formAbandonment.abandonRate > 35
                ? "text-amber-400"
                : "text-emerald-400"
            }`}
          >
            {formAbandonment.abandonRate.toFixed(1)}%
          </div>
        </div>
      </div>

      {/* Top abandoned fields */}
      {formAbandonment.topAbandonedFields.length > 0 && (
        <div className="px-6 py-5 space-y-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">
            Top abandoned fields
          </p>
          <div className="space-y-4">
            {formAbandonment.topAbandonedFields.slice(0, 5).map((field, i) => (
              <div key={i} className="space-y-1.5">
                <div className="flex items-center justify-between gap-3">
                  <span className="text-sm font-medium text-slate-200 truncate">
                    {field.fieldName}
                  </span>
                  <div className="flex items-center gap-3 shrink-0 text-xs tabular-nums">
                    <span className="text-slate-400">
                      {(field.medianTimeSpent / 1000).toFixed(1)}s median
                    </span>
                    {field.errorRate > 0 && (
                      <span className="text-red-400">
                        {field.errorRate.toFixed(0)}% errors
                      </span>
                    )}
                    <span className="font-semibold text-amber-400">
                      {field.abandonRate.toFixed(1)}%
                    </span>
                  </div>
                </div>

                {/* Bar */}
                <div className="h-2 bg-white/8 rounded-full overflow-hidden">
                  <div
                    className="h-full rounded-full bg-amber-500/70"
                    style={{ width: `${Math.min(field.abandonRate, 100)}%` }}
                  />
                </div>

                {/* Recommendation */}
                {field.recommendation && (
                  <p className="text-[10px] text-slate-500 italic leading-relaxed">
                    {field.recommendation}
                  </p>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </CardShell>
  );
}

// ─── 4. Channel Mix ───────────────────────────────────────────────────────────

const CHANNEL_META: Record<
  "phone" | "form" | "paperwork" | "chat",
  { label: string; Icon: React.ElementType }
> = {
  phone: { label: "Phone", Icon: Phone },
  form: { label: "Form", Icon: FileText },
  paperwork: { label: "Paperwork", Icon: FileCheck },
  chat: { label: "Chat", Icon: MessageCircle },
};

function ChannelMixCard({
  channelMix,
  dataConfidence,
}: {
  channelMix: SignalCenter["channelMix"];
  dataConfidence: SignalCenter["dataConfidence"];
}) {
  const channels = (
    ["phone", "form", "paperwork", "chat"] as const
  ).map((key) => ({
    key,
    ...CHANNEL_META[key],
    ...channelMix[key],
  }));

  const maxCount = Math.max(...channels.map((c) => c.count));
  const topChannel = channels.find((c) => c.count === maxCount);

  const totalConversions = channels.reduce((sum, c) => sum + c.count, 0);

  return (
    <CardShell
      id="signal-channels"
      title="Conversion Channels"
      subtitle="How visitors are converting"
    >
      {dataConfidence === "low" && <LowConfidenceBanner />}

      <div className="px-6 py-5 space-y-4">
        {/* 2×2 grid */}
        <div className="grid grid-cols-2 gap-3">
          {channels.map((ch) => {
            const isTop = ch.count === maxCount && maxCount > 0;
            return (
              <div
                key={ch.key}
                className={`rounded-xl border px-4 py-4 ${
                  isTop
                    ? "bg-indigo-500/10 border-indigo-500/30"
                    : "bg-white/5 border-white/8"
                }`}
              >
                <div className="flex items-center gap-2 mb-3">
                  <ch.Icon
                    className={`w-4 h-4 ${
                      isTop ? "text-indigo-400" : "text-slate-400"
                    }`}
                  />
                  <span
                    className={`text-xs font-semibold ${
                      isTop ? "text-indigo-300" : "text-slate-300"
                    }`}
                  >
                    {ch.label}
                  </span>
                  {isTop && (
                    <span className="ml-auto text-[9px] font-bold uppercase tracking-widest text-indigo-400 bg-indigo-500/20 px-1.5 py-0.5 rounded-full">
                      Top
                    </span>
                  )}
                </div>

                <div className="text-2xl font-black tabular-nums text-white leading-none mb-1">
                  {fmt(ch.count)}
                </div>

                <div className="flex items-center gap-2 text-[10px] text-slate-400">
                  <span>{ch.share.toFixed(1)}% share</span>
                  {ch.conversionRate != null && (
                    <>
                      <span className="text-slate-600">·</span>
                      <span className="text-emerald-400">
                        {ch.conversionRate.toFixed(1)}% conv.
                      </span>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {/* Callout */}
        {topChannel && totalConversions > 0 && (
          <div className="rounded-xl bg-indigo-500/10 border border-indigo-500/20 px-4 py-3">
            <p className="text-xs text-indigo-300 leading-relaxed">
              <span className="font-semibold">Most converting channel:</span>{" "}
              {topChannel.label} with{" "}
              {pct(topChannel.count, totalConversions)} of all conversions (
              {fmt(topChannel.count)})
            </p>
          </div>
        )}
      </div>
    </CardShell>
  );
}

// ─── 5. Scroll to Conversion ──────────────────────────────────────────────────

function ScrollToConversionCard({
  scrollToConversion,
  dataConfidence,
}: {
  scrollToConversion: SignalCenter["scrollToConversion"];
  dataConfidence: SignalCenter["dataConfidence"];
}) {
  const stc = scrollToConversion;

  return (
    <CardShell
      id="signal-scroll"
      title="Scroll-to-Conversion"
      subtitle="Where visitors are on the page when they convert"
    >
      {dataConfidence === "low" && <LowConfidenceBanner />}

      <div className="px-6 py-5 space-y-5">
        {/* Median stat */}
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Median scroll depth at conversion
          </p>
          <div className="flex items-end gap-3">
            <div className="text-3xl font-black tabular-nums text-white leading-none">
              {stc.medianScrollDepthBeforeConversion}%
            </div>
            <div className="pb-1 flex-1">
              <div className="h-2 bg-white/8 rounded-full overflow-hidden">
                <div
                  className="h-full rounded-full bg-indigo-500/70"
                  style={{
                    width: `${Math.min(
                      stc.medianScrollDepthBeforeConversion,
                      100
                    )}%`,
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Two panels */}
        <div className="grid sm:grid-cols-2 gap-3">
          {/* High scroll, low conversion */}
          <div className="rounded-xl border border-red-500/25 bg-red-500/8 p-4">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-red-400 mb-2.5">
              High scroll · Low conversion
            </p>
            {stc.highScrollLowConvPages.length === 0 ? (
              <p className="text-xs text-slate-500 italic">None detected.</p>
            ) : (
              <div className="space-y-2">
                {stc.highScrollLowConvPages.slice(0, 3).map((p, i) => (
                  <div key={i} className="space-y-0.5">
                    <p className="text-[11px] font-mono text-slate-300 truncate">
                      {urlPath(p.url)}
                    </p>
                    <p className="text-[10px] text-slate-500">
                      {p.avgScroll.toFixed(0)}% avg scroll ·{" "}
                      {fmt(p.conversions)} conversions
                    </p>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Low scroll, high conversion */}
          <div className="rounded-xl border border-emerald-500/25 bg-emerald-500/8 p-4">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-emerald-400 mb-2.5">
              Low scroll · High conversion
            </p>
            {stc.lowScrollHighConvPages.length === 0 ? (
              <p className="text-xs text-slate-500 italic">None detected.</p>
            ) : (
              <div className="space-y-2">
                {stc.lowScrollHighConvPages.slice(0, 3).map((p, i) => (
                  <div key={i} className="space-y-0.5">
                    <p className="text-[11px] font-mono text-slate-300 truncate">
                      {urlPath(p.url)}
                    </p>
                    <p className="text-[10px] text-slate-500">
                      {p.avgScroll.toFixed(0)}% avg scroll ·{" "}
                      {fmt(p.conversions)} conversions
                    </p>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Recommendation */}
        {stc.recommendation && (
          <p className="text-xs text-slate-400 italic leading-relaxed">
            {stc.recommendation}
          </p>
        )}
      </div>
    </CardShell>
  );
}

// ─── 6. Device & Geo ──────────────────────────────────────────────────────────

function DeviceGeoCard({
  deviceGeo,
  dataConfidence,
}: {
  deviceGeo: NonNullable<SignalCenter["deviceGeo"]>;
  dataConfidence: SignalCenter["dataConfidence"];
}) {
  const { deviceMix, mobileDesktopDelta, topMetros, geoConcentration } =
    deviceGeo;

  const deltaNegative = mobileDesktopDelta < -5;
  const deltaPositive = mobileDesktopDelta >= 5;

  const devices: Array<{
    key: "mobile" | "desktop" | "tablet";
    label: string;
  }> = [
    { key: "mobile", label: "Mobile" },
    { key: "desktop", label: "Desktop" },
    { key: "tablet", label: "Tablet" },
  ];

  return (
    <CardShell
      id="signal-device"
      title="Device & Geographic Breakdown"
      subtitle="Visitor mix and where conversions come from"
    >
      {dataConfidence === "low" && <LowConfidenceBanner />}

      <div className="px-6 py-5 space-y-6">
        {/* Device tiles */}
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
            Device mix
          </p>
          <div className="grid grid-cols-3 gap-3">
            {devices.map(({ key, label }) => {
              const d = deviceMix[key];
              return (
                <div
                  key={key}
                  className="rounded-xl bg-white/5 border border-white/8 px-4 py-4"
                >
                  <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">
                    {label}
                  </p>
                  <div className="text-2xl font-black tabular-nums text-white leading-none mb-1">
                    {fmt(d.sessions)}
                  </div>
                  <div className="text-[10px] text-slate-400 space-y-0.5">
                    <div>{d.share.toFixed(1)}% of sessions</div>
                    <div className="text-emerald-400">
                      {d.conversionRate.toFixed(2)}% conv.
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Mobile vs desktop delta */}
        <div
          className={`rounded-xl border px-4 py-3 ${
            deltaNegative
              ? "bg-red-500/10 border-red-500/20"
              : deltaPositive
              ? "bg-emerald-500/10 border-emerald-500/20"
              : "bg-white/5 border-white/10"
          }`}
        >
          <p
            className={`text-xs leading-relaxed ${
              deltaNegative
                ? "text-red-300"
                : deltaPositive
                ? "text-emerald-300"
                : "text-slate-300"
            }`}
          >
            <span className="font-semibold">Mobile vs. desktop delta:</span>{" "}
            {mobileDesktopDelta > 0 ? "+" : ""}
            {mobileDesktopDelta.toFixed(1)}pp conversion rate difference
            {deltaNegative && " — mobile is significantly underperforming."}
            {deltaPositive && " — mobile is outperforming desktop."}
          </p>
        </div>

        {/* Top metros */}
        {topMetros.length > 0 && (
          <div>
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
              Top metros
            </p>
            <div className="overflow-x-auto">
              <table className="w-full text-xs min-w-[300px]">
                <thead>
                  <tr className="text-slate-500 border-b border-white/8">
                    <th className="text-left font-medium pb-2 pr-4">City</th>
                    <th className="text-right font-medium pb-2 px-3">
                      Sessions
                    </th>
                    <th className="text-right font-medium pb-2 pl-3">
                      Conv. rate
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {topMetros.slice(0, 5).map((metro, i) => (
                    <tr key={i}>
                      <td className="py-2.5 pr-4 text-slate-300">
                        {metro.city}
                        {metro.region ? (
                          <span className="text-slate-500">, {metro.region}</span>
                        ) : null}
                      </td>
                      <td className="py-2.5 px-3 text-right tabular-nums text-slate-300">
                        {fmt(metro.sessions)}
                      </td>
                      <td className="py-2.5 pl-3 text-right tabular-nums text-emerald-400 font-semibold">
                        {metro.conversionRate.toFixed(2)}%
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Geo concentration callout */}
        {topMetros.length > 0 && (
          <div className="rounded-xl bg-white/5 border border-white/8 px-4 py-3">
            <p className="text-xs text-slate-300 leading-relaxed">
              <span className="font-semibold text-white">
                {geoConcentration.toFixed(0)}%
              </span>{" "}
              of conversions from top metro:{" "}
              <span className="text-indigo-300">{topMetros[0]?.city}</span>
            </p>
          </div>
        )}
      </div>
    </CardShell>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

export function SignalCenterSection({ signalCenter }: Props) {
  if (!signalCenter) return null;

  const conf = confidenceConfig[signalCenter.dataConfidence];

  return (
    <section className="space-y-6">
      {/* Section header */}
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
        <div>
          <h2 className="text-xl font-bold text-white">Signal Center</h2>
          <p className="text-sm text-slate-400 mt-1">
            Behavioral telemetry from real visitors over the last{" "}
            {signalCenter.windowDays} days
          </p>
        </div>

        <div className="flex items-center gap-3 shrink-0">
          <span
            className={`text-[10px] font-semibold uppercase tracking-widest px-2.5 py-1 rounded-full ${conf.class}`}
          >
            {conf.label}
          </span>
          <span className="text-sm font-semibold tabular-nums text-white">
            {fmt(signalCenter.totalSessions)}{" "}
            <span className="font-normal text-slate-400">sessions</span>
          </span>
        </div>
      </div>

      {/* Sub-section cards */}
      <FrictionEventsCard
        events={signalCenter.topFrictionEvents}
        dataConfidence={signalCenter.dataConfidence}
      />

      <FunnelCard
        funnel={signalCenter.conversionFunnel}
        dataConfidence={signalCenter.dataConfidence}
      />

      {signalCenter.formAbandonment != null && (
        <FormAbandonmentCard
          formAbandonment={signalCenter.formAbandonment}
          dataConfidence={signalCenter.dataConfidence}
        />
      )}

      <ChannelMixCard
        channelMix={signalCenter.channelMix}
        dataConfidence={signalCenter.dataConfidence}
      />

      <ScrollToConversionCard
        scrollToConversion={signalCenter.scrollToConversion}
        dataConfidence={signalCenter.dataConfidence}
      />

      {signalCenter.deviceGeo != null && (
        <DeviceGeoCard
          deviceGeo={signalCenter.deviceGeo}
          dataConfidence={signalCenter.dataConfidence}
        />
      )}
    </section>
  );
}
