'use client';

/**
 * CustomTooltip — Themed tooltip for Recharts charts.
 *
 * Features:
 * - Dark background (#141414) matching Divisi card color
 * - Accent border (#c8e600) for brand consistency
 * - Displays exact value, label, and percentage where applicable
 * - Styled with the Divisi theme tokens
 *
 * Requirements: 16.2
 */

import { tooltipStyle } from '@/lib/constants/theme';

interface TooltipPayloadItem {
  name?: string;
  value?: number | string;
  color?: string;
  dataKey?: string;
  payload?: Record<string, unknown>;
}

interface CustomTooltipProps {
  active?: boolean;
  payload?: TooltipPayloadItem[];
  label?: string;
  /** If true, show percentage alongside value (useful for pie charts) */
  showPercentage?: boolean;
  /** Total value for computing percentages */
  total?: number;
}

export default function CustomTooltip({
  active,
  payload,
  label,
  showPercentage = false,
  total,
}: CustomTooltipProps) {
  if (!active || !payload || payload.length === 0) {
    return null;
  }

  return (
    <div
      className="rounded-lg px-3 py-2 shadow-lg border border-divisi-accent bg-divisi-card"
    >
      {label && (
        <p
          className="text-xs font-medium mb-1 text-divisi-text-secondary"
        >
          {label}
        </p>
      )}
      {payload.map((entry, index) => {
        const value =
          typeof entry.value === 'number'
            ? entry.value.toLocaleString()
            : entry.value;

        const percentage =
          showPercentage && total && typeof entry.value === 'number'
            ? ((entry.value / total) * 100).toFixed(1)
            : null;

        return (
          <div key={index} className="flex items-center gap-2 text-sm">
            <span
              className="inline-block h-2.5 w-2.5 rounded-full flex-shrink-0"
              style={{ backgroundColor: entry.color ?? tooltipStyle.borderColor }}
            />
            <span className="text-divisi-text-primary">
              {entry.name ?? entry.dataKey}: {value}
              {percentage && (
                <span className="ml-1 text-divisi-text-secondary">
                  ({percentage}%)
                </span>
              )}
            </span>
          </div>
        );
      })}
    </div>
  );
}
