import { useEffect, useMemo, useState } from "react";
import { apiFetch } from '@/utils/api';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip as RechartsTooltip,
  XAxis,
  YAxis,
  TooltipProps,
} from "recharts";
import {
  TrendingUp,
  DollarSign,
  ShoppingBag,
  Percent,
  ArrowUpRight,
  ArrowDownRight,
  Clock3,
  Zap,
  Users,
  Wallet,
  Package,
} from "lucide-react";
import { acotService } from "@/services/dashboard/acotService";
import { cn } from "@/lib/utils";
import { NameType, ValueType } from "recharts/types/component/DefaultTooltipContent";
import { DateTime } from "luxon";
import { businessTodayStr } from "@/utils/businessTime";

type BlackFridayRange = {
  start: DateTime;
  end: DateTime;
  label: string;
};

type DayMetrics = {
  label: string;
  date: Date;
  revenue: number;
  orders: number;
  avgOrderValue: number;
  profit: number;
  cogs: number;
  margin: number;
};

type YearMetrics = {
  year: number;
  range: BlackFridayRange;
  days: DayMetrics[];
  totals: {
    revenue: number;
    orders: number;
    avgOrderValue: number;
    profit: number;
    margin: number;
    cogs: number;
  };
};

type RealtimeSnapshot = {
  last5MinUsers: number;
  last30MinUsers: number;
  lastUpdated: string | null;
};

type DebugBucketNote = {
  year: number;
  source: "stats" | "financial";
  raw: string;
  bucket: string;
  index: number;
};

type StatsDetailsResponse = {
  stats?: Array<Record<string, unknown>>;
} | null;

type FinancialsResponse = {
  trend?: Array<Record<string, unknown>>;
  totals?: Record<string, unknown>;
} | null;

const DAY_LABELS = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue"];
const BUSINESS_TIMEZONE = "America/New_York";
const BUSINESS_DAY_START_HOUR = 1;
const COLOR_PALETTE = [
  "#10b981", // emerald-500 - current year gets the best color
  "#6366f1", // indigo-500
  "#f59e0b", // amber-500
  "#8b5cf6", // violet-500
  "#64748b", // slate-500
  "#94a3b8", // slate-400
];

const formatCurrency = (value: number, digits = 0) =>
  new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  }).format(Number.isFinite(value) ? value : 0);

const formatNumber = (value: number) =>
  Number.isFinite(value) ? value.toLocaleString("en-US") : "0";

const mapRealtimeBasic = (payload: Record<string, unknown>): RealtimeSnapshot => {
  const last30Raw =
    (payload as { userResponse?: { rows?: Array<{ metricValues?: Array<{ value?: string }> }> } })
      ?.userResponse?.rows?.[0]?.metricValues?.[0]?.value ?? "0";
  const last5Raw =
    (payload as { fiveMinResponse?: { rows?: Array<{ metricValues?: Array<{ value?: string }> }> } })
      ?.fiveMinResponse?.rows?.[0]?.metricValues?.[0]?.value ?? "0";

  const last30MinUsers = Number.parseInt(String(last30Raw), 10);
  const last5MinUsers = Number.parseInt(String(last5Raw), 10);

  return {
    last5MinUsers: Number.isFinite(last5MinUsers) ? last5MinUsers : 0,
    last30MinUsers: Number.isFinite(last30MinUsers) ? last30MinUsers : 0,
    lastUpdated: new Date().toISOString(),
  };
};

const formatPercent = (value: number | null | undefined, digits = 1) => {
  if (value === null || value === undefined || Number.isNaN(value)) {
    return "—";
  }
  return `${value.toFixed(digits)}%`;
};

const percentChange = (current: number, previous: number | null | undefined) => {
  if (previous === null || previous === undefined || previous === 0) {
    return null;
  }

  return ((current - previous) / Math.abs(previous)) * 100;
};

const formatLastUpdated = (value: string | null | undefined) => {
  if (!value) return "—";
  const dt = DateTime.fromISO(value);
  if (!dt.isValid) return "—";
  return dt.toLocal().toLocaleString({timeStyle: "short"});
};

const toBusinessDateTime = (value: unknown) => {
  if (!value) return null;

  if (value instanceof Date) {
    return DateTime.fromJSDate(value, { zone: BUSINESS_TIMEZONE });
  }
  if (value instanceof DateTime) {
    return value.setZone(BUSINESS_TIMEZONE);
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    const datePart = trimmed.split("T")[0];
    const isoDateOnly = /^\d{4}-\d{2}-\d{2}$/;
    // Date-only strings (e.g., "2024-11-28")
    if (isoDateOnly.test(trimmed)) {
      const dateOnly = DateTime.fromISO(trimmed, {
        zone: BUSINESS_TIMEZONE,
      }).set({ hour: BUSINESS_DAY_START_HOUR, minute: 0, second: 0, millisecond: 0 });
      return dateOnly.isValid ? dateOnly : null;
    }

    // Stats responses often send midnight-Z timestamps (e.g., 2024-11-29T00:00:00.000Z) that
    // represent a whole business day. Treat those as date-only to avoid shifting a day earlier.
    if (isoDateOnly.test(datePart)) {
      const dateOnly = DateTime.fromISO(datePart, {
        zone: BUSINESS_TIMEZONE,
      }).set({ hour: BUSINESS_DAY_START_HOUR, minute: 0, second: 0, millisecond: 0 });
      return dateOnly.isValid ? dateOnly : null;
    }

    const hasZulu = trimmed.endsWith("Z");
    const isoLike = hasZulu ? trimmed.slice(0, -1) : trimmed;
    // ISO strings with time:
    // - If Z, parse as UTC then convert to business zone
    // - Otherwise, treat as wall time in business zone
    let dt = hasZulu
      ? DateTime.fromISO(trimmed, { zone: "utc", setZone: true }).setZone(BUSINESS_TIMEZONE)
      : DateTime.fromISO(isoLike, { zone: BUSINESS_TIMEZONE, setZone: false });
    if (!dt.isValid) {
      dt = hasZulu
        ? DateTime.fromSQL(trimmed, { zone: "utc", setZone: true }).setZone(BUSINESS_TIMEZONE)
        : DateTime.fromSQL(isoLike, { zone: BUSINESS_TIMEZONE, setZone: false });
    }
    return dt.isValid ? dt : null;
  }
  if (typeof value === "number") {
    return DateTime.fromMillis(value, { zone: BUSINESS_TIMEZONE });
  }
  return null;
};

const getBusinessDayStart = (dt: DateTime) => {
  const start = dt.set({
    hour: BUSINESS_DAY_START_HOUR,
    minute: 0,
    second: 0,
    millisecond: 0,
  });
  return dt.hour < BUSINESS_DAY_START_HOUR ? start.minus({ days: 1 }) : start;
};

const formatRangeLabel = (start: DateTime, end: DateTime) => {
  const startZoned = start.setZone(BUSINESS_TIMEZONE);
  const endZoned = end.setZone(BUSINESS_TIMEZONE);
  return `${startZoned.toFormat("LLL d")} - ${endZoned.toFormat("LLL d")}`;
};

const computeDayIndex = (timestamp: unknown, rangeStart: DateTime) => {
  try {
    const dt = toBusinessDateTime(timestamp);
    if (!dt || !dt.isValid || !rangeStart?.isValid) return -1;

    const start = getBusinessDayStart(rangeStart);
    const target = getBusinessDayStart(dt);

    return Math.floor(target.diff(start, "days").days);
  } catch (err) {
    console.error("[BlackFridayDashboard] Failed to compute day index", err);
    return -1;
  }
};

const getBlackFridayRange = (year: number): BlackFridayRange => {
  const novemberFirst = DateTime.fromObject(
    { year, month: 11, day: 1 },
    { zone: BUSINESS_TIMEZONE }
  );
  if (!novemberFirst.isValid) {
    throw new Error(`Invalid start date for year ${year}: ${novemberFirst.invalidReason ?? "unknown"}`);
  }

  const offsetToThursday = (4 - novemberFirst.weekday + 7) % 7; // 4 = Thursday
  const thanksgiving = novemberFirst.plus({ days: offsetToThursday + 21 }); // 4th Thursday
  const start = thanksgiving.set({
    hour: BUSINESS_DAY_START_HOUR,
    minute: 0,
    second: 0,
    millisecond: 0,
  });
  const end = start.plus({ days: DAY_LABELS.length }).minus({ milliseconds: 1 });

  return {
    start,
    end,
    label: formatRangeLabel(start, end),
  };
};

const buildDayBuckets = (start: DateTime) =>
  DAY_LABELS.map((label, index) => {
    const dayStart = getBusinessDayStart(start.plus({ days: index }));
    return {
      label,
      date: dayStart.toJSDate(),
      revenue: 0,
      orders: 0,
      avgOrderValue: 0,
      profit: 0,
      cogs: 0,
      margin: 0,
    };
  });

const mapFinancialTrendToDays = (
  days: DayMetrics[],
  trend: Array<Record<string, unknown>>,
  start: DateTime,
  debug?: DebugBucketNote[]
) => {
  if (!Array.isArray(trend)) return;

  trend.forEach((point) => {
    const timestamp = point.date || point.timestamp;
    if (!timestamp) return;

    const dayIndex = computeDayIndex(timestamp as string, start);

    if (dayIndex < 0 || dayIndex >= days.length) return;

    if (debug) {
      debug.push({
        year: start.year,
        source: "financial",
        raw: String(timestamp),
        bucket: days[dayIndex]?.label ?? "n/a",
        index: dayIndex,
      });
    }

    const target = days[dayIndex];
    const income = Number(point.income ?? 0);
    const profit = Number(point.profit ?? 0);
    const cogs = Number(point.cogs ?? 0);
    const orders = Number(point.orders ?? 0);

    if (!target.revenue && Number.isFinite(income)) target.revenue = income;
    if (!target.orders && Number.isFinite(orders)) target.orders = orders;
    target.profit = profit;
    target.cogs = cogs;
    // Margin is calculated in finalizeMetrics to ensure consistency with final revenue
  });
};

const mapStatsToDays = (
  days: DayMetrics[],
  stats: Array<Record<string, unknown>>,
  start: DateTime,
  debug?: DebugBucketNote[]
) => {
  if (!Array.isArray(stats)) return;

  stats.forEach((entry) => {
    const timestamp = entry.date || entry.timestamp;
    if (!timestamp) return;

    const dayIndex = computeDayIndex(timestamp as string, start);

    if (dayIndex < 0 || dayIndex >= days.length) return;

    if (debug) {
      debug.push({
        year: start.year,
        source: "stats",
        raw: String(timestamp),
        bucket: days[dayIndex]?.label ?? "n/a",
        index: dayIndex,
      });
    }

    const target = days[dayIndex];
    const revenue = Number(entry.revenue ?? entry.total ?? entry.income ?? 0);
    const orders = Number(
      entry.orders ?? entry.count ?? entry.orderCount ?? entry.quantity ?? 0
    );

    target.revenue = revenue;
    target.orders = orders;
  });
};

const finalizeMetrics = (days: DayMetrics[]) => {
  days.forEach((day) => {
    day.avgOrderValue = day.orders > 0 ? day.revenue / day.orders : 0;

    if (day.profit === 0 && day.revenue > 0 && day.cogs > 0) {
      day.profit = day.revenue - day.cogs;
    }
    
    // Calculate margin based on the final revenue and profit figures
    // This fixes discrepancies where financial income source != stats revenue source
    if (day.revenue > 0) {
      const profit = day.profit || (day.cogs > 0 ? day.revenue - day.cogs : 0);
      day.margin = profit ? (profit / day.revenue) * 100 : 0;
    } else {
      day.margin = 0;
    }
  });
};

const computeTotals = (
  days: DayMetrics[],
  financialTotals?: Record<string, unknown>
) => {
  const revenue = days.reduce((sum, day) => sum + day.revenue, 0);
  const orders = days.reduce((sum, day) => sum + day.orders, 0);
  const cogs = days.reduce((sum, day) => sum + day.cogs, 0);
  const profitFromDays = days.reduce((sum, day) => sum + day.profit, 0);

  const incomeFromTotals = Number(financialTotals?.income);
  const profitFromTotals = Number(financialTotals?.profit);
  const cogsFromTotals = Number(financialTotals?.cogs);
  const marginFromTotals = Number(financialTotals?.margin);

  const income = Number.isFinite(incomeFromTotals) ? incomeFromTotals : revenue;
  const profit = Number.isFinite(profitFromTotals)
    ? profitFromTotals
    : profitFromDays || income - cogs;
  const safeCogs = Number.isFinite(cogsFromTotals) ? cogsFromTotals : cogs;
  const margin =
    Number.isFinite(marginFromTotals) && marginFromTotals !== 0
      ? marginFromTotals
      : income !== 0
        ? (profit / income) * 100
        : 0;

  return {
    revenue,
    orders,
    avgOrderValue: orders > 0 ? revenue / orders : 0,
    profit,
    margin,
    cogs: safeCogs,
  };
};

function InsightBadge({
  value,
  positiveLabel,
  negativeLabel,
  className,
  size = "default",
}: {
  value: number | null;
  positiveLabel: string;
  negativeLabel: string;
  className?: string;
  size?: "default" | "lg";
}) {
  if (value === null) {
    return <Badge variant="secondary" className={className}>—</Badge>;
  }

  const isUp = value >= 0;
  return (
    <Badge
      variant="outline"
      className={cn(
        "gap-1 font-medium transition-colors",
        size === "lg" ? "px-3 py-1 text-sm" : "pl-2 pr-2.5 py-0.5 text-xs",
        isUp ? "bg-emerald-500/10 text-emerald-600 border-emerald-500/30" : "bg-rose-500/10 text-rose-600 border-rose-500/30",
        className
      )}
    >
      {isUp ? <ArrowUpRight className={size === "lg" ? "h-4 w-4" : "h-3.5 w-3.5"} /> : <ArrowDownRight className={size === "lg" ? "h-4 w-4" : "h-3.5 w-3.5"} />}
      {isUp ? positiveLabel : negativeLabel} {formatPercent(Math.abs(value), 1)}
    </Badge>
  );
}

const CustomTooltip = ({ active, payload, label }: TooltipProps<ValueType, NameType>) => {
  if (active && payload && payload.length) {
    return (
      <div className="rounded-lg border bg-background/95 p-2.5 shadow-xl backdrop-blur-sm ring-1 ring-black/5">
        <div className="mb-1.5 border-b pb-1 text-xs font-medium text-foreground">
          {label}
        </div>
        <div className="grid gap-1">
          {payload.map((entry, index) => {
            const name = entry.name?.toString() || "";
            const isRevenue = name.includes("revenue");
            const isMargin = name.includes("margin");
            const isAov = name.includes("aov");
            const isProfit = name.includes("profit");
            const isCogs = name.includes("cogs");
            
            let valueFormatted = "";
            if (isRevenue || isAov || isProfit || isCogs) valueFormatted = formatCurrency(Number(entry.value));
            else if (isMargin) valueFormatted = `${Number(entry.value).toFixed(1)}%`;
            else valueFormatted = formatNumber(Number(entry.value));

            return (
              <div key={index} className="flex items-center justify-between gap-3 text-xs">
                <div className="flex items-center gap-1.5">
                  <div
                    className="h-2 w-2 rounded-full"
                    style={{ backgroundColor: entry.color }}
                  />
                  <span className="text-muted-foreground">
                     {name.replace(/-/g, " ")}
                  </span>
                </div>
                <span className="font-mono font-medium tabular-nums">{valueFormatted}</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
  return null;
};

function LoadingBlock() {
  return (
    <div className="space-y-4">
      <Skeleton className="h-48 w-full" />
      <div className="grid gap-3 grid-cols-2 lg:grid-cols-4">
        {[...Array(4)].map((_, index) => (
          <Skeleton key={index} className="h-20 w-full" />
        ))}
      </div>
    </div>
  );
}

export function BlackFridayDashboard() {
  // Anchor on the BUSINESS date (Chicago calendar), not UTC.
  const [businessYear, businessMonth] = businessTodayStr()
    .split("-")
    .map(Number);
  const currentYear = businessYear;
  const currentMonth = businessMonth;
  // Show previous year until November of current year
  const displayYear = currentMonth < 11 ? currentYear - 1 : currentYear;
  const availableYears = useMemo(
    () =>
      Array.from({ length: 6 }, (_, index) => currentYear - index).filter(
        (year) => year >= 2018
      ),
    [currentYear]
  );

  const [selectedYears] = useState<number[]>(
    availableYears.slice(0, 6)
  );
  const [dataByYear, setDataByYear] = useState<Record<number, YearMetrics>>({});
  const [bucketDebug, setBucketDebug] = useState<DebugBucketNote[]>([]);
  const [showDebug] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [refreshToken, setRefreshToken] = useState(0);
  const [realtimeSnapshot, setRealtimeSnapshot] = useState<RealtimeSnapshot>({
    last5MinUsers: 0,
    last30MinUsers: 0,
    lastUpdated: null,
  });
  const [realtimeError, setRealtimeError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    const loadData = async () => {
      setLoading(true);
      setError(null);

      try {
        const results = await Promise.all(
          selectedYears.map(async (year) => {
            const range = getBlackFridayRange(year);
            const params = {
              timeRange: "custom",
              startDate: range.start.toUTC().toISO(),
              endDate: range.end.toUTC().toISO(),
            };

            const debugNotes: DebugBucketNote[] = [];

            const [statsResponseRaw, financialResponseRaw] = await Promise.all([
              acotService.getStatsDetails({
                ...params,
                metric: "revenue",
                eventType: "PLACED_ORDER",
                daily: true,
                excludeCherryBox: true,
              }),
              acotService.getFinancials({
                timeRange: "custom",
                startDate: params.startDate,
                endDate: params.endDate,
                excludeCherryBox: true,
              }),
            ]);

            const statsResponse = statsResponseRaw as StatsDetailsResponse;
            const financialResponse = financialResponseRaw as FinancialsResponse;

            const days = buildDayBuckets(range.start);
            const stats = Array.isArray(statsResponse?.stats)
              ? statsResponse.stats
              : [];
            mapStatsToDays(days, stats, range.start, debugNotes);
            mapFinancialTrendToDays(
              days,
              Array.isArray(financialResponse?.trend) ? financialResponse.trend : [],
              range.start,
              debugNotes
            );
            finalizeMetrics(days);

            const totals = computeTotals(
              days,
              (financialResponse?.totals as Record<string, unknown>) || {}
            );

            return {
              year,
              range,
              days,
              totals,
              debugNotes,
            } as YearMetrics & { debugNotes: DebugBucketNote[] };
          })
        );

        if (cancelled) return;

        const record: Record<number, YearMetrics> = {};
        const debug: DebugBucketNote[] = [];
        results.forEach((result) => {
          const { debugNotes, ...rest } = result;
          record[rest.year] = rest;
          debug.push(...debugNotes);
        });

        setDataByYear(record);
        setBucketDebug(debug);
      } catch (err) {
        if (cancelled) return;
        const message =
          typeof err === "object" &&
          err !== null &&
          "message" in err &&
          typeof (err as { message?: unknown }).message === "string"
            ? (err as { message: string }).message
            : "Failed to load Black Friday data";
        setError(message);
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void loadData();

    return () => {
      cancelled = true;
    };
  }, [selectedYears, refreshToken]);

  useEffect(() => {
    const interval = setInterval(() => {
      setRefreshToken((token) => token + 1);
    }, 30000);

    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    let cancelled = false;

    const fetchRealtime = async () => {
      try {
        const response = await apiFetch("/api/dashboard-analytics/realtime/basic", {
          credentials: "include",
        });

        if (!response.ok) {
          throw new Error("Failed to fetch realtime analytics");
        }

        const result = await response.json();
        if (cancelled) return;

        const snapshot = mapRealtimeBasic((result?.data ?? {}) as Record<string, unknown>);
        setRealtimeSnapshot(snapshot);
        setRealtimeError(null);
      } catch (err) {
        if (cancelled) return;
        setRealtimeError("Realtime data unavailable");
      }
    };

    void fetchRealtime();
    const interval = setInterval(fetchRealtime, 30000);

    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);

  const sortedYears = useMemo(
    () => [...selectedYears].sort((a, b) => b - a), // Current year first
    [selectedYears]
  );

  const chartYears = useMemo(
    () => sortedYears.filter(y => y <= displayYear),
    [sortedYears, displayYear]
  );

  const previousYears = useMemo(
    () => sortedYears.filter(y => y !== displayYear),
    [sortedYears, displayYear]
  );

  const yoyByYear = useMemo(() => {
    const map: Record<number, number | null> = {};
    const ascending = [...sortedYears].sort((a, b) => a - b);
    ascending.forEach((year, index) => {
      const current = dataByYear[year];
      const previousYear = ascending[index - 1];
      const previous = previousYear ? dataByYear[previousYear] : undefined;

      if (current && previous) {
        map[year] = percentChange(
          current.totals.revenue,
          previous.totals.revenue
        );
      } else {
        map[year] = null;
      }
    });
    return map;
  }, [dataByYear, sortedYears]);

  const chartData = useMemo(() => {
    if (!chartYears.length) return [];

    return DAY_LABELS.map((label, index) => {
      const point: Record<string, string | number | null> = { day: label };
      chartYears.forEach((year, colorIndex) => {
        const day = dataByYear[year]?.days[index];
        point[`${year}-revenue`] = day?.revenue ?? 0;
        point[`${year}-orders`] = day?.orders ?? 0;
        point[`${year}-margin`] = day?.margin ?? null;
        point[`${year}-aov`] = day?.avgOrderValue ?? 0;
        point[`${year}-profit`] = day?.profit ?? 0;
        point[`${year}-cogs`] = day?.cogs ?? 0;
        point[`color-${year}`] = COLOR_PALETTE[colorIndex % COLOR_PALETTE.length];
      });
      return point;
    });
  }, [dataByYear, chartYears]);

  const debugOverlay = useMemo(() => {
    if (!bucketDebug.length) return [];
    return bucketDebug.slice(0, 200); // keep overlay readable
  }, [bucketDebug]);

  const getStrokeForYear = (year: number) => {
    const index = chartYears.indexOf(year);
    return COLOR_PALETTE[index % COLOR_PALETTE.length];
  };

  const currentYearData = dataByYear[displayYear];
  const lastYearData = dataByYear[displayYear - 1];

  // Live status indicator
  const renderLiveHeader = () => (
    <div className="flex items-center justify-between gap-4 flex-wrap">
      <div className="flex items-center gap-3">
        <h1 className="text-xl font-bold tracking-tight">Black Friday {displayYear}</h1>
        <span className="text-sm text-muted-foreground">{currentYearData?.range.label}</span>
      </div>
    </div>
  );

  // Realtime shoppers strip - more prominent
  const renderRealtimeStrip = () => (
    <div className="flex items-center gap-6 text-sm">
      <div className="flex items-center gap-2">
        <Users className="h-4 w-4 text-muted-foreground" />
        <span className="text-muted-foreground">On site:</span>
        <span className="font-bold tabular-nums text-lg">{formatNumber(realtimeSnapshot.last5MinUsers)}</span>
        <span className="text-xs text-muted-foreground">(5m)</span>
      </div>
      <div className="h-4 w-px bg-border" />
      <div className="flex items-center gap-2">
        <span className="font-semibold tabular-nums">{formatNumber(realtimeSnapshot.last30MinUsers)}</span>
        <span className="text-xs text-muted-foreground">(30m)</span>
      </div>
      <div className="flex items-center gap-1.5 text-xs text-muted-foreground ml-auto">
        <Clock3 className="h-3 w-3" />
        {formatLastUpdated(realtimeSnapshot.lastUpdated)}
      </div>
      {realtimeError && (
        <span className="text-xs text-rose-500">{realtimeError}</span>
      )}
    </div>
  );

  // Current year hero section - big numbers
  const renderCurrentYearHero = () => {
    if (!currentYearData) return null;
    
    const yoy = yoyByYear[displayYear];
    
    return (
      <div className="rounded-xl bg-gradient-to-br from-emerald-500/5 via-emerald-500/[0.02] to-transparent border border-emerald-500/20 p-4">
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
          {/* Revenue - Primary metric */}
          <div className="col-span-2 lg:col-span-1">
            <div className="flex flex-col">
              <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1">
                <DollarSign className="h-3.5 w-3.5" />
                Revenue
              </div>
              <div className="text-3xl font-bold tracking-tight tabular-nums text-emerald-600 dark:text-emerald-400">
                {formatCurrency(currentYearData.totals.revenue, 0)}
              </div>
              {yoy !== null && (
                <InsightBadge value={yoy} positiveLabel="vs LY" negativeLabel="vs LY" className="mt-1.5 w-fit" size="lg" />
              )}
            </div>
          </div>

          {/* Orders */}
          <div>
            <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1">
              <ShoppingBag className="h-3.5 w-3.5" />
              Orders
            </div>
            <div className="text-2xl font-bold tabular-nums">
              {formatNumber(currentYearData.totals.orders)}
            </div>
            {lastYearData && (
              <div className="text-xs text-muted-foreground mt-1">
                vs {formatNumber(lastYearData.totals.orders)} LY
              </div>
            )}
          </div>

          {/* Profit */}
          <div>
            <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1">
              <TrendingUp className="h-3.5 w-3.5" />
              Profit
            </div>
            <div className="text-2xl font-bold tabular-nums text-emerald-600 dark:text-emerald-400">
              {formatCurrency(currentYearData.totals.profit, 0)}
            </div>
            {lastYearData && (
              <div className="text-xs text-muted-foreground mt-1">
                vs {formatCurrency(lastYearData.totals.profit, 0)} LY
              </div>
            )}
          </div>

          {/* Margin */}
          <div>
            <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1">
              <Percent className="h-3.5 w-3.5" />
              Margin
            </div>
            <div className="text-2xl font-bold tabular-nums">
              {formatPercent(currentYearData.totals.margin, 1)}
            </div>
            {lastYearData && (
              <div className="text-xs text-muted-foreground mt-1">
                vs {formatPercent(lastYearData.totals.margin, 1)} LY
              </div>
            )}
          </div>

          {/* AOV */}
          <div>
            <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1">
              <Zap className="h-3.5 w-3.5" />
              AOV
            </div>
            <div className="text-2xl font-bold tabular-nums">
              {formatCurrency(currentYearData.totals.avgOrderValue, 0)}
            </div>
            {lastYearData && (
              <div className="text-xs text-muted-foreground mt-1">
                vs {formatCurrency(lastYearData.totals.avgOrderValue, 0)} LY
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  // Daily progress for current year
  const renderCurrentYearDays = () => {
    if (!currentYearData) return null;

    return (
      <div className="grid grid-cols-3 lg:grid-cols-6 gap-2">
        {currentYearData.days.map((day, idx) => {
          const lastYearDay = lastYearData?.days[idx];
          const change = lastYearDay ? percentChange(day.revenue, lastYearDay.revenue) : null;
          const isToday = idx === Math.min(
            Math.floor(
              DateTime.now().setZone(BUSINESS_TIMEZONE).diff(currentYearData.range.start, 'days').days
            ),
            5
          );
          
          return (
            <div
              key={day.label}
              className={cn(
                "rounded-lg border p-2.5 transition-all",
                isToday 
                  ? "bg-emerald-500/10 border-emerald-500/30 ring-1 ring-emerald-500/20" 
                  : "bg-muted/30 hover:bg-muted/50"
              )}
            >
              <div className="flex items-center justify-between mb-1.5">
                <span className={cn(
                  "text-xs font-semibold",
                  isToday ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground"
                )}>
                  {day.label}
                </span>
                {isToday && (
                  <div className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse" />
                )}
              </div>
              <div className="text-base font-bold tabular-nums leading-tight">
                {formatCurrency(day.revenue, 0)}
              </div>
              <div className="flex items-center justify-between mt-1">
                <span className="text-[10px] text-muted-foreground tabular-nums">
                  {formatNumber(day.orders)} ord
                </span>
                {change !== null && (
                  <span className={cn(
                    "text-[10px] font-medium tabular-nums",
                    change >= 0 ? "text-emerald-600" : "text-rose-500"
                  )}>
                    {change >= 0 ? "+" : ""}{change.toFixed(0)}%
                  </span>
                )}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // Compact previous years comparison
  const renderPreviousYearsComparison = () => {
    if (!previousYears.length) return null;

    return (
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-2">
        {previousYears.slice(0, 5).map((year) => {
          const data = dataByYear[year];
          if (!data) return null;
          
          const yoy = yoyByYear[year];
          
          return (
            <div key={year} className="rounded-lg border bg-card p-3 hover:bg-muted/30 transition-colors">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-bold">{year}</span>
                {yoy !== null && (
                  <span className={cn(
                    "text-xs font-medium tabular-nums",
                    yoy >= 0 ? "text-emerald-600" : "text-rose-500"
                  )}>
                    {yoy >= 0 ? "+" : ""}{yoy.toFixed(1)}%
                  </span>
                )}
              </div>
              <div className="text-lg font-bold tabular-nums mb-1">
                {formatCurrency(data.totals.revenue, 0)}
              </div>
              <div className="flex gap-3 text-[10px] text-muted-foreground">
                <span>{formatNumber(data.totals.orders)} orders</span>
                <span>{formatPercent(data.totals.margin, 0)} margin</span>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // Compact charts - 3x2 grid (Revenue/Profit on top, COGS/Margin in middle, Orders/AOV on bottom)
  const renderCharts = () => (
    <div className="grid gap-3 grid-cols-1 md:grid-cols-2">
      {/* Revenue Chart */}
      <Card className="border-muted">
        <CardHeader className="pb-2 pt-3 px-4">
          <CardTitle className="text-sm font-medium flex items-center gap-2">
            <DollarSign className="h-4 w-4 text-muted-foreground" />
            Revenue
          </CardTitle>
        </CardHeader>
        <CardContent className="p-2 pt-0">
          <div className="h-[160px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="day" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }} 
                  dy={5}
                />
                <YAxis 
                  tickFormatter={(value) => `$${(value as number / 1000).toFixed(0)}k`}
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }}
                  width={45}
                />
                <RechartsTooltip content={<CustomTooltip />} />
                {chartYears.map((year) => (
                  <Line
                    key={year}
                    type="monotone"
                    name={`${year}`}
                    dataKey={`${year}-revenue`}
                    stroke={getStrokeForYear(year)}
                    strokeWidth={year === displayYear ? 2.5 : 1.5}
                    strokeOpacity={year === displayYear ? 1 : 0.6}
                    dot={year === displayYear ? { r: 3, strokeWidth: 2, fill: "hsl(var(--background))" } : false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* Profit Chart */}
      <Card className="border-muted">
        <CardHeader className="pb-2 pt-3 px-4">
          <CardTitle className="text-sm font-medium flex items-center gap-2">
            <Wallet className="h-4 w-4 text-emerald-500" />
            Profit
          </CardTitle>
        </CardHeader>
        <CardContent className="p-2 pt-0">
          <div className="h-[160px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="day" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }} 
                  dy={5}
                />
                <YAxis 
                  tickFormatter={(value) => `$${(value as number / 1000).toFixed(0)}k`}
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }}
                  width={45}
                />
                <RechartsTooltip content={<CustomTooltip />} />
                {chartYears.map((year) => (
                  <Line
                    key={year}
                    type="monotone"
                    name={`${year}`}
                    dataKey={`${year}-profit`}
                    stroke={getStrokeForYear(year)}
                    strokeWidth={year === displayYear ? 2.5 : 1.5}
                    strokeOpacity={year === displayYear ? 1 : 0.6}
                    dot={year === displayYear ? { r: 3, strokeWidth: 2, fill: "hsl(var(--background))" } : false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* COGS Chart */}
      <Card className="border-muted">
        <CardHeader className="pb-2 pt-3 px-4">
          <CardTitle className="text-sm font-medium flex items-center gap-2">
            <Package className="h-4 w-4 text-muted-foreground" />
            COGS
          </CardTitle>
        </CardHeader>
        <CardContent className="p-2 pt-0">
          <div className="h-[160px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="day" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }} 
                  dy={5}
                />
                <YAxis 
                  tickFormatter={(value) => `$${(value as number / 1000).toFixed(0)}k`}
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }}
                  width={45}
                />
                <RechartsTooltip content={<CustomTooltip />} />
                {chartYears.map((year) => (
                  <Line
                    key={year}
                    type="monotone"
                    name={`${year}`}
                    dataKey={`${year}-cogs`}
                    stroke={getStrokeForYear(year)}
                    strokeWidth={year === displayYear ? 2.5 : 1.5}
                    strokeOpacity={year === displayYear ? 1 : 0.6}
                    dot={year === displayYear ? { r: 3, strokeWidth: 2, fill: "hsl(var(--background))" } : false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* Margin Chart */}
      <Card className="border-muted">
        <CardHeader className="pb-2 pt-3 px-4">
          <CardTitle className="text-sm font-medium flex items-center gap-2">
            <Percent className="h-4 w-4 text-muted-foreground" />
            Margin
          </CardTitle>
        </CardHeader>
        <CardContent className="p-2 pt-0">
          <div className="h-[160px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="day" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }} 
                  dy={5}
                />
                <YAxis 
                  tickFormatter={(value) => `${Number(value).toFixed(0)}%`}
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }}
                  width={35}
                />
                <RechartsTooltip content={<CustomTooltip />} />
                {chartYears.map((year) => (
                  <Line
                    key={year}
                    type="monotone"
                    name={`${year}`}
                    dataKey={`${year}-margin`}
                    stroke={getStrokeForYear(year)}
                    strokeWidth={year === displayYear ? 2.5 : 1.5}
                    strokeOpacity={year === displayYear ? 1 : 0.6}
                    dot={year === displayYear ? { r: 3, strokeWidth: 2, fill: "hsl(var(--background))" } : false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* Orders Chart */}
      <Card className="border-muted">
        <CardHeader className="pb-2 pt-3 px-4">
          <CardTitle className="text-sm font-medium flex items-center gap-2">
            <ShoppingBag className="h-4 w-4 text-muted-foreground" />
            Orders
          </CardTitle>
        </CardHeader>
        <CardContent className="p-2 pt-0">
          <div className="h-[160px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="day" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }} 
                  dy={5}
                />
                <YAxis 
                  tickFormatter={(value) => formatNumber(Number(value))} 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }}
                  width={40}
                />
                <RechartsTooltip content={<CustomTooltip />} />
                {chartYears.map((year) => (
                  <Line
                    key={year}
                    type="monotone"
                    name={`${year}`}
                    dataKey={`${year}-orders`}
                    stroke={getStrokeForYear(year)}
                    strokeWidth={year === displayYear ? 2.5 : 1.5}
                    strokeOpacity={year === displayYear ? 1 : 0.6}
                    dot={year === displayYear ? { r: 3, strokeWidth: 2, fill: "hsl(var(--background))" } : false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* AOV Chart */}
      <Card className="border-muted">
        <CardHeader className="pb-2 pt-3 px-4">
          <CardTitle className="text-sm font-medium flex items-center gap-2">
            <Zap className="h-4 w-4 text-muted-foreground" />
            AOV
          </CardTitle>
        </CardHeader>
        <CardContent className="p-2 pt-0">
          <div className="h-[160px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                <XAxis 
                  dataKey="day" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }} 
                  dy={5}
                />
                <YAxis 
                  tickFormatter={(value) => `$${Number(value).toFixed(0)}`}
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 10 }}
                  width={40}
                />
                <RechartsTooltip content={<CustomTooltip />} />
                {chartYears.map((year) => (
                  <Line
                    key={year}
                    type="monotone"
                    name={`${year}`}
                    dataKey={`${year}-aov`}
                    stroke={getStrokeForYear(year)}
                    strokeWidth={year === displayYear ? 2.5 : 1.5}
                    strokeOpacity={year === displayYear ? 1 : 0.6}
                    dot={year === displayYear ? { r: 3, strokeWidth: 2, fill: "hsl(var(--background))" } : false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>
    </div>
  );

  // Compact year comparison table
  const renderComparisonTable = () => (
    <Card className="border-muted">
      <CardHeader className="pb-2 pt-3 px-4">
        <CardTitle className="text-sm font-medium">Year-over-Year Comparison</CardTitle>
      </CardHeader>
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="hover:bg-transparent border-b">
                <TableHead className="text-xs font-semibold h-8 pl-4">Year</TableHead>
                <TableHead className="text-xs font-semibold h-8 text-right">Revenue</TableHead>
                <TableHead className="text-xs font-semibold h-8 text-right">Orders</TableHead>
                <TableHead className="text-xs font-semibold h-8 text-right">AOV</TableHead>
                <TableHead className="text-xs font-semibold h-8 text-right">Profit</TableHead>
                <TableHead className="text-xs font-semibold h-8 text-right pr-4">Margin</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sortedYears.filter(year => year <= displayYear).map((year) => {
                const entry = dataByYear[year];
                if (!entry) return null;
                
                const isCurrentYear = year === displayYear;
                
                return (
                  <TableRow 
                    key={year} 
                    className={cn(
                      "hover:bg-muted/30",
                      isCurrentYear && "bg-emerald-500/5"
                    )}
                  >
                    <TableCell className={cn(
                      "text-xs h-9 pl-4",
                      isCurrentYear ? "font-bold text-emerald-600 dark:text-emerald-400" : "font-semibold"
                    )}>
                      {year}
                    </TableCell>
                    <TableCell className="text-xs h-9 text-right tabular-nums font-medium">
                      {formatCurrency(entry.totals.revenue, 0)}
                    </TableCell>
                    <TableCell className="text-xs h-9 text-right tabular-nums text-muted-foreground">
                      {formatNumber(entry.totals.orders)}
                    </TableCell>
                    <TableCell className="text-xs h-9 text-right tabular-nums text-muted-foreground">
                      {formatCurrency(entry.totals.avgOrderValue, 0)}
                    </TableCell>
                    <TableCell className="text-xs h-9 text-right tabular-nums font-medium text-emerald-600 dark:text-emerald-400">
                      {formatCurrency(entry.totals.profit, 0)}
                    </TableCell>
                    <TableCell className="text-xs h-9 text-right pr-4">
                      <Badge variant="outline" className="text-[10px] font-normal h-5 px-1.5">
                        {formatPercent(entry.totals.margin, 1)}
                      </Badge>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );

  const renderDebugOverlay = () => {
    if (!showDebug) return null;
    return (
      <Card className="shadow-sm border-dashed border-primary/40">
        <CardHeader className="pb-3">
          <CardTitle className="text-sm">Debug: Bucket Mapping (first 200)</CardTitle>
          <CardDescription>Raw date - business bucket assignments</CardDescription>
        </CardHeader>
        <CardContent className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="hover:bg-transparent">
                <TableHead className="min-w-[60px]">Year</TableHead>
                <TableHead className="min-w-[80px]">Source</TableHead>
                <TableHead className="min-w-[180px]">Raw</TableHead>
                <TableHead className="min-w-[80px]">Bucket</TableHead>
                <TableHead className="min-w-[60px]">Index</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {debugOverlay.map((entry, idx) => (
                <TableRow key={`${entry.year}-${entry.raw}-${idx}`} className="hover:bg-muted/40">
                  <TableCell className="font-mono text-xs">{entry.year}</TableCell>
                  <TableCell className="text-xs capitalize">{entry.source}</TableCell>
                  <TableCell className="font-mono text-xs">{entry.raw}</TableCell>
                  <TableCell className="font-semibold text-xs">{entry.bucket}</TableCell>
                  <TableCell className="font-mono text-xs">{entry.index}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    );
  };

  // Chart legend
  const renderLegend = () => (
    <div className="flex items-center gap-4 text-xs">
      {chartYears.map((year) => (
        <div key={year} className="flex items-center gap-1.5">
          <div 
            className="h-2.5 w-2.5 rounded-full" 
            style={{ backgroundColor: getStrokeForYear(year) }}
          />
          <span className={cn(
            "font-medium",
            year === displayYear ? "text-foreground" : "text-muted-foreground"
          )}>
            {year}
          </span>
        </div>
      ))}
    </div>
  );

  return (
    <div className="flex-1 p-4 lg:p-6 max-w-7xl mx-auto space-y-4">
      {/* Header with live indicator */}
      {renderLiveHeader()}
      
      {/* Realtime shoppers */}
      {renderRealtimeStrip()}
      
      {error && (
        <Alert variant="destructive" className="py-2">
          <AlertTitle className="text-sm">Unable to load Black Friday data</AlertTitle>
          <AlertDescription className="text-xs">{error}</AlertDescription>
        </Alert>
      )}

      {loading && !Object.keys(dataByYear).length ? (
        <LoadingBlock />
      ) : (
        <div className="space-y-4 animate-in fade-in-50 duration-300">
          {/* Current year hero */}
          {renderCurrentYearHero()}
          
          {/* Current year daily breakdown */}
          {renderCurrentYearDays()}
          
          {/* Previous years quick comparison */}
          {previousYears.length > 0 && (
            <div className="space-y-2">
              <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Previous Years</h3>
              {renderPreviousYearsComparison()}
            </div>
          )}
          
          {/* Charts with legend */}
          <div className="space-y-2">
            <div className="flex flex-col lg:flex-row items-center justify-between">
              <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Daily Trends</h3>
              {renderLegend()}
            </div>
            {renderCharts()}
          </div>
          
          {/* Comparison table */}
          {renderComparisonTable()}
          
          {renderDebugOverlay()}
        </div>
      )}
    </div>
  );
}

export default BlackFridayDashboard;
