'use client';

import { useState, useEffect, useCallback } from 'react';
import { TrendingUp, ShoppingBag, CalendarDays, Bot, Download, Package, Wifi, Award, Gift, Coins, Percent, Repeat, Calendar } from 'lucide-react';
import FeatureGuard from '@client/components/FeatureGuard';
import { isFeatureLockedError } from '@client/utils/isFeatureLockedError';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';
import { getLoyaltyStats, type LoyaltyStats } from '@client/api/loyalty';
import {
  AreaChart, Area, BarChart, Bar, LineChart, Line,
  XAxis, YAxis, CartesianGrid, Tooltip, PieChart, Pie, Cell,
  ComposedChart, Legend,
} from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import { useAuth } from '@client/contexts/AuthContext';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { useCurrency } from '@client/hooks/useCurrency';

const PIE_COLORS = ['hsl(22,89%,48%)', 'hsl(210,100%,40%)', 'hsl(142,72%,29%)', 'hsl(280,60%,45%)', 'hsl(40,96%,40%)'];

const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const DAYS = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

type ApiPeriod = 'today' | 'week' | 'month' | '3months';

const PERIOD_MAP: Record<string, ApiPeriod> = {
  'Today': 'today',
  'This Week': 'week',
  'This Month': 'month',
  'Last 3 Months': '3months',
};

interface KpiData { value: number; change: string; positive: boolean; }
interface AnalyticsData {
  kpis: { revenue: KpiData; orders: KpiData; bookings: KpiData; aiResolution: KpiData };
  orderTrend: { bucket: string; orders: number; revenue: number }[];
  bookingTrend: { bucket: string; bookings: number; cancellations: number }[];
  aiByHour: { hour: string; resolution: number; escalation: number; total: number }[];
  channelSplit: { name: string; value: number; count: number }[];
  revenueByChannel: { channel: string; orders: number; revenue: number }[];
  topItems: { name: string; orderCount: number; revenue: number }[];
  period: string;
  currentStart: string;
}

function KPISkeleton() {
  return (
    <div className="metric-card">
      <div className="flex items-center justify-between mb-3">
        <div className="w-9 h-9 rounded-lg skeleton" />
        <div className="h-5 w-14 rounded-full skeleton" />
      </div>
      <div className="h-7 w-24 rounded skeleton mb-1.5" />
      <div className="h-3 w-20 rounded skeleton" />
    </div>
  );
}

function ChartSkeleton({ height = 220 }: { height?: number }) {
  return <div className="w-full rounded-xl skeleton" style={{ height }} />;
}

function EmptyChart({ height = 220, message = 'No data yet', sub = 'Data appears as activity is recorded' }: { height?: number; message?: string; sub?: string }) {
  return (
    <div className="flex items-center justify-center" style={{ height, color: 'hsl(var(--muted-foreground))' }}>
      <div className="text-center">
        <p className="text-sm font-medium">{message}</p>
        <p className="text-xs mt-1">{sub}</p>
      </div>
    </div>
  );
}

function formatBucket(bucket: string, apiPeriod: ApiPeriod): string {
  if (apiPeriod === 'today') {
    const h = parseInt(bucket, 10);
    if (h === 0) return '12am';
    if (h < 12) return `${h}am`;
    if (h === 12) return '12pm';
    return `${h - 12}pm`;
  }
  if (apiPeriod === 'week') {
    const d = new Date(bucket + 'T00:00:00');
    return `${DAYS[d.getDay()]} ${d.getDate()}`;
  }
  if (apiPeriod === 'month') {
    const d = new Date(bucket + 'T00:00:00');
    return `${d.getDate()}`;
  }
  const [, m] = bucket.split('-');
  return MONTHS[parseInt(m, 10) - 1];
}

function utcDateStr(d: Date): string {
  return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(d.getUTCDate()).padStart(2, '0')}`;
}
function utcMonthStr(d: Date): string {
  return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
}

function generateOrderBuckets(apiPeriod: ApiPeriod): string[] {
  if (apiPeriod === 'today') return Array.from({ length: 24 }, (_, i) => String(i));
  const now = new Date();
  if (apiPeriod === 'week') {
    return Array.from({ length: 7 }, (_, i) => {
      const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 6 + i));
      return utcDateStr(d);
    });
  }
  if (apiPeriod === 'month') {
    const year = now.getUTCFullYear();
    const month = now.getUTCMonth();
    const days = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    return Array.from({ length: days }, (_, i) => {
      const d = new Date(Date.UTC(year, month, i + 1));
      return utcDateStr(d);
    });
  }
  return Array.from({ length: 3 }, (_, i) => {
    const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 2 + i, 1));
    return utcMonthStr(d);
  });
}

function generateBookingBuckets(apiPeriod: ApiPeriod): string[] {
  const now = new Date();
  if (apiPeriod === 'today') {
    return [utcDateStr(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())))];
  }
  if (apiPeriod === 'week') {
    return Array.from({ length: 7 }, (_, i) => {
      const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 6 + i));
      return utcDateStr(d);
    });
  }
  if (apiPeriod === 'month') {
    return Array.from({ length: 6 }, (_, i) => {
      const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 5 + i, 1));
      return utcMonthStr(d);
    });
  }
  return Array.from({ length: 3 }, (_, i) => {
    const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 2 + i, 1));
    return utcMonthStr(d);
  });
}

function fillOrderBuckets(
  data: { bucket: string; orders: number; revenue: number }[],
  apiPeriod: ApiPeriod
) {
  const buckets = generateOrderBuckets(apiPeriod);
  const map = new Map(data.map(d => [d.bucket, d]));
  return buckets.map(b => ({
    label: formatBucket(b, apiPeriod),
    orders: map.get(b)?.orders ?? 0,
    revenue: map.get(b)?.revenue ?? 0,
  }));
}

function fillBookingBuckets(
  data: { bucket: string; bookings: number; cancellations: number }[],
  apiPeriod: ApiPeriod
) {
  const buckets = generateBookingBuckets(apiPeriod);
  const formatPeriod: ApiPeriod = (apiPeriod === 'today' || apiPeriod === 'week') ? 'week' : '3months';
  const map = new Map(data.map(d => [d.bucket, d]));
  return buckets.map(b => ({
    label: formatBucket(b, formatPeriod),
    bookings: map.get(b)?.bookings ?? 0,
    cancellations: map.get(b)?.cancellations ?? 0,
  }));
}

function periodLabel(period: string, tFn?: (key: string, fallback: string) => string): string {
  const t = tFn || ((k: string, fb: string) => fb);
  if (period === 'Today') return t('period.today', 'today');
  if (period === 'This Week') return t('period.last7days', 'last 7 days');
  if (period === 'This Month') return t('period.thisMonthLabel', 'this month');
  return t('period.last3months', 'last 3 months');
}

function exportCSV(data: AnalyticsData, uiPeriod: string, apiPeriod: ApiPeriod, fc?: (n: number) => string) {
  const fmt = fc || ((n: number) => `$${n.toFixed(2)}`);
  const rows: string[] = [];
  rows.push(`Analytics Report — ${uiPeriod}`);
  rows.push(`Generated: ${new Date().toLocaleString()}`);
  rows.push('');

  rows.push('KPIs');
  rows.push('Metric,Value,vs Prior Period');
  rows.push(`Revenue,${fmt(data.kpis.revenue.value)},${data.kpis.revenue.change}`);
  rows.push(`Total Orders,${data.kpis.orders.value},${data.kpis.orders.change}`);
  rows.push(`Reservations,${data.kpis.bookings.value},${data.kpis.bookings.change}`);
  rows.push(`AI Resolution,${data.kpis.aiResolution.value}%,${data.kpis.aiResolution.change}`);
  rows.push('');

  const filledOrders = fillOrderBuckets(data.orderTrend, apiPeriod);
  rows.push('Revenue & Orders Trend');
  rows.push('Period,Orders,Revenue');
  filledOrders.forEach(r => rows.push(`${r.label},${r.orders},${fmt(r.revenue)}`));
  rows.push('');

  const filledBookings = fillBookingBuckets(data.bookingTrend, apiPeriod);
  rows.push('Reservations Trend');
  rows.push('Period,Bookings,Cancellations');
  filledBookings.forEach(r => rows.push(`${r.label},${r.bookings},${r.cancellations}`));
  rows.push('');

  rows.push('AI Resolution by Hour');
  rows.push('Hour,Resolution %,Escalation %,Total Conversations');
  data.aiByHour.forEach(r => rows.push(`${r.hour},${r.resolution}%,${r.escalation}%,${r.total}`));
  rows.push('');

  rows.push('Channel Split (Conversations)');
  rows.push('Channel,% Share,Count');
  data.channelSplit.forEach(r => rows.push(`${r.name},${r.value}%,${r.count}`));
  rows.push('');

  rows.push('Revenue by Channel (Orders)');
  rows.push('Channel,Orders,Revenue');
  data.revenueByChannel.forEach(r => rows.push(`${r.channel},${r.orders},${fmt(r.revenue)}`));
  rows.push('');

  rows.push('Top Menu Items');
  rows.push('Item,Orders,Revenue');
  data.topItems.forEach(r => rows.push(`"${r.name}",${r.orderCount},${fmt(r.revenue)}`));

  const csv = rows.join('\n');
  const blob = new Blob([csv], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `analytics-${uiPeriod.toLowerCase().replace(/\s+/g, '-')}-${new Date().toISOString().slice(0, 10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

export default function AnalyticsPage() {
  const { t } = useLanguage();
  usePageHeader(t('nav.analytics', 'Analytics & Reports'), t('nav.analyticsSubtitle', 'Revenue, orders, bookings, and AI performance'));
  const { restaurantId } = useAuth();
  const { hasFeature } = usePlanFeatures();
  const loyaltyEnabled = hasFeature('loyalty');
  const { format: fc, formatCompact: fcc, symbol: currSym } = useCurrency();
  const [period, setPeriod] = useState('This Week');
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [loyalty, setLoyalty] = useState<LoyaltyStats | null>(null);
  const [loyaltyLoading, setLoyaltyLoading] = useState(false);

  const fetchAnalytics = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const apiPeriod = PERIOD_MAP[period] ?? 'week';
      const res = await fetch(`/api/analytics/full?period=${apiPeriod}`, { credentials: 'include' });
      if (!res.ok) throw new Error('Failed to fetch analytics');
      const json: AnalyticsData = await res.json();
      setData(json);
    } catch (err) {
      if (!isFeatureLockedError(err)) {
        console.error('Failed to load analytics', err);
      }
    } finally {
      setLoading(false);
    }
  }, [restaurantId, period]);

  const fetchLoyalty = useCallback(async () => {
    if (!restaurantId || !loyaltyEnabled) { setLoyalty(null); return; }
    setLoyaltyLoading(true);
    try {
      const apiPeriod = PERIOD_MAP[period] ?? 'week';
      const stats = await getLoyaltyStats(apiPeriod);
      setLoyalty(stats);
    } catch (err) {
      console.error('Failed to load loyalty stats', err);
      setLoyalty(null);
    } finally {
      setLoyaltyLoading(false);
    }
  }, [restaurantId, period, loyaltyEnabled]);

  useEffect(() => { fetchAnalytics(); }, [fetchAnalytics]);
  useEffect(() => { fetchLoyalty(); }, [fetchLoyalty]);

  const apiPeriod = PERIOD_MAP[period] ?? 'week';

  const orderTrendFilled = data ? fillOrderBuckets(data.orderTrend, apiPeriod) : [];
  const bookingTrendFilled = data ? fillBookingBuckets(data.bookingTrend, apiPeriod) : [];

  const hasRevenueData = orderTrendFilled.some(d => d.revenue > 0 || d.orders > 0);
  const hasBookingData = bookingTrendFilled.some(d => d.bookings > 0 || d.cancellations > 0);
  const hasAIData = (data?.aiByHour ?? []).some(d => d.total > 0);
  const hasChannelData = (data?.channelSplit ?? []).some(d => d.count > 0);
  const hasTopItems = (data?.topItems ?? []).length > 0;
  const hasRevenueByChannel = (data?.revenueByChannel ?? []).length > 0;

  const maxChannelRevenue = Math.max(...(data?.revenueByChannel ?? []).map(r => r.revenue), 1);

  const kpiCards = data ? [
    {
      label: t('analytics.totalRevenue', 'Total Revenue'),
      value: fc(data.kpis.revenue.value),
      change: data.kpis.revenue.change,
      positive: data.kpis.revenue.positive,
      icon: <TrendingUp size={18} />,
    },
    {
      label: t('analytics.totalOrders', 'Total Orders'),
      value: String(data.kpis.orders.value),
      change: data.kpis.orders.change,
      positive: data.kpis.orders.positive,
      icon: <ShoppingBag size={18} />,
    },
    {
      label: t('analytics.reservations', 'Reservations'),
      value: String(data.kpis.bookings.value),
      change: data.kpis.bookings.change,
      positive: data.kpis.bookings.positive,
      icon: <CalendarDays size={18} />,
    },
    {
      label: t('analytics.aiResolution', 'AI Resolution'),
      value: `${data.kpis.aiResolution.value}%`,
      change: data.kpis.aiResolution.change,
      positive: data.kpis.aiResolution.positive,
      icon: <Bot size={18} />,
    },
  ] : [];

  return (
    <FeatureGuard feature="analytics" featureName="Analytics">
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex gap-2 flex-wrap">
          {[
            { key: 'Today', label: t('period.today', 'Today') },
            { key: 'This Week', label: t('period.thisWeek', 'This Week') },
            { key: 'This Month', label: t('period.thisMonth', 'This Month') },
            { key: 'Last 3 Months', label: t('period.last3Months', 'Last 3 Months') },
          ].map(p => (
            <button
              key={p.key}
              onClick={() => setPeriod(p.key)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-all ${period === p.key ? 'btn-primary' : 'btn-secondary'}`}
            >
              {p.label}
            </button>
          ))}
        </div>
        <button
          className="btn-secondary"
          onClick={() => data && exportCSV(data, period, apiPeriod, fc)}
          disabled={!data || loading}
        >
          <Download size={15} />
          {t('common.exportCSV', 'Export CSV')}
        </button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {loading
          ? Array.from({ length: 4 }).map((_, i) => <KPISkeleton key={i} />)
          : kpiCards.map(kpi => (
            <div key={kpi.label} className="metric-card">
              <div className="flex items-center justify-between mb-3">
                <div
                  className="w-9 h-9 rounded-lg flex items-center justify-center"
                  style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
                >
                  {kpi.icon}
                </div>
                {kpi.change && kpi.change !== '–' && (
                  <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${kpi.positive ? 'badge-success' : 'badge-danger'}`}>
                    {kpi.change}
                  </span>
                )}
              </div>
              <p className="text-2xl font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{kpi.value}</p>
              <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{kpi.label}</p>
            </div>
          ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">
        <div className="card p-5 lg:col-span-2">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('analytics.revenueOrders', 'Revenue & Orders')}</h3>
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {periodLabel(period, t)}
            </span>
          </div>
          {loading ? (
            <ChartSkeleton height={230} />
          ) : !hasRevenueData ? (
            <EmptyChart height={230} message={t('analytics.noRevenueData', 'No revenue data yet')} sub={t('analytics.noRevenueDataSub', 'Data will appear as orders come in')} />
          ) : (
            <SafeChart height={230}>
              <ComposedChart data={orderTrendFilled} margin={{ top: 5, right: 30, left: -10, bottom: 0 }}>
                <defs>
                  <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="hsl(22,89%,48%)" stopOpacity={0.2} />
                    <stop offset="95%" stopColor="hsl(22,89%,48%)" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220,13%,91%)" />
                <XAxis dataKey="label" tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} interval="preserveStartEnd" />
                <YAxis yAxisId="rev" tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} tickFormatter={v => fcc(v)} />
                <YAxis yAxisId="ord" orientation="right" tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} />
                <Tooltip
                  contentStyle={{ borderRadius: '10px', border: '1px solid hsl(220,13%,91%)', fontSize: 12 }}
                  formatter={(val: number, name: string) => name === 'Revenue ($)' ? [fc(val), name] : [val, name]}
                />
                <Legend wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
                <Area yAxisId="rev" type="monotone" dataKey="revenue" stroke="hsl(22,89%,48%)" strokeWidth={2} fill="url(#revGrad)" name={t('analytics.revenueLabel', 'Revenue ($)')} />
                <Bar yAxisId="ord" dataKey="orders" fill="hsl(210,100%,40%)" opacity={0.7} radius={[3, 3, 0, 0]} name={t('analytics.ordersLabel', 'Orders')} />
              </ComposedChart>
            </SafeChart>
          )}
        </div>

        <div className="card p-5">
          <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('analytics.channelSplit', 'Channel Split')}</h3>
          {loading ? (
            <><ChartSkeleton height={160} /><div className="space-y-2 mt-4">{[1, 2, 3].map(i => <div key={i} className="h-4 rounded skeleton" />)}</div></>
          ) : !hasChannelData ? (
            <EmptyChart height={200} message={t('analytics.noChannelData', 'No channel data yet')} sub={t('analytics.noChannelDataSub', 'Data appears as conversations start')} />
          ) : (
            <>
              <SafeChart height={160}>
                <PieChart>
                  <Pie
                    data={data!.channelSplit}
                    cx="50%" cy="50%"
                    innerRadius={45} outerRadius={70}
                    paddingAngle={3}
                    dataKey="value"
                  >
                    {data!.channelSplit.map((_, i) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
                  </Pie>
                  <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} formatter={(v: number) => [`${v}%`, 'Share']} />
                </PieChart>
              </SafeChart>
              <div className="space-y-2 mt-2">
                {data!.channelSplit.map((c, i) => (
                  <div key={c.name} className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }} />
                      <span className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>{c.name}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-xs tabular-nums" style={{ color: 'hsl(var(--muted-foreground))' }}>{c.count}</span>
                      <span className="text-xs font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{c.value}%</span>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mb-5">
        <div className="card p-5">
          <h3 className="font-semibold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('analytics.reservationsTrend', 'Reservations Trend')}</h3>
          <p className="text-xs mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {apiPeriod === 'today' ? t('period.today', 'Today') : apiPeriod === 'week' ? t('period.last7days', 'Last 7 days') : apiPeriod === 'month' ? t('period.last6months', 'Last 6 months') : t('period.last3months', 'Last 3 months')}
          </p>
          {loading ? (
            <ChartSkeleton height={200} />
          ) : !hasBookingData ? (
            <EmptyChart height={200} message={t('analytics.noBookingData', 'No booking data yet')} sub={t('analytics.noBookingDataSub', 'Data appears as reservations are made')} />
          ) : (
            <SafeChart height={200}>
              <BarChart data={bookingTrendFilled} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220,13%,91%)" />
                <XAxis dataKey="label" tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} interval="preserveStartEnd" />
                <YAxis tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} />
                <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} />
                <Legend wrapperStyle={{ fontSize: 11, paddingTop: 4 }} />
                <Bar dataKey="bookings" fill="hsl(210,100%,40%)" radius={[4, 4, 0, 0]} name={t('analytics.bookingsLabel', 'Bookings')} />
                <Bar dataKey="cancellations" fill="hsl(0,84%,44%)" radius={[4, 4, 0, 0]} name={t('analytics.cancellationsLabel', 'Cancellations')} />
              </BarChart>
            </SafeChart>
          )}
        </div>

        <div className="card p-5">
          <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('analytics.aiResolutionByHour', 'AI Resolution Rate by Hour')}</h3>
          {loading ? (
            <ChartSkeleton height={200} />
          ) : !hasAIData ? (
            <EmptyChart height={200} message={t('analytics.noAIData', 'No AI performance data yet')} sub={t('analytics.noAIDataSub', 'Data appears as conversations are resolved')} />
          ) : (
            <SafeChart height={200}>
              <LineChart data={data!.aiByHour} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220,13%,91%)" />
                <XAxis dataKey="hour" tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: 'hsl(220,9%,46%)' }} axisLine={false} tickLine={false} domain={[0, 100]} tickFormatter={v => `${v}%`} />
                <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} formatter={(v: number) => [`${v}%`]} />
                <Legend wrapperStyle={{ fontSize: 11, paddingTop: 4 }} />
                <Line type="monotone" dataKey="resolution" stroke="hsl(142,72%,29%)" strokeWidth={2} dot={false} name={t('analytics.resolutionPct', 'Resolution %')} />
                <Line type="monotone" dataKey="escalation" stroke="hsl(0,84%,44%)" strokeWidth={2} dot={false} name={t('analytics.escalationPct', 'Escalation %')} strokeDasharray="4 4" />
              </LineChart>
            </SafeChart>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <div className="card p-5">
          <div className="flex items-center gap-2 mb-4">
            <Wifi size={16} style={{ color: 'hsl(var(--primary))' }} />
            <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('analytics.revenueByChannel', 'Revenue by Channel')}</h3>
          </div>
          {loading ? (
            <div className="space-y-3">
              {[1, 2, 3].map(i => <div key={i} className="h-10 rounded-lg skeleton" />)}
            </div>
          ) : !hasRevenueByChannel ? (
            <EmptyChart height={160} message={t('analytics.noChannelRevenueData', 'No channel revenue data yet')} sub={t('analytics.noChannelRevenueDataSub', 'Data appears as orders come in through different channels')} />
          ) : (
            <div className="space-y-3">
              {data!.revenueByChannel.map((r, i) => (
                <div key={r.channel}>
                  <div className="flex items-center justify-between mb-1">
                    <div className="flex items-center gap-2">
                      <span className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }} />
                      <span className="text-sm font-medium capitalize" style={{ color: 'hsl(var(--foreground))' }}>{r.channel}</span>
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{r.orders} {t('analytics.ordersLabel', 'Orders').toLowerCase()}</span>
                    </div>
                    <span className="text-sm font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>
                      {fc(r.revenue)}
                    </span>
                  </div>
                  <div className="h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--border))' }}>
                    <div
                      className="h-full rounded-full transition-all duration-500"
                      style={{
                        width: `${Math.max((r.revenue / maxChannelRevenue) * 100, 2)}%`,
                        backgroundColor: PIE_COLORS[i % PIE_COLORS.length],
                      }}
                    />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="card p-5">
          <div className="flex items-center gap-2 mb-4">
            <Package size={16} style={{ color: 'hsl(var(--primary))' }} />
            <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('analytics.topMenuItems', 'Top Menu Items')}</h3>
          </div>
          {loading ? (
            <div className="space-y-2">
              {[1, 2, 3, 4, 5].map(i => <div key={i} className="h-8 rounded skeleton" />)}
            </div>
          ) : !hasTopItems ? (
            <EmptyChart height={160} message={t('analytics.noItemData', 'No item data yet')} sub={t('analytics.noItemDataSub', 'Top items appear as orders are completed')} />
          ) : (
            <div className="space-y-1">
              <div className="grid grid-cols-12 gap-2 pb-1 mb-1" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <span className="col-span-1 text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>#</span>
                <span className="col-span-5 text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menu.item', 'Item')}</span>
                <span className="col-span-3 text-xs font-medium text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.ordersLabel', 'Orders')}</span>
                <span className="col-span-3 text-xs font-medium text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.totalRevenue', 'Revenue')}</span>
              </div>
              {data!.topItems.map((item, i) => (
                <div key={item.name} className="grid grid-cols-12 gap-2 py-1.5 rounded" style={{ alignItems: 'center' }}>
                  <span className="col-span-1 text-xs tabular-nums font-bold" style={{ color: i < 3 ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }}>
                    {i + 1}
                  </span>
                  <span className="col-span-5 text-xs truncate" style={{ color: 'hsl(var(--foreground))' }} title={item.name}>
                    {item.name}
                  </span>
                  <span className="col-span-3 text-xs tabular-nums text-right" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                    {item.orderCount}
                  </span>
                  <span className="col-span-3 text-xs tabular-nums font-semibold text-right" style={{ color: 'hsl(var(--foreground))' }}>
                    {fc(item.revenue)}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {loyaltyEnabled && (
        <div className="mt-6">
          <div className="flex items-center gap-2 mb-4">
            <Award size={18} style={{ color: 'hsl(var(--primary))' }} />
            <h2 className="text-lg font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
              {t('analytics.loyaltySection', 'Loyalty Performance')}
            </h2>
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              · {periodLabel(period, t)}
            </span>
          </div>

          {loyaltyLoading ? (
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-5">
              {Array.from({ length: 4 }).map((_, i) => <KPISkeleton key={i} />)}
            </div>
          ) : !loyalty ? (
            <div className="card p-5">
              <EmptyChart
                height={140}
                message={t('analytics.loyaltyUnavailable', 'Loyalty data unavailable')}
                sub={t('analytics.loyaltyUnavailableSub', 'Enable the loyalty program to start tracking performance')}
              />
            </div>
          ) : (
            <>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-5">
                <div className="metric-card">
                  <div className="flex items-center justify-between mb-3">
                    <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                      <Coins size={18} />
                    </div>
                    <span className="text-xs font-semibold px-2 py-0.5 rounded-full badge-info">
                      {loyalty.totals.wallets} {t('analytics.wallets', 'wallets')}
                    </span>
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>
                    {loyalty.totals.points_outstanding.toLocaleString()}
                  </p>
                  <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {t('analytics.pointsOutstanding', 'Points Outstanding')}
                  </p>
                </div>
                <div className="metric-card">
                  <div className="flex items-center justify-between mb-3">
                    <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(142,72%,93%)', color: 'hsl(142,72%,29%)' }}>
                      <TrendingUp size={18} />
                    </div>
                    <span className="text-xs font-semibold tabular-nums" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      −{loyalty.totals.points_redeemed.toLocaleString()}
                    </span>
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>
                    +{loyalty.totals.points_earned.toLocaleString()}
                  </p>
                  <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {t('analytics.pointsEarnedRedeemed', 'Earned vs Redeemed')}
                  </p>
                </div>
                <div className="metric-card">
                  <div className="flex items-center justify-between mb-3">
                    <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(210,100%,93%)', color: 'hsl(210,100%,40%)' }}>
                      <Percent size={18} />
                    </div>
                    <span className="text-xs font-semibold tabular-nums" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {loyalty.redemption.redeemed_orders}/{loyalty.redemption.total_orders}
                    </span>
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>
                    {(loyalty.redemption.redemption_rate * 100).toFixed(1)}%
                  </p>
                  <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {t('analytics.redemptionRate', 'Redemption Rate')}
                  </p>
                </div>
                <div className="metric-card">
                  <div className="flex items-center justify-between mb-3">
                    <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(22,89%,93%)', color: 'hsl(22,89%,48%)' }}>
                      <Gift size={18} />
                    </div>
                    <span className="text-xs font-semibold tabular-nums" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {loyalty.redemption.redemptions_count} {t('analytics.redemptions', 'redemptions')}
                    </span>
                  </div>
                  <p className="text-2xl font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>
                    {fc(loyalty.redemption.avg_discount_per_redemption)}
                  </p>
                  <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {t('analytics.avgDiscountPerRedemption', 'Avg Discount / Redemption')}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-5">
                <div className="card p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <Calendar size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <h4 className="text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('analytics.last30Days', 'Last 30 days')}
                    </h4>
                  </div>
                  <div className="flex items-baseline justify-between">
                    <div>
                      <p className="text-xl font-bold tabular-nums" style={{ color: 'hsl(142,72%,29%)' }}>
                        +{loyalty.rolling.last_30_days.points_earned.toLocaleString()}
                      </p>
                      <p className="text-[11px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.earned', 'Earned')}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xl font-bold tabular-nums" style={{ color: 'hsl(22,89%,48%)' }}>
                        −{loyalty.rolling.last_30_days.points_redeemed.toLocaleString()}
                      </p>
                      <p className="text-[11px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.redeemed', 'Redeemed')}</p>
                    </div>
                  </div>
                </div>
                <div className="card p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <Calendar size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <h4 className="text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('analytics.last90Days', 'Last 90 days')}
                    </h4>
                  </div>
                  <div className="flex items-baseline justify-between">
                    <div>
                      <p className="text-xl font-bold tabular-nums" style={{ color: 'hsl(142,72%,29%)' }}>
                        +{loyalty.rolling.last_90_days.points_earned.toLocaleString()}
                      </p>
                      <p className="text-[11px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.earned', 'Earned')}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xl font-bold tabular-nums" style={{ color: 'hsl(22,89%,48%)' }}>
                        −{loyalty.rolling.last_90_days.points_redeemed.toLocaleString()}
                      </p>
                      <p className="text-[11px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.redeemed', 'Redeemed')}</p>
                    </div>
                  </div>
                </div>
                <div className="card p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <Repeat size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <h4 className="text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('analytics.repeatCustomerLift', 'Repeat-customer lift (90d)')}
                    </h4>
                  </div>
                  {loyalty.repeat_lift.member_customers === 0 && loyalty.repeat_lift.nonmember_customers === 0 ? (
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('analytics.noRepeatData', 'Not enough data yet')}
                    </p>
                  ) : (
                    <>
                      <div className="flex items-baseline gap-2">
                        <p className="text-2xl font-bold tabular-nums" style={{
                          color: loyalty.repeat_lift.lift_pct != null && loyalty.repeat_lift.lift_pct >= 0 ? 'hsl(142,72%,29%)' : 'hsl(0,84%,44%)',
                        }}>
                          {loyalty.repeat_lift.lift_pct != null
                            ? `${loyalty.repeat_lift.lift_pct >= 0 ? '+' : ''}${loyalty.repeat_lift.lift_pct.toFixed(1)} pts`
                            : '—'}
                        </p>
                        {loyalty.repeat_lift.lift_ratio != null && (
                          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            ({loyalty.repeat_lift.lift_ratio.toFixed(2)}×)
                          </span>
                        )}
                      </div>
                      <p className="text-[11px] mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t('analytics.members', 'Members')}: {(loyalty.repeat_lift.member_repeat_rate * 100).toFixed(1)}%
                        {' · '}
                        {t('analytics.nonMembers', 'Non-members')}: {(loyalty.repeat_lift.nonmember_repeat_rate * 100).toFixed(1)}%
                      </p>
                    </>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">
                <div className="card p-5">
                  <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>
                    {t('analytics.tierDistribution', 'Tier Distribution')}
                  </h3>
                  {loyalty.tier_distribution.every(t => t.customers === 0) ? (
                    <EmptyChart
                      height={200}
                      message={t('analytics.noTierData', 'No tier data yet')}
                      sub={t('analytics.noTierDataSub', 'Tiers populate as customers earn points')}
                    />
                  ) : (
                    <>
                      <SafeChart height={160}>
                        <PieChart>
                          <Pie
                            data={loyalty.tier_distribution.filter(t => t.customers > 0)}
                            cx="50%" cy="50%"
                            innerRadius={45} outerRadius={70}
                            paddingAngle={3}
                            dataKey="customers"
                            nameKey="tier_name"
                          >
                            {loyalty.tier_distribution.filter(t => t.customers > 0).map((tier, i) => (
                              <Cell key={tier.tier_id ?? i} fill={tier.badge_color || PIE_COLORS[i % PIE_COLORS.length]} />
                            ))}
                          </Pie>
                          <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} formatter={(v: number) => [`${v}`, t('analytics.customers', 'Customers')]} />
                        </PieChart>
                      </SafeChart>
                      <div className="space-y-2 mt-2">
                        {loyalty.tier_distribution.map((tier, i) => {
                          const totalC = loyalty.tier_distribution.reduce((s, x) => s + x.customers, 0);
                          const pct = totalC > 0 ? (tier.customers / totalC) * 100 : 0;
                          return (
                            <div key={tier.tier_id ?? i} className="flex items-center justify-between">
                              <div className="flex items-center gap-2 min-w-0">
                                <span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ backgroundColor: tier.badge_color || PIE_COLORS[i % PIE_COLORS.length] }} />
                                <span className="text-xs truncate" style={{ color: 'hsl(var(--foreground-secondary))' }}>{tier.tier_name}</span>
                              </div>
                              <div className="flex items-center gap-2">
                                <span className="text-xs tabular-nums" style={{ color: 'hsl(var(--muted-foreground))' }}>{tier.customers}</span>
                                <span className="text-xs font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{pct.toFixed(0)}%</span>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </>
                  )}
                </div>

                <div className="card p-5 lg:col-span-2">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                      {t('analytics.topLoyalCustomers', 'Top Loyal Customers')}
                    </h3>
                    <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('analytics.byLifetimePoints', 'by lifetime points')}
                    </span>
                  </div>
                  {loyalty.top_customers.length === 0 ? (
                    <EmptyChart
                      height={200}
                      message={t('analytics.noLoyalCustomers', 'No loyal customers yet')}
                      sub={t('analytics.noLoyalCustomersSub', 'Customers appear here once they start earning points')}
                    />
                  ) : (
                    <div className="space-y-1">
                      <div className="grid grid-cols-12 gap-2 pb-1 mb-1" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        <span className="col-span-4 text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.title', 'Customer')}</span>
                        <span className="col-span-2 text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.tier', 'Tier')}</span>
                        <span className="col-span-2 text-xs font-medium text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.balance', 'Balance')}</span>
                        <span className="col-span-2 text-xs font-medium text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('analytics.lifetime', 'Lifetime')}</span>
                        <span className="col-span-2 text-xs font-medium text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.lastVisit', 'Last Visit')}</span>
                      </div>
                      {loyalty.top_customers.map((c) => (
                        <div key={c.customer_id} className="grid grid-cols-12 gap-2 py-1.5 rounded items-center">
                          <div className="col-span-4 min-w-0">
                            <p className="text-xs font-medium truncate" style={{ color: 'hsl(var(--foreground))' }} title={c.name ?? c.email ?? c.phone ?? c.customer_id}>
                              {c.name || c.email || c.phone || c.customer_id.slice(0, 8)}
                            </p>
                            {c.email && c.name && (
                              <p className="text-[10px] truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{c.email}</p>
                            )}
                          </div>
                          <div className="col-span-2">
                            {c.tier_name ? (
                              <span className="text-[11px] font-semibold px-2 py-0.5 rounded-full"
                                style={{
                                  backgroundColor: c.badge_color ? `${c.badge_color}22` : 'hsl(var(--muted))',
                                  color: c.badge_color || 'hsl(var(--foreground-secondary))',
                                }}
                              >
                                {c.tier_name}
                              </span>
                            ) : (
                              <span className="text-[11px]" style={{ color: 'hsl(var(--muted-foreground))' }}>—</span>
                            )}
                          </div>
                          <span className="col-span-2 text-xs tabular-nums text-right" style={{ color: 'hsl(var(--foreground))' }}>
                            {c.balance.toLocaleString()}
                          </span>
                          <span className="col-span-2 text-xs tabular-nums font-semibold text-right" style={{ color: 'hsl(var(--foreground))' }}>
                            {c.lifetime_points.toLocaleString()}
                          </span>
                          <span className="col-span-2 text-xs tabular-nums text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {c.last_visit ? new Date(c.last_visit).toLocaleDateString() : '—'}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
      )}
    </>
    </FeatureGuard>
  );
}
