'use client';

import { AnimatePresence, motion } from 'framer-motion';
import {
  Activity,
  AlertTriangle,
  BarChart3,
  Bot,
  CalendarDays,
  ChevronDown,
  Clock3,
  Compass,
  Globe,
  Laptop,
  Link as LinkIcon,
  Loader2,
  Monitor,
  MousePointerClick,
  Send,
  Smartphone,
  Tablet,
  Users,
  type LucideIcon,
} from 'lucide-react';
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import ProfileEmptyStateCard from '@/app/components/profile/ProfileEmptyStateCard';
import ProfileTabSkeleton from '@/app/components/profile/ProfileTabSkeleton';
import SafeResponsiveChart from '@/app/components/SafeResponsiveChart';
import type { OverviewDistributionItem, OverviewPayload } from '@/app/profile/hooks/useProfileOverviewData';
import { useToast } from '@/app/components/ToastProvider';
import { usePersistedState } from '@/lib/use-persisted-state';

type AnalyticsPeriodOption = 7 | 30 | 90 | 180 | 365;

const ANALYTICS_PERIOD_OPTIONS: AnalyticsPeriodOption[] = [7, 30, 90, 180, 365];
const ANALYTICS_PERIOD_CACHE_TTL_MS = 10_000;
const analyticsPeriodCache = new Map<AnalyticsPeriodOption, { payload: OverviewPayload; updatedAt: number }>();

function normalizeAnalyticsPeriod(value: number | undefined, fallback: AnalyticsPeriodOption): AnalyticsPeriodOption {
  const resolved = ANALYTICS_PERIOD_OPTIONS.find((period) => period === value);
  return resolved || fallback;
}

function readAnalyticsPeriodCache(period: AnalyticsPeriodOption) {
  const cacheEntry = analyticsPeriodCache.get(period);
  if (!cacheEntry) return null;
  if (Date.now() - cacheEntry.updatedAt > ANALYTICS_PERIOD_CACHE_TTL_MS) return null;
  return cacheEntry.payload;
}

const PERIOD_LABELS: Record<AnalyticsPeriodOption, string> = {
  7: '7 дн',
  30: '30 дн',
  90: '90 дн',
  180: '180 дн',
  365: '365 дн',
};

type ProfileAnalyticsTabProps = {
  data: OverviewPayload;
  availableAnalyticsPeriods?: number[];
  isLoading: boolean;
  onGoToLinks: () => void;
};

function formatDateTime(value: string) {
  return new Date(value).toLocaleString('ru-RU', {
    day: '2-digit',
    month: 'short',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function getDeviceIcon(value: string): LucideIcon {
  const normalized = value.toLowerCase();
  if (normalized.includes('план') || normalized.includes('tablet')) return Tablet;
  if (normalized.includes('моб') || normalized.includes('mobile')) return Smartphone;
  if (normalized.includes('комп') || normalized.includes('desktop')) return Monitor;
  return Laptop;
}

function getBrowserIcon(value: string): LucideIcon {
  const normalized = value.toLowerCase();
  if (normalized.includes('telegram')) return Send;
  if (normalized.includes('safari')) return Compass;
  return Globe;
}

function renderDeviceValue(value: string) {
  const Icon = getDeviceIcon(value);
  return (
    <span className="inline-flex min-w-0 items-center gap-2">
      <Icon className="h-3.5 w-3.5 shrink-0 text-violet-300" />
      <span className="truncate">{value}</span>
    </span>
  );
}

function renderBrowserValue(value: string) {
  const Icon = getBrowserIcon(value);
  return (
    <span className="inline-flex min-w-0 items-center gap-2">
      <Icon className="h-3.5 w-3.5 shrink-0 text-violet-300" />
      <span className="truncate">{value}</span>
    </span>
  );
}

function DistributionList({
  items,
  emptyText,
  distributionType,
}: {
  items: OverviewDistributionItem[];
  emptyText: string;
  distributionType?: 'device' | 'browser';
}) {
  if (items.length === 0) {
    return <p className="text-xs text-gray-500">{emptyText}</p>;
  }

  return (
    <div className="space-y-2.5">
      {items.slice(0, 6).map((item, index) => (
        <motion.div
          key={item.name}
          initial={{ opacity: 0, y: 6 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.2, delay: index * 0.04 }}
        >
          <div className="flex items-center justify-between text-xs mb-1">
            <span className="text-gray-300 truncate">
              {distributionType === 'device'
                ? renderDeviceValue(item.name)
                : distributionType === 'browser'
                  ? renderBrowserValue(item.name)
                  : item.name}
            </span>
            <span className="font-mono text-gray-400">{item.count}</span>
          </div>
          <div className="h-1.5 rounded-full bg-white/5 overflow-hidden">
            <motion.div
              initial={{ width: 0 }}
              animate={{ width: `${Math.min(100, item.share)}%` }}
              transition={{ duration: 0.45, delay: 0.05 + index * 0.05, ease: 'easeOut' }}
              className="h-full bg-gradient-to-r from-fuchsia-500 to-violet-500"
            />
          </div>
        </motion.div>
      ))}
    </div>
  );
}

export default function ProfileAnalyticsTab({
  data: initialData,
  availableAnalyticsPeriods,
  isLoading,
  onGoToLinks,
}: ProfileAnalyticsTabProps) {
  const [analyticsData, setAnalyticsData] = useState<OverviewPayload>(initialData);
  const [selectedPeriod, setSelectedPeriod] = usePersistedState<AnalyticsPeriodOption>(
    'profile.analytics.period',
    30,
    (value): value is AnalyticsPeriodOption =>
      typeof value === 'number' && ANALYTICS_PERIOD_OPTIONS.includes(value as AnalyticsPeriodOption),
  );
  const [isPeriodMenuOpen, setIsPeriodMenuOpen] = useState(false);
  const [isPeriodLoading, setIsPeriodLoading] = useState(false);
  const toast = useToast();

  const periodMenuRef = useRef<HTMLDivElement | null>(null);
  const periodRequestIdRef = useRef(0);

  const allowedPeriodSet = useMemo(() => {
    const values = availableAnalyticsPeriods && availableAnalyticsPeriods.length > 0
      ? availableAnalyticsPeriods
      : [7];
    return new Set(values);
  }, [availableAnalyticsPeriods]);

  useEffect(() => {
    const initialPeriod = normalizeAnalyticsPeriod(initialData.period, 7);
    const normalizedData: OverviewPayload = {
      ...initialData,
      period: initialPeriod,
    };

    setAnalyticsData(normalizedData);
    analyticsPeriodCache.set(initialPeriod, {
      payload: normalizedData,
      updatedAt: Date.now(),
    });
  }, [initialData]);

  useEffect(() => {
    if (allowedPeriodSet.has(selectedPeriod)) return;
    const fallback = ANALYTICS_PERIOD_OPTIONS.find((period) => allowedPeriodSet.has(period)) || 7;
    setSelectedPeriod(fallback);
  }, [allowedPeriodSet, selectedPeriod, setSelectedPeriod]);

  useEffect(() => {
    if (!isPeriodMenuOpen) return;

    const handlePointerDown = (event: PointerEvent) => {
      if (!periodMenuRef.current) return;
      if (periodMenuRef.current.contains(event.target as Node)) return;
      setIsPeriodMenuOpen(false);
    };

    window.addEventListener('pointerdown', handlePointerDown);
    return () => window.removeEventListener('pointerdown', handlePointerDown);
  }, [isPeriodMenuOpen]);

  const fetchPeriodData = useCallback(async (period: AnalyticsPeriodOption, options?: { force?: boolean; showLoader?: boolean }) => {
    const requestId = ++periodRequestIdRef.current;
    const force = options?.force ?? false;
    const showLoader = options?.showLoader ?? true;
    if (showLoader) {
      setIsPeriodLoading(true);
    }

    const cachedPayload = force ? null : readAnalyticsPeriodCache(period);
    if (cachedPayload) {
      setAnalyticsData(cachedPayload);
      if (showLoader) {
        setIsPeriodLoading(false);
      }
      return;
    }

    try {
      const response = await fetch(`/api/profile/overview?period=${period}`, { cache: 'no-store' });
      if (!response.ok) {
        throw new Error('Не удалось загрузить аналитику за выбранный период');
      }

      const payload = await response.json() as OverviewPayload;
      if (requestId !== periodRequestIdRef.current) return;

      const normalizedPayload: OverviewPayload = {
        ...payload,
        period: normalizeAnalyticsPeriod(payload.period, period),
      };

      setAnalyticsData(normalizedPayload);
      analyticsPeriodCache.set(period, {
        payload: normalizedPayload,
        updatedAt: Date.now(),
      });
    } catch {
      if (requestId !== periodRequestIdRef.current) return;
    } finally {
      if (showLoader && requestId === periodRequestIdRef.current) {
        setIsPeriodLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    if (analyticsData.period === selectedPeriod) return;
    void fetchPeriodData(selectedPeriod);
  }, [analyticsData.period, fetchPeriodData, selectedPeriod]);

  useEffect(() => {
    const refresh = () => {
      void fetchPeriodData(selectedPeriod, { force: true, showLoader: false });
    };
    const intervalId = window.setInterval(refresh, 15_000);
    window.addEventListener('focus', refresh);

    return () => {
      window.clearInterval(intervalId);
      window.removeEventListener('focus', refresh);
    };
  }, [fetchPeriodData, selectedPeriod]);

  const data = analyticsData;
  const totalUniques = data.chart.reduce((sum, point) => sum + point.uniques, 0);
  const last24Total = data.hourly.reduce((sum, point) => sum + point.clicks, 0);
  const hasNoLinks = data.summary.totalLinks === 0;
  const hasNoClicks = !hasNoLinks && data.summary.totalClicks === 0;
  const shouldShowSkeleton = isLoading && hasNoLinks && data.chart.length === 0;

  if (shouldShowSkeleton) {
    return <ProfileTabSkeleton mode="analytics" />;
  }

  return (
    <motion.section
      key="analytics"
      initial={{ opacity: 0, y: 14 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -10 }}
      transition={{ duration: 0.24, ease: 'easeOut' }}
      className="max-w-6xl mx-auto space-y-5"
    >
      <div className="rounded-2xl border border-white/10 bg-white/[0.03] backdrop-blur-xl p-6 relative z-20">
        <div className="absolute -top-20 -right-20 w-64 h-64 rounded-full bg-violet-500/15 blur-3xl pointer-events-none" />
        <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight text-white mb-1">Аналитика</h2>
            <p className="text-sm text-gray-400">Глубокая статистика переходов, аудитории и источников трафика.</p>
          </div>
          <div ref={periodMenuRef} className="relative z-[70]">
            <button
              type="button"
              onClick={() => setIsPeriodMenuOpen((prev) => !prev)}
              className="inline-flex min-h-[42px] items-center gap-2.5 rounded-xl border border-white/15 bg-white/[0.03] px-4 py-2.5 text-sm font-medium text-gray-200 transition-all duration-300 hover:border-white/30 hover:bg-white/[0.08] hover:text-white"
            >
              {isPeriodLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarDays className="h-4 w-4" />}
              Последние {PERIOD_LABELS[selectedPeriod]}
              <ChevronDown className={`h-4 w-4 transition-transform ${isPeriodMenuOpen ? 'rotate-180' : ''}`} />
            </button>

            <AnimatePresence>
              {isPeriodMenuOpen ? (
                <motion.div
                  initial={{ opacity: 0, y: 8, scale: 0.98 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: 8, scale: 0.98 }}
                  transition={{ duration: 0.15 }}
                  className="absolute right-0 top-[calc(100%+6px)] z-[80] mt-1 w-56 rounded-xl border border-white/10 bg-[#0E0E0E]/95 p-2 shadow-[0_14px_44px_rgba(0,0,0,0.55)] backdrop-blur-md"
                >
                  {ANALYTICS_PERIOD_OPTIONS.map((period) => {
                    const active = selectedPeriod === period;
                    const isAllowed = allowedPeriodSet.has(period);

                    return (
                      <button
                        key={period}
                        type="button"
                        onClick={() => {
                          setIsPeriodMenuOpen(false);
                          if (!isAllowed) {
                            toast.info('На вашем тарифе этот период недоступен');
                            return;
                          }
                          setSelectedPeriod(period);
                        }}
                        className={`inline-flex w-full items-center justify-between rounded-lg px-3 py-2.5 text-left text-sm transition-colors ${
                          active
                            ? 'bg-violet-500/18 text-violet-100'
                            : isAllowed
                              ? 'text-gray-300 hover:bg-white/5 hover:text-white'
                              : 'text-gray-500'
                        }`}
                      >
                        <span>{period} дн</span>
                        {!isAllowed ? <span className="text-[11px] text-gray-500">Недоступно</span> : null}
                      </button>
                    );
                  })}
                </motion.div>
              ) : null}
            </AnimatePresence>
          </div>
        </div>
      </div>

      {hasNoLinks ? (
        <ProfileEmptyStateCard
          title="Аналитика появится после первой ссылки"
          description="Сначала создайте короткую ссылку. После этого здесь начнут заполняться графики, распределения и журнал переходов."
          actionLabel="Перейти к ссылкам"
          onAction={onGoToLinks}
        />
      ) : hasNoClicks ? (
        <ProfileEmptyStateCard
          title="Пока нет переходов по ссылкам"
          description="Ссылки уже созданы, но статистике еще не из чего строить отчеты. Как только появятся клики, раздел заполнится автоматически."
          actionLabel="Открыть список ссылок"
          onAction={onGoToLinks}
        />
      ) : (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.2 }}
              whileHover={{ y: -2 }}
              className="rounded-2xl border border-white/10 bg-black/40 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.02]"
            >
              <div className="flex items-center justify-between mb-3">
                <span className="w-9 h-9 rounded-xl border border-violet-500/20 bg-violet-500/20 inline-flex items-center justify-center text-violet-300">
                  <MousePointerClick className="w-5 h-5" />
                </span>
                <span className="text-[11px] text-gray-500">Всего</span>
              </div>
              <p className="text-xs text-gray-500 mb-1">Клики</p>
              <p className="text-3xl font-mono tracking-tight text-white">{data.summary.totalClicks.toLocaleString('ru-RU')}</p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.2, delay: 0.04 }}
              whileHover={{ y: -2 }}
              className="rounded-2xl border border-white/10 bg-black/40 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.02]"
            >
              <div className="flex items-center justify-between mb-3">
                <span className="w-9 h-9 rounded-xl border border-blue-500/20 bg-blue-500/20 inline-flex items-center justify-center text-blue-300">
                  <Users className="w-5 h-5" />
                </span>
                <span className="text-[11px] text-gray-500">7 дней</span>
              </div>
              <p className="text-xs text-gray-500 mb-1">Уникальные</p>
              <p className="text-3xl font-mono tracking-tight text-white">{totalUniques.toLocaleString('ru-RU')}</p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.2, delay: 0.08 }}
              whileHover={{ y: -2 }}
              className="rounded-2xl border border-white/10 bg-black/40 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.02]"
            >
              <div className="flex items-center justify-between mb-3">
                <span className="w-9 h-9 rounded-xl border border-cyan-500/20 bg-cyan-500/20 inline-flex items-center justify-center text-cyan-300">
                  <Clock3 className="w-5 h-5" />
                </span>
                <span className="text-[11px] text-gray-500">24 часа</span>
              </div>
              <p className="text-xs text-gray-500 mb-1">Клики за сутки</p>
              <p className="text-3xl font-mono tracking-tight text-white">{last24Total.toLocaleString('ru-RU')}</p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.2, delay: 0.12 }}
              whileHover={{ y: -2 }}
              className="rounded-2xl border border-white/10 bg-black/40 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.02]"
            >
              <div className="flex items-center justify-between mb-3">
                <span className="w-9 h-9 rounded-xl border border-fuchsia-500/20 bg-fuchsia-500/20 inline-flex items-center justify-center text-fuchsia-300">
                  <Bot className="w-5 h-5" />
                </span>
                <span className="text-[11px] text-gray-500">Фильтры</span>
              </div>
              <p className="text-xs text-gray-500 mb-1">Подозрительный трафик</p>
              <p className="text-3xl font-mono tracking-tight text-white">
                {(data.summary.filteredClicks + data.summary.botClicks).toLocaleString('ru-RU')}
              </p>
            </motion.div>
          </div>

          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
            <div className="rounded-2xl border border-white/10 bg-black/35 p-5 backdrop-blur-md transition-colors hover:border-white/20 hover:bg-white/[0.03]">
              <div className="flex items-center gap-2 mb-4">
                <BarChart3 className="w-4 h-4 text-violet-300" />
                <p className="text-sm text-gray-200">Клики по дням</p>
              </div>
              {data.chart.length > 0 ? (
                <div className="h-64 min-w-0">
                  <SafeResponsiveChart>
                    <AreaChart data={data.chart} margin={{ top: 10, right: 8, left: -20, bottom: 0 }}>
                      <defs>
                        <linearGradient id="analyticsClicksGradient" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="0%" stopColor="#8b5cf6" stopOpacity={0.35} />
                          <stop offset="100%" stopColor="#8b5cf6" stopOpacity={0.02} />
                        </linearGradient>
                        <linearGradient id="analyticsUniqueGradient" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.35} />
                          <stop offset="100%" stopColor="#3b82f6" stopOpacity={0.02} />
                        </linearGradient>
                      </defs>
                      <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
                      <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 12 }} axisLine={false} tickLine={false} />
                      <YAxis tick={{ fill: '#94a3b8', fontSize: 12 }} axisLine={false} tickLine={false} allowDecimals={false} />
                      <Tooltip
                        cursor={{ stroke: 'rgba(255,255,255,0.18)' }}
                        contentStyle={{
                          background: 'rgba(8,8,8,0.95)',
                          border: '1px solid rgba(255,255,255,0.12)',
                          borderRadius: 10,
                          color: '#fff',
                        }}
                      />
                      <Area type="monotone" dataKey="clicks" name="Клики" stroke="#8b5cf6" strokeWidth={2.5} fillOpacity={1} fill="url(#analyticsClicksGradient)" />
                      <Area type="monotone" dataKey="uniques" name="Уникальные" stroke="#3b82f6" strokeWidth={2.5} fillOpacity={1} fill="url(#analyticsUniqueGradient)" />
                    </AreaChart>
                  </SafeResponsiveChart>
                </div>
              ) : (
                <div className="h-64 rounded-xl border border-white/10 bg-white/[0.02] flex items-center justify-center">
                  <p className="text-sm text-gray-500">Нет данных по дням</p>
                </div>
              )}
            </div>

            <div className="rounded-2xl border border-white/10 bg-black/35 p-5 backdrop-blur-md transition-colors hover:border-white/20 hover:bg-white/[0.03]">
              <div className="flex items-center gap-2 mb-4">
                <Clock3 className="w-4 h-4 text-cyan-300" />
                <p className="text-sm text-gray-200">Клики по часам (24ч)</p>
              </div>
              {data.hourly.length > 0 ? (
                <div className="h-64 min-w-0">
                  <SafeResponsiveChart>
                    <BarChart data={data.hourly} margin={{ top: 10, right: 0, left: -20, bottom: 0 }}>
                      <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
                      <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 11 }} axisLine={false} tickLine={false} minTickGap={18} />
                      <YAxis tick={{ fill: '#94a3b8', fontSize: 12 }} axisLine={false} tickLine={false} allowDecimals={false} />
                      <Tooltip
                        cursor={{ fill: 'rgba(255,255,255,0.05)' }}
                        contentStyle={{
                          background: 'rgba(8,8,8,0.95)',
                          border: '1px solid rgba(255,255,255,0.12)',
                          borderRadius: 10,
                          color: '#fff',
                        }}
                      />
                      <Bar dataKey="clicks" name="Клики" fill="#2AABEE" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </SafeResponsiveChart>
                </div>
              ) : (
                <div className="h-64 rounded-xl border border-white/10 bg-white/[0.02] flex items-center justify-center">
                  <p className="text-sm text-gray-500">Почасовая статистика пока недоступна</p>
                </div>
              )}
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
            <div className="rounded-2xl border border-white/10 bg-black/35 p-4 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <p className="flex items-center gap-2 text-sm text-gray-300 mb-3">
                <Smartphone className="w-4 h-4 text-violet-300" />
                Устройства
              </p>
              <DistributionList items={data.distributions.devices} emptyText="Нет данных по устройствам" distributionType="device" />
            </div>
            <div className="rounded-2xl border border-white/10 bg-black/35 p-4 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <p className="flex items-center gap-2 text-sm text-gray-300 mb-3">
                <Laptop className="w-4 h-4 text-violet-300" />
                Браузеры
              </p>
              <DistributionList items={data.distributions.browsers} emptyText="Нет данных по браузерам" distributionType="browser" />
            </div>
            <div className="rounded-2xl border border-white/10 bg-black/35 p-4 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <p className="flex items-center gap-2 text-sm text-gray-300 mb-3">
                <Activity className="w-4 h-4 text-violet-300" />
                Источники
              </p>
              <DistributionList items={data.distributions.sources} emptyText="Источники появятся после переходов" />
            </div>
            <div className="rounded-2xl border border-white/10 bg-black/35 p-4 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <p className="flex items-center gap-2 text-sm text-gray-300 mb-3">
                <Globe className="w-4 h-4 text-violet-300" />
                География
              </p>
              <DistributionList items={data.distributions.locations} emptyText="Геоданные пока недоступны" />
            </div>
          </div>

          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
            <div className="rounded-2xl border border-white/10 bg-black/35 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <p className="text-sm text-gray-300 mb-3">Топ UTM источники</p>
              {data.summary.topUtmSources.length > 0 ? (
                <div className="space-y-2.5">
                  {data.summary.topUtmSources.map((item) => (
                    <div key={item.name} className="flex items-center justify-between text-xs">
                      <span className="text-gray-300 truncate">{item.name}</span>
                      <span className="font-mono text-gray-200">{item.clicks.toLocaleString('ru-RU')}</span>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-xs text-gray-500">UTM-источники пока не собраны</p>
              )}
            </div>
            <div className="rounded-2xl border border-white/10 bg-black/35 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <p className="text-sm text-gray-300 mb-3">Топ UTM кампании</p>
              {data.summary.topUtmCampaigns.length > 0 ? (
                <div className="space-y-2.5">
                  {data.summary.topUtmCampaigns.map((item) => (
                    <div key={item.name} className="flex items-center justify-between text-xs">
                      <span className="text-gray-300 truncate">{item.name}</span>
                      <span className="font-mono text-gray-200">{item.clicks.toLocaleString('ru-RU')}</span>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-xs text-gray-500">UTM-кампании пока не собраны</p>
              )}
            </div>
          </div>

          <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
            <div className="xl:col-span-2 rounded-2xl border border-white/10 bg-black/35 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <div className="flex items-center justify-between mb-4">
                <p className="text-sm text-gray-300">Последние переходы</p>
                <span className="text-xs text-gray-500">{data.recentClicks.length} записей</span>
              </div>

              {data.recentClicks.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="text-left text-xs text-gray-500 border-b border-white/10">
                        <th className="py-2 pr-3 font-medium">Время</th>
                        <th className="py-2 pr-3 font-medium">Ссылка</th>
                        <th className="py-2 pr-3 font-medium">Страна</th>
                        <th className="py-2 pr-3 font-medium">Устройство</th>
                        <th className="py-2 pr-3 font-medium">Браузер</th>
                        <th className="py-2 pr-3 font-medium">Источник</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.recentClicks.map((click) => (
                        <tr key={click.id} className="border-b border-white/5 text-xs text-gray-300 transition-colors hover:bg-white/[0.03]">
                          <td className="py-2 pr-3 whitespace-nowrap">{formatDateTime(click.createdAt)}</td>
                          <td className="py-2 pr-3">
                            <span className="inline-flex flex-col">
                              <span className="text-gray-200 truncate max-w-[220px]">{click.link.title}</span>
                              <span className="text-gray-500 font-mono">{click.link.shortUrl}</span>
                            </span>
                          </td>
                          <td className="py-2 pr-3">{click.country}</td>
                          <td className="py-2 pr-3">{renderDeviceValue(click.device)}</td>
                          <td className="py-2 pr-3">{renderBrowserValue(click.browser)}</td>
                          <td className="py-2 pr-3 truncate max-w-[180px]">{click.source}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="rounded-xl border border-white/10 bg-white/[0.02] p-6 text-center">
                  <p className="text-sm text-gray-500">История переходов пока пустая</p>
                </div>
              )}
            </div>

            <div className="rounded-2xl border border-white/10 bg-black/35 p-5 backdrop-blur-md transition-colors hover:bg-white/[0.03]">
              <div className="flex items-center justify-between mb-4">
                <p className="text-sm text-gray-300">Топ ссылок</p>
                <button
                  type="button"
                  onClick={onGoToLinks}
                  className="text-xs px-2.5 py-1 rounded-lg border border-white/10 bg-white/[0.03] text-gray-300 hover:text-white hover:bg-white/[0.06] transition-colors"
                >
                  Ко всем
                </button>
              </div>

              {data.topLinks.length > 0 ? (
                <div className="space-y-2.5">
                  {data.topLinks.map((link) => (
                    <div key={link.id} className="rounded-lg border border-white/10 bg-white/[0.02] p-3 transition-colors hover:bg-white/[0.05]">
                      <p className="text-xs text-gray-200 truncate mb-1">{link.title || link.slug}</p>
                      <p className="text-[11px] font-mono text-gray-500 truncate mb-2">{link.shortUrl}</p>
                      <div className="flex items-center justify-between text-[11px]">
                        <span className="text-gray-500 inline-flex items-center gap-1">
                          <LinkIcon className="w-3 h-3" />
                          {new Date(link.createdAt).toLocaleDateString('ru-RU')}
                        </span>
                        <span className="text-violet-300 font-mono">{link.clicks.toLocaleString('ru-RU')}</span>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="rounded-xl border border-white/10 bg-white/[0.02] p-5">
                  <p className="text-sm text-gray-500">Нет данных по ссылкам</p>
                </div>
              )}
            </div>
          </div>
        </>
      )}

    </motion.section>
  );
}
