/**
 * Chart Configuration
 *
 * Centralized Recharts configuration for consistent chart appearance
 * across all dashboard components.
 */

import { METRIC_COLORS, FINANCIAL_COLORS } from "./designTokens";

// =============================================================================
// CHART LAYOUT CONFIGURATION
// =============================================================================

/**
 * Standard chart margins
 * Negative left margin accounts for Y-axis label width
 */
export const CHART_MARGINS = {
  default: { top: 10, right: 10, left: -15, bottom: 5 },
  withLegend: { top: 10, right: 10, left: -15, bottom: 25 },
  compact: { top: 5, right: 5, left: -20, bottom: 5 },
  spacious: { top: 20, right: 20, left: 0, bottom: 10 },
} as const;

/**
 * Standard chart heights
 */
export const CHART_HEIGHTS = {
  small: 200,
  medium: 300,
  default: 400,
  large: 500,
} as const;

// =============================================================================
// GRID CONFIGURATION
// =============================================================================

/**
 * CartesianGrid styling
 */
export const GRID_CONFIG = {
  strokeDasharray: "3 3",
  className: "stroke-border/40",
  stroke: "hsl(var(--border) / 0.4)",
  vertical: false, // Horizontal lines only for cleaner look
} as const;

// =============================================================================
// AXIS CONFIGURATION
// =============================================================================

/**
 * X-Axis default configuration
 */
export const X_AXIS_CONFIG = {
  className: "text-xs fill-muted-foreground",
  tickLine: false,
  axisLine: false,
  tick: { fontSize: 11 },
  dy: 10,
} as const;

/**
 * Y-Axis default configuration
 */
export const Y_AXIS_CONFIG = {
  className: "text-xs fill-muted-foreground",
  tickLine: false,
  axisLine: false,
  tick: { fontSize: 11 },
  width: 60,
} as const;

// =============================================================================
// LINE/BAR CONFIGURATION
// =============================================================================

/**
 * Line chart series configuration
 */
export const LINE_CONFIG = {
  strokeWidth: 2,
  dot: false,
  activeDot: {
    r: 4,
    strokeWidth: 2,
    className: "fill-background stroke-current",
  },
  type: "monotone" as const,
} as const;

/**
 * Area chart series configuration
 */
export const AREA_CONFIG = {
  strokeWidth: 2,
  fillOpacity: 0.1,
  type: "monotone" as const,
} as const;

/**
 * Bar chart series configuration
 */
export const BAR_CONFIG = {
  radius: [4, 4, 0, 0] as [number, number, number, number],
  maxBarSize: 50,
} as const;

// =============================================================================
// TOOLTIP CONFIGURATION
// =============================================================================

/**
 * Tooltip styling - comprehensive styles for consistent tooltip appearance
 *
 * Structure:
 * <div className={container}>
 *   <p className={header}>{date/label}</p>
 *   <div className={content}>
 *     {items.map(item => (
 *       <div className={row}>
 *         <div className={rowLabel}>
 *           <span className={dot} style={{backgroundColor: color}} />
 *           <span className={name}>{name}</span>
 *         </div>
 *         <span className={value}>{value}</span>
 *       </div>
 *     ))}
 *   </div>
 * </div>
 */
export const TOOLTIP_STYLES = {
  // Outer container
  container: "rounded-lg border border-border/50 bg-popover px-3 py-2 shadow-lg",

  // Header/label at top of tooltip
  header: "font-medium text-sm text-foreground pb-1.5 mb-1.5 border-b border-border/50",
  label: "font-medium text-sm text-foreground pb-1.5 mb-1.5 border-b border-border/50",

  // Content wrapper
  content: "space-y-1",

  // Individual row
  row: "flex justify-between items-center gap-4",

  // Left side of row (dot + name)
  rowLabel: "flex items-center gap-2",

  // Color indicator dot
  dot: "h-2.5 w-2.5 rounded-full shrink-0",

  // Metric name / item label
  name: "text-sm text-muted-foreground",
  item: "text-sm text-muted-foreground",

  // Value on right side
  value: "text-sm font-medium text-foreground",

  // Divider between sections (if needed)
  divider: "border-t border-border/50 my-1.5",
} as const;

/**
 * Themed tooltip variants for special contexts (e.g., SmallDashboard TV display)
 * These maintain the same structure as TOOLTIP_STYLES but with different color schemes
 */
export const TOOLTIP_THEMES = {
  /** Stone/neutral dark theme - for MiniSalesChart */
  stone: {
    container: "rounded-lg border-none bg-stone-800 px-3 py-2 shadow-lg",
    header: "font-medium text-sm text-stone-100 pb-1.5 mb-1.5 border-b border-stone-700",
    content: "space-y-1",
    row: "flex justify-between items-center gap-4",
    rowLabel: "flex items-center gap-2",
    dot: "h-2.5 w-2.5 rounded-full shrink-0",
    name: "text-sm text-stone-200",
    value: "text-sm font-medium text-stone-100",
  },
  /** Sky/blue dark theme - for MiniRealtimeAnalytics */
  sky: {
    container: "rounded-lg border-none bg-sky-800 px-3 py-2 shadow-lg",
    header: "font-medium text-sm text-sky-100 pb-1.5 mb-1.5 border-b border-sky-700",
    content: "space-y-1",
    row: "flex justify-between items-center gap-4",
    rowLabel: "flex items-center gap-2",
    dot: "h-2.5 w-2.5 rounded-full shrink-0",
    name: "text-sm text-sky-200",
    value: "text-sm font-medium text-sky-100",
  },
} as const;

/**
 * Tooltip cursor styling (the vertical line that follows the mouse)
 */
export const TOOLTIP_CURSOR = {
  stroke: "hsl(var(--border))",
  strokeWidth: 1,
  strokeDasharray: "4 4",
} as const;

// =============================================================================
// LEGEND CONFIGURATION
// =============================================================================

/**
 * Legend styling
 */
export const LEGEND_CONFIG = {
  wrapperStyle: {
    paddingTop: "10px",
  },
  iconType: "circle" as const,
  iconSize: 8,
  formatter: (value: string) => (
    `<span class="text-xs text-muted-foreground ml-1">${value}</span>`
  ),
} as const;

// =============================================================================
// COLOR PALETTES
// =============================================================================

/**
 * Standard chart color palette
 * Use these in order for multi-series charts
 */
export const CHART_PALETTE = [
  METRIC_COLORS.revenue,   // Emerald
  METRIC_COLORS.orders,    // Blue
  METRIC_COLORS.aov,       // Purple
  METRIC_COLORS.comparison, // Amber
  METRIC_COLORS.secondary, // Cyan
  METRIC_COLORS.tertiary,  // Pink
] as const;

/**
 * Financial chart palette
 * Preserves accounting conventions
 */
export const FINANCIAL_PALETTE = {
  income: FINANCIAL_COLORS.income,
  cogs: FINANCIAL_COLORS.expense,
  profit: FINANCIAL_COLORS.profit,
  margin: FINANCIAL_COLORS.margin,
} as const;

/**
 * Comparison chart colors (current vs previous period)
 */
export const COMPARISON_PALETTE = {
  current: METRIC_COLORS.revenue,
  previous: METRIC_COLORS.comparison,
} as const;

// =============================================================================
// FORMATTERS
// =============================================================================

/**
 * Currency formatter for chart labels
 */
export const formatChartCurrency = (value: number): string => {
  if (value >= 1000000) {
    return `$${(value / 1000000).toFixed(1)}M`;
  }
  if (value >= 1000) {
    return `$${(value / 1000).toFixed(1)}K`;
  }
  return `$${value.toFixed(0)}`;
};

/**
 * Number formatter for chart labels
 */
export const formatChartNumber = (value: number): string => {
  if (value >= 1000000) {
    return `${(value / 1000000).toFixed(1)}M`;
  }
  if (value >= 1000) {
    return `${(value / 1000).toFixed(1)}K`;
  }
  return value.toFixed(0);
};

/**
 * Percentage formatter for chart labels
 */
export const formatChartPercent = (value: number): string => {
  return `${value.toFixed(1)}%`;
};

/**
 * Date formatter for X-axis labels
 */
export const formatChartDate = (dateString: string): string => {
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
};

/**
 * Time formatter for real-time charts
 */
export const formatChartTime = (dateString: string): string => {
  const date = new Date(dateString);
  return date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
};

// =============================================================================
// PRESET CONFIGURATIONS
// =============================================================================

/**
 * Ready-to-use chart configurations for common use cases
 */
export const CHART_PRESETS = {
  /** Revenue/financial line chart */
  revenue: {
    margins: CHART_MARGINS.default,
    height: CHART_HEIGHTS.default,
    grid: GRID_CONFIG,
    xAxis: X_AXIS_CONFIG,
    yAxis: { ...Y_AXIS_CONFIG, tickFormatter: formatChartCurrency },
    line: { ...LINE_CONFIG, stroke: METRIC_COLORS.revenue },
  },

  /** Order count bar chart */
  orders: {
    margins: CHART_MARGINS.default,
    height: CHART_HEIGHTS.default,
    grid: GRID_CONFIG,
    xAxis: X_AXIS_CONFIG,
    yAxis: { ...Y_AXIS_CONFIG, tickFormatter: formatChartNumber },
    bar: { ...BAR_CONFIG, fill: METRIC_COLORS.orders },
  },

  /** Comparison chart (current vs previous) */
  comparison: {
    margins: CHART_MARGINS.withLegend,
    height: CHART_HEIGHTS.default,
    grid: GRID_CONFIG,
    xAxis: X_AXIS_CONFIG,
    yAxis: Y_AXIS_CONFIG,
    colors: COMPARISON_PALETTE,
  },

  /** Real-time metrics chart */
  realtime: {
    margins: CHART_MARGINS.compact,
    height: CHART_HEIGHTS.small,
    grid: { ...GRID_CONFIG, vertical: false },
    xAxis: { ...X_AXIS_CONFIG, tickFormatter: formatChartTime },
    yAxis: Y_AXIS_CONFIG,
  },

  /** Financial overview chart */
  financial: {
    margins: CHART_MARGINS.withLegend,
    height: CHART_HEIGHTS.default,
    grid: GRID_CONFIG,
    xAxis: X_AXIS_CONFIG,
    yAxis: { ...Y_AXIS_CONFIG, tickFormatter: formatChartCurrency },
    colors: FINANCIAL_PALETTE,
  },
} as const;

// =============================================================================
// RESPONSIVE BREAKPOINTS
// =============================================================================

/**
 * Breakpoints for responsive chart sizing
 */
export const CHART_BREAKPOINTS = {
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
} as const;

/**
 * Get responsive chart height based on container width
 */
export function getResponsiveHeight(
  containerWidth: number,
  baseHeight: number = CHART_HEIGHTS.default
): number {
  if (containerWidth < CHART_BREAKPOINTS.sm) {
    return Math.round(baseHeight * 0.6);
  }
  if (containerWidth < CHART_BREAKPOINTS.md) {
    return Math.round(baseHeight * 0.75);
  }
  return baseHeight;
}
