"use client";

import { startTransition, useRef, useState } from "react";

import { KavenixStatisticsActionDetailDialog } from "@/components/kavenix-statistics-action-detail-dialog";
import { KavenixStatisticsDetailDialog } from "@/components/kavenix-statistics-detail-dialog";

import type {
  KavenixStatistics,
  KavenixStatisticsActionItem,
  KavenixStatisticsActionSeverity,
  KavenixStatisticsDailyPoint,
  KavenixStatisticsMetricKey,
  KavenixStatisticsRange,
} from "@/lib/kavenix-statistics-types";

type StatisticsResponse = {
  message?: string;
  ok?: boolean;
  statistics?: KavenixStatistics;
};

type DetailTab = "adoption" | "domains" | "funnel";
type ActionFilter = "all" | KavenixStatisticsActionSeverity;

const RANGE_OPTIONS: KavenixStatisticsRange[] = [7, 30, 90, 365];
const METRIC_DEFINITIONS: Array<{
  color: string;
  key: KavenixStatisticsMetricKey;
  label: string;
}> = [
  { color: "#2f6df6", key: "signups", label: "신규 고객" },
  { color: "#16a36a", key: "verifiedDomains", label: "도메인 연결" },
  { color: "#0f8fa9", key: "inboundMessages", label: "수신" },
  { color: "#e3782f", key: "outboundMessages", label: "발송" },
  { color: "#c5465d", key: "revenue", label: "결제 매출" },
  { color: "#64748b", key: "successfulLogins", label: "로그인" },
];

function formatNumber(value: number) {
  return value.toLocaleString("ko-KR");
}

function formatCurrency(value: number) {
  return `${Math.round(value).toLocaleString("ko-KR")}원`;
}

function formatMetricValue(key: KavenixStatisticsMetricKey, value: number) {
  return key === "revenue" ? formatCurrency(value) : formatNumber(value);
}

function formatPercent(value: number, digits = 1) {
  return `${value.toFixed(digits)}%`;
}

function ratio(value: number, base: number) {
  return base > 0 ? (value / base) * 100 : 0;
}

function comparisonMeta(current: number, previous: number) {
  if (previous <= 0) {
    return current > 0
      ? { label: "신규", positive: true }
      : { label: "변화 없음", positive: null };
  }

  const delta = ((current - previous) / previous) * 100;
  return {
    label: `${delta > 0 ? "+" : ""}${delta.toFixed(1)}%`,
    positive: delta === 0 ? null : delta > 0,
  };
}

function formatDateLabel(value: string, includeYear = false) {
  const [year, month, day] = value.split("-").map(Number);
  return new Intl.DateTimeFormat("ko-KR", {
    day: "numeric",
    month: "short",
    ...(includeYear ? { year: "numeric" } : {}),
  }).format(new Date(Date.UTC(year, month - 1, day)));
}

function formatDateTime(value: string | null) {
  if (!value) {
    return "-";
  }

  return new Intl.DateTimeFormat("ko-KR", {
    day: "numeric",
    hour: "2-digit",
    hour12: true,
    minute: "2-digit",
    month: "short",
    timeZone: "Asia/Seoul",
  }).format(new Date(value));
}

function MetricComparison({
  current,
  previous,
  show,
}: {
  current: number;
  previous: number;
  show: boolean;
}) {
  if (!show) {
    return null;
  }

  const comparison = comparisonMeta(current, previous);
  const tone =
    comparison.positive === true
      ? "text-[#23845a]"
      : comparison.positive === false
        ? "text-[#c14d61]"
        : "text-[#8290a5]";

  return (
    <span className={`text-[11px] font-semibold ${tone}`}>
      {comparison.label}
    </span>
  );
}

function Sparkline({
  color,
  hoverIndex,
  metricKey,
  onSelectIndex,
  points,
  setHoverIndex,
}: {
  color: string;
  hoverIndex: number | null;
  metricKey: KavenixStatisticsMetricKey;
  onSelectIndex: (index: number) => void;
  points: KavenixStatisticsDailyPoint[];
  setHoverIndex: (index: number | null) => void;
}) {
  const width = 1000;
  const height = 82;
  const values = points.map((point) => point[metricKey]);
  const maximum = Math.max(1, ...values);
  const coordinates = values.map((value, index) => ({
    x: points.length <= 1 ? width / 2 : (index / (points.length - 1)) * width,
    y: height - 8 - (value / maximum) * (height - 18),
  }));
  const path = coordinates
    .map((point, index) => `${index === 0 ? "M" : "L"}${point.x.toFixed(2)},${point.y.toFixed(2)}`)
    .join(" ");
  const area = coordinates.length
    ? `${path} L${coordinates.at(-1)?.x ?? width},${height} L${coordinates[0].x},${height} Z`
    : "";
  const hoveredPoint = hoverIndex === null ? null : coordinates[hoverIndex];
  const pointIndexFromClientX = (clientX: number, left: number, renderedWidth: number) => {
    const relativeX = Math.max(0, Math.min(renderedWidth, clientX - left));
    return Math.round(
      (relativeX / Math.max(1, renderedWidth)) * Math.max(0, points.length - 1),
    );
  };

  return (
    <svg
      viewBox={`0 0 ${width} ${height}`}
      preserveAspectRatio="none"
      role="button"
      tabIndex={0}
      aria-label={`${METRIC_DEFINITIONS.find((metric) => metric.key === metricKey)?.label ?? "통계"} 일별 추세. 선택하면 상세 항목을 확인합니다.`}
      className="h-[82px] w-full cursor-pointer touch-none overflow-visible focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2f6df6]/30"
      onMouseLeave={() => setHoverIndex(null)}
      onMouseMove={(event) => {
        const bounds = event.currentTarget.getBoundingClientRect();
        const nextIndex = pointIndexFromClientX(event.clientX, bounds.left, bounds.width);
        setHoverIndex(nextIndex);
      }}
      onClick={(event) => {
        const bounds = event.currentTarget.getBoundingClientRect();
        const nextIndex = pointIndexFromClientX(event.clientX, bounds.left, bounds.width);
        setHoverIndex(nextIndex);
        onSelectIndex(nextIndex);
      }}
      onKeyDown={(event) => {
        if (event.key !== "Enter" && event.key !== " ") {
          return;
        }

        event.preventDefault();
        const nextIndex = hoverIndex ?? Math.max(0, points.length - 1);
        setHoverIndex(nextIndex);
        onSelectIndex(nextIndex);
      }}
    >
      <defs>
        <linearGradient id={`metric-fill-${metricKey}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.2" />
          <stop offset="100%" stopColor={color} stopOpacity="0.015" />
        </linearGradient>
      </defs>
      {[20, 41, 62].map((y) => (
        <line key={y} x1="0" x2={width} y1={y} y2={y} stroke="#edf2f8" strokeWidth="1" />
      ))}
      {area ? <path d={area} fill={`url(#metric-fill-${metricKey})`} /> : null}
      {path ? (
        <path
          d={path}
          fill="none"
          stroke={color}
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth="2.2"
          vectorEffect="non-scaling-stroke"
        />
      ) : null}
      {hoveredPoint ? (
        <>
          <line
            x1={hoveredPoint.x}
            x2={hoveredPoint.x}
            y1="4"
            y2={height}
            stroke="#8ba0bd"
            strokeDasharray="3 4"
            vectorEffect="non-scaling-stroke"
          />
          <circle
            cx={hoveredPoint.x}
            cy={hoveredPoint.y}
            fill="white"
            r="4.5"
            stroke={color}
            strokeWidth="2"
            vectorEffect="non-scaling-stroke"
          />
        </>
      ) : null}
    </svg>
  );
}

function AdoptionRow({ count, label, total }: { count: number; label: string; total: number }) {
  const rate = ratio(count, total);

  return (
    <div className="grid grid-cols-[112px_minmax(0,1fr)_76px] items-center gap-3 py-2.5">
      <p className="text-[12px] font-semibold text-[#344767]">{label}</p>
      <div className="h-2 overflow-hidden rounded-full bg-[#edf2f8]">
        <div
          className="h-full rounded-full bg-[#2f6df6] transition-[width] duration-500"
          style={{ width: `${Math.min(100, rate)}%` }}
        />
      </div>
      <p className="text-right text-[12px] font-semibold text-[#263957]">
        {count}명 <span className="font-medium text-[#8492a8]">{formatPercent(rate, 0)}</span>
      </p>
    </div>
  );
}

function FunnelPanel({ data, showComparison }: { data: KavenixStatistics; showComparison: boolean }) {
  const steps = [
    { key: "signups", label: "가입", value: data.currentFunnel.signups },
    { key: "connected", label: "도메인 연결", value: data.currentFunnel.connected },
    { key: "sentMail", label: "첫 발송 경험", value: data.currentFunnel.sentMail },
    { key: "paid", label: "성장 플랜", value: data.currentFunnel.paid },
  ] as const;
  const previous = data.previousFunnel;

  return (
    <div className="grid gap-px overflow-hidden rounded-[14px] border border-[#e3eaf5] bg-[#e8eef7] sm:grid-cols-4">
      {steps.map((step, index) => {
        const previousValue = previous[step.key];
        const conversion = index === 0 ? 100 : ratio(step.value, data.currentFunnel.signups);

        return (
          <div key={step.key} className="relative bg-white px-4 py-4">
            <div className="flex items-center justify-between gap-2">
              <p className="text-[12px] font-semibold text-[#71819b]">{step.label}</p>
              {index > 0 ? (
                <span className="text-[10px] font-semibold text-[#2f6df6]">
                  {formatPercent(conversion)}
                </span>
              ) : null}
            </div>
            <div className="mt-2 flex items-end gap-2">
              <p className="text-[24px] font-semibold tracking-[-0.05em] text-[#16233c]">
                {formatNumber(step.value)}
              </p>
              <MetricComparison current={step.value} previous={previousValue} show={showComparison} />
            </div>
            {index < steps.length - 1 ? (
              <span className="absolute -right-2.5 top-1/2 z-10 hidden h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full border border-[#dce6f5] bg-white text-[#8191aa] sm:flex">
                →
              </span>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}

export function KavenixStatisticsDashboard({ initialData }: { initialData: KavenixStatistics }) {
  const [actionFilter, setActionFilter] = useState<ActionFilter>("all");
  const [data, setData] = useState(initialData);
  const [detailTab, setDetailTab] = useState<DetailTab>("funnel");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [selectedAction, setSelectedAction] = useState<KavenixStatisticsActionItem | null>(null);
  const [selectedMetrics, setSelectedMetrics] = useState<KavenixStatisticsMetricKey[]>([
    "signups",
    "verifiedDomains",
    "inboundMessages",
    "outboundMessages",
    "revenue",
    "successfulLogins",
  ]);
  const [selectedDetail, setSelectedDetail] = useState<{
    date: string;
    label: string;
    metricKey: KavenixStatisticsMetricKey;
    value: number;
  } | null>(null);
  const [showComparison, setShowComparison] = useState(true);
  const requestIdRef = useRef(0);

  function resolveActionItem(actionId: KavenixStatisticsActionItem["id"]) {
    setData((current) => ({
      ...current,
      actionItems: current.actionItems
        .map((item) =>
          item.id === actionId
            ? { ...item, count: Math.max(0, item.count - 1) }
            : item,
        )
        .filter((item) => item.count > 0),
    }));
    setSelectedAction((current) =>
      current?.id === actionId
        ? { ...current, count: Math.max(0, current.count - 1) }
        : current,
    );
  }

  async function changeRange(rangeDays: KavenixStatisticsRange) {
    if (rangeDays === data.rangeDays || loading) {
      return;
    }

    const requestId = ++requestIdRef.current;
    setLoading(true);
    setErrorMessage(null);
    setHoverIndex(null);
    setSelectedAction(null);
    setSelectedDetail(null);

    try {
      const response = await fetch(`/api/kavenix/statistics?range=${rangeDays}`, {
        cache: "no-store",
        credentials: "same-origin",
      });
      const payload = (await response.json().catch(() => null)) as StatisticsResponse | null;

      if (!response.ok || !payload?.ok || !payload.statistics) {
        throw new Error(payload?.message || "통계를 불러오지 못했습니다.");
      }

      if (requestId !== requestIdRef.current) {
        return;
      }

      startTransition(() => setData(payload.statistics as KavenixStatistics));
      const url = new URL(window.location.href);
      url.searchParams.set("view", "statistics");
      url.searchParams.set("statsRange", String(rangeDays));
      window.history.replaceState(null, "", url);
    } catch (error) {
      if (requestId === requestIdRef.current) {
        setErrorMessage(error instanceof Error ? error.message : "통계를 불러오지 못했습니다.");
      }
    } finally {
      if (requestId === requestIdRef.current) {
        setLoading(false);
      }
    }
  }

  function toggleMetric(metric: KavenixStatisticsMetricKey) {
    setSelectedMetrics((current) => {
      if (current.includes(metric)) {
        return current.length === 1 ? current : current.filter((item) => item !== metric);
      }

      return [...current, metric];
    });
  }

  const paymentSuccessRate = ratio(
    data.current.successfulCharges,
    data.current.paymentAttempts,
  );
  const previousPaymentSuccessRate = ratio(
    data.previous.successfulCharges,
    data.previous.paymentAttempts,
  );
  const kpis = [
    {
      current: data.current.signups,
      formatter: formatNumber,
      label: "신규 고객",
      previous: data.previous.signups,
      suffix: "명",
    },
    {
      current: data.current.verifiedDomains,
      formatter: formatNumber,
      label: "연결 완료",
      previous: data.previous.verifiedDomains,
      suffix: "개",
    },
    {
      current: data.current.activeMailboxes,
      formatter: formatNumber,
      label: "실사용 메일함",
      previous: data.previous.activeMailboxes,
      suffix: "개",
    },
    {
      current: data.current.outboundMessages,
      formatter: formatNumber,
      label: "메일 발송",
      previous: data.previous.outboundMessages,
      suffix: "건",
    },
    {
      current: data.current.revenue,
      formatter: formatCurrency,
      label: "결제 매출",
      previous: data.previous.revenue,
      suffix: "",
    },
    {
      current: paymentSuccessRate,
      formatter: (value: number) => formatPercent(value),
      label: "결제 성공률",
      previous: previousPaymentSuccessRate,
      suffix: "",
    },
  ];
  const hoveredDate = hoverIndex === null ? null : data.currentDaily[hoverIndex]?.date;
  const filteredActions = data.actionItems.filter(
    (item) => actionFilter === "all" || item.severity === actionFilter,
  );
  const severityCounts = data.actionItems.reduce(
    (result, item) => ({ ...result, [item.severity]: result[item.severity] + item.count }),
    { critical: 0, info: 0, warning: 0 },
  );

  return (
    <div className={`relative transition-opacity ${loading ? "opacity-70" : "opacity-100"}`}>
      <section className="border-b border-[#e8eef7] bg-[#fbfdff] px-3 py-3 sm:px-4 lg:px-8">
        <div className="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
          <div className="flex flex-wrap items-center gap-1.5" aria-label="운영 통계 기간">
            {RANGE_OPTIONS.map((range) => (
              <button
                key={range}
                type="button"
                disabled={loading}
                onClick={() => void changeRange(range)}
                className={`h-9 rounded-[9px] px-3 text-[12px] font-semibold transition-colors disabled:cursor-wait ${
                  data.rangeDays === range
                    ? "bg-[#162f62] text-white"
                    : "border border-[#dce5f2] bg-white text-[#657792] hover:border-[#bcd0ee] hover:text-[#2f6df6]"
                }`}
              >
                {range === 365 ? "1년" : `${range}일`}
              </button>
            ))}
          </div>
          <div className="flex flex-wrap items-center gap-3">
            <p className="text-[11px] text-[#8190a6]">
              고객 계정 기준 · {formatDateLabel(data.currentDaily[0]?.date ?? "", true)}–{formatDateLabel(data.currentDaily.at(-1)?.date ?? "")}
            </p>
            <button
              type="button"
              role="switch"
              aria-checked={showComparison}
              onClick={() => setShowComparison((current) => !current)}
              className="inline-flex items-center gap-2 text-[12px] font-semibold text-[#536681]"
            >
              <span
                className={`relative inline-flex h-5 w-9 shrink-0 rounded-full transition-colors ${showComparison ? "bg-[#2f6df6]" : "bg-[#cfd8e6]"}`}
              >
                <span
                  className={`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-transform ${showComparison ? "translate-x-4" : "translate-x-0"}`}
                />
              </span>
              직전 기간 비교
            </button>
          </div>
        </div>
        {errorMessage ? (
          <p className="mt-2 text-[12px] font-medium text-[#bd4b5e]">{errorMessage}</p>
        ) : null}
      </section>

      <section className="grid border-b border-[#e8eef7] bg-white sm:grid-cols-2 xl:grid-cols-6">
        {kpis.map((item, index) => (
          <div
            key={item.label}
            className={`px-4 py-4 lg:px-5 ${index > 0 ? "border-t border-[#edf2f8] sm:border-l xl:border-t-0" : ""} ${index === 2 ? "sm:border-l-0 xl:border-l" : ""} ${index === 4 ? "sm:border-l-0 xl:border-l" : ""}`}
          >
            <div className="flex items-center justify-between gap-2">
              <p className="text-[11px] font-semibold text-[#7b8ba3]">{item.label}</p>
              <MetricComparison current={item.current} previous={item.previous} show={showComparison} />
            </div>
            <p className="mt-1.5 text-[20px] font-semibold tracking-[-0.04em] text-[#16233c]">
              {item.formatter(item.current)}
              {item.suffix ? <span className="ml-0.5 text-[12px] font-medium text-[#7e8da3]">{item.suffix}</span> : null}
            </p>
          </div>
        ))}
      </section>

      <section className="border-b border-[#e8eef7] px-3 py-5 sm:px-4 lg:px-8 lg:py-6">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-[15px] font-semibold tracking-[-0.03em] text-[#1e2d47]">핵심 지표 추세</h2>
              {hoveredDate ? (
                <span className="rounded-full bg-[#edf4ff] px-2 py-1 text-[10px] font-semibold text-[#2f6df6]">
                  {formatDateLabel(hoveredDate, data.rangeDays === 365)}
                </span>
              ) : null}
            </div>
            <p className="mt-1 text-[12px] text-[#7b8ba3]">그래프 위를 움직여 일별 값을 보고, 데이터 점을 누르면 실제 항목을 확인합니다.</p>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {METRIC_DEFINITIONS.map((metric) => {
              const selected = selectedMetrics.includes(metric.key);
              return (
                <button
                  key={metric.key}
                  type="button"
                  aria-pressed={selected}
                  onClick={() => toggleMetric(metric.key)}
                  className={`inline-flex h-8 items-center gap-1.5 rounded-[8px] border px-2.5 text-[11px] font-semibold transition-colors ${
                    selected
                      ? "border-[#c9d9f2] bg-[#f5f9ff] text-[#344767]"
                      : "border-[#e2e8f1] bg-white text-[#98a4b5] hover:text-[#61718a]"
                  }`}
                >
                  <span
                    className={`h-2 w-2 rounded-full ${selected ? "opacity-100" : "opacity-30"}`}
                    style={{ backgroundColor: metric.color }}
                  />
                  {metric.label}
                </button>
              );
            })}
          </div>
        </div>

        <div className="mt-5 divide-y divide-[#edf2f8] border-y border-[#e7edf6]">
          {METRIC_DEFINITIONS.filter((metric) => selectedMetrics.includes(metric.key)).map((metric) => {
            const currentValue = data.current[metric.key];
            const previousValue = data.previous[metric.key];
            const focusedValue = hoverIndex === null
              ? currentValue
              : (data.currentDaily[hoverIndex]?.[metric.key] ?? 0);

            return (
              <div key={metric.key} className="grid min-h-[116px] gap-3 py-3 sm:grid-cols-[148px_minmax(0,1fr)] sm:items-center">
                <div>
                  <div className="flex items-center gap-2">
                    <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: metric.color }} />
                    <p className="text-[12px] font-semibold text-[#536681]">{metric.label}</p>
                  </div>
                  <div className="mt-2 flex items-end gap-2">
                    <p className="text-[19px] font-semibold tracking-[-0.04em] text-[#16233c]">
                      {formatMetricValue(metric.key, focusedValue)}
                    </p>
                    {hoverIndex === null ? (
                      <MetricComparison current={currentValue} previous={previousValue} show={showComparison} />
                    ) : null}
                  </div>
                  <p className="mt-1 text-[10px] text-[#94a0b2]">{hoverIndex === null ? `${data.rangeDays}일 합계` : "선택일"}</p>
                </div>
                <Sparkline
                  color={metric.color}
                  hoverIndex={hoverIndex}
                  metricKey={metric.key}
                  onSelectIndex={(index) => {
                    const point = data.currentDaily[index];

                    if (point) {
                      setSelectedDetail({
                        date: point.date,
                        label: metric.label,
                        metricKey: metric.key,
                        value: point[metric.key],
                      });
                    }
                  }}
                  points={data.currentDaily}
                  setHoverIndex={setHoverIndex}
                />
              </div>
            );
          })}
        </div>
        <div className="mt-2 flex justify-between text-[10px] text-[#95a2b5] sm:pl-[160px]">
          <span>{formatDateLabel(data.currentDaily[0]?.date ?? "", data.rangeDays === 365)}</span>
          <span>{formatDateLabel(data.currentDaily.at(-1)?.date ?? "", data.rangeDays === 365)}</span>
        </div>
      </section>

      <section className="border-b border-[#e8eef7] px-3 py-5 sm:px-4 lg:px-8 lg:py-6">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
          <div>
            <h2 className="text-[15px] font-semibold tracking-[-0.03em] text-[#1e2d47]">사업 전환과 사용 현황</h2>
            <p className="mt-1 text-[12px] text-[#7b8ba3]">한 영역에서 전환 품질, 기능 채택, 고객별 사용량을 바꿔 봅니다.</p>
          </div>
          <div className="inline-flex w-fit rounded-[10px] border border-[#dfe7f2] bg-[#f7f9fc] p-1">
            {([
              ["funnel", "전환"],
              ["adoption", "기능 사용"],
              ["domains", "상위 도메인"],
            ] as const).map(([tab, label]) => (
              <button
                key={tab}
                type="button"
                onClick={() => setDetailTab(tab)}
                className={`h-8 rounded-[7px] px-3 text-[11px] font-semibold transition-colors ${
                  detailTab === tab
                    ? "bg-white text-[#2f6df6] shadow-[0_2px_8px_rgba(26,51,91,0.08)]"
                    : "text-[#74849c] hover:text-[#40536f]"
                }`}
              >
                {label}
              </button>
            ))}
          </div>
        </div>

        <div className="mt-4">
          {detailTab === "funnel" ? (
            <FunnelPanel data={data} showComparison={showComparison} />
          ) : detailTab === "adoption" ? (
            <div className="grid gap-x-10 divide-y divide-[#edf2f8] lg:grid-cols-2 lg:divide-y-0">
              <div className="divide-y divide-[#edf2f8]">
                <AdoptionRow count={data.adoption.activePaidOwners} label="성장 플랜" total={data.adoption.totalOwners} />
                <AdoptionRow count={data.adoption.aiRelayOwners} label="AI 릴레이" total={data.adoption.totalOwners} />
                <AdoptionRow count={data.adoption.activeAutoSendOwners} label="자동발송" total={data.adoption.totalOwners} />
              </div>
              <div className="divide-y divide-[#edf2f8]">
                <AdoptionRow count={data.adoption.activeApiOwners} label="발송 API" total={data.adoption.totalOwners} />
                <AdoptionRow count={data.adoption.pushEnabledOwners} label="앱 푸시" total={data.adoption.totalOwners} />
                <AdoptionRow count={data.adoption.signatureOwners} label="메일 서명" total={data.adoption.totalOwners} />
              </div>
            </div>
          ) : data.topDomains.length > 0 ? (
            <div className="overflow-x-auto border-y border-[#e7edf6]">
              <table className="w-full min-w-[720px] text-left">
                <thead className="bg-[#f8faff] text-[11px] font-semibold text-[#75869f]">
                  <tr>
                    <th className="px-3 py-2.5">도메인</th>
                    <th className="px-3 py-2.5 text-right">전체</th>
                    <th className="px-3 py-2.5 text-right">수신</th>
                    <th className="px-3 py-2.5 text-right">발송</th>
                    <th className="px-3 py-2.5 text-right">최근 활동</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#edf2f8]">
                  {data.topDomains.map((row, index) => (
                    <tr key={row.domain} className="text-[12px] text-[#42546f]">
                      <td className="px-3 py-3">
                        <div className="flex items-center gap-3">
                          <span className="w-5 text-center text-[10px] font-semibold text-[#9aa7b9]">{index + 1}</span>
                          <div>
                            <p className="font-semibold text-[#263957]">{row.domain}</p>
                            <p className="mt-0.5 text-[10px] text-[#8a98ac]">{row.companyName}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-3 py-3 text-right font-semibold text-[#263957]">{formatNumber(row.totalMessages)}</td>
                      <td className="px-3 py-3 text-right">{formatNumber(row.inboundMessages)}</td>
                      <td className="px-3 py-3 text-right">{formatNumber(row.outboundMessages)}</td>
                      <td className="px-3 py-3 text-right text-[#7e8da3]">{formatDateTime(row.lastActiveAt)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="border-y border-[#e7edf6] py-8 text-center text-[12px] text-[#8492a7]">선택 기간에 메일 사용 기록이 없습니다.</p>
          )}
        </div>
      </section>

      <section className="px-3 py-5 sm:px-4 lg:px-8 lg:py-6">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-[15px] font-semibold tracking-[-0.03em] text-[#1e2d47]">지금 확인할 운영 항목</h2>
              <span className="rounded-full bg-[#fff1f3] px-2 py-1 text-[10px] font-semibold text-[#b74359]">
                {data.actionItems.reduce((sum, item) => sum + item.count, 0)}건
              </span>
            </div>
            <p className="mt-1 text-[12px] text-[#7b8ba3]">정상 지표는 숨기고 실제 조치가 필요한 항목만 표시합니다.</p>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {([
              ["all", "전체", data.actionItems.reduce((sum, item) => sum + item.count, 0)],
              ["critical", "긴급", severityCounts.critical],
              ["warning", "점검", severityCounts.warning],
              ["info", "보완", severityCounts.info],
            ] as const).map(([filter, label, count]) => (
              <button
                key={filter}
                type="button"
                onClick={() => setActionFilter(filter)}
                className={`h-8 rounded-[8px] border px-2.5 text-[11px] font-semibold transition-colors ${
                  actionFilter === filter
                    ? "border-[#bcd0ee] bg-[#edf4ff] text-[#2f6df6]"
                    : "border-[#e0e7f0] bg-white text-[#77879d]"
                }`}
              >
                {label} {count}
              </button>
            ))}
          </div>
        </div>

        {filteredActions.length > 0 ? (
          <div className="mt-4 divide-y divide-[#edf2f8] border-y border-[#e6ecf5]">
            {filteredActions.map((item) => {
              const tone = item.severity === "critical"
                ? "bg-[#fff1f3] text-[#b74359]"
                : item.severity === "warning"
                  ? "bg-[#fff7e9] text-[#9a651b]"
                  : "bg-[#edf4ff] text-[#2f6df6]";
              const severityLabel = item.severity === "critical" ? "긴급" : item.severity === "warning" ? "점검" : "보완";

              return (
                <div key={item.id} className="flex flex-col gap-3 py-3.5 sm:flex-row sm:items-center">
                  <span className={`w-fit rounded-full px-2 py-1 text-[10px] font-semibold ${tone}`}>{severityLabel}</span>
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="text-[13px] font-semibold text-[#2a3b56]">{item.title}</p>
                      <span className="text-[12px] font-semibold text-[#c14d61]">{item.count}건</span>
                    </div>
                    <p className="mt-1 text-[11px] leading-5 text-[#7a8aa1]">{item.description}</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setSelectedAction(item)}
                    className="inline-flex h-8 shrink-0 cursor-pointer items-center text-[11px] font-semibold text-[#2f6df6] hover:underline"
                  >
                    상세보기
                  </button>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="mt-4 border-y border-[#e6ecf5] py-9 text-center">
            <p className="text-[13px] font-semibold text-[#2b7652]">현재 조건에서 즉시 조치할 항목이 없습니다.</p>
            <p className="mt-1 text-[11px] text-[#8492a7]">정상 상태 항목은 자동으로 목록에서 제외됩니다.</p>
          </div>
        )}

        <div className="mt-4 flex flex-wrap items-center justify-between gap-2 text-[10px] text-[#94a1b3]">
          <p>집계 시각 {formatDateTime(data.generatedAt)} · 운영 계정과 팀 멤버 중복 제외</p>
          <p>현재 고객 {data.snapshot.totalOwners}명 · 활성 구독 {data.snapshot.activeSubscriptions}건 · 예상 월 매출 {formatCurrency(data.snapshot.expectedMonthlyRevenue)}</p>
        </div>
      </section>

      {selectedDetail ? (
        <KavenixStatisticsDetailDialog
          key={`${selectedDetail.date}-${selectedDetail.metricKey}`}
          date={selectedDetail.date}
          label={selectedDetail.label}
          metricKey={selectedDetail.metricKey}
          onClose={() => setSelectedDetail(null)}
          value={formatMetricValue(selectedDetail.metricKey, selectedDetail.value)}
        />
      ) : null}

      {selectedAction ? (
        <KavenixStatisticsActionDetailDialog
          key={selectedAction.id}
          action={selectedAction}
          onClose={() => setSelectedAction(null)}
          onResolved={resolveActionItem}
        />
      ) : null}
    </div>
  );
}
