/**
 * F-148 — ChannelBreakdown: ecommerce vs POS vs admin sales breakdown.
 */

import type { ReportingChannel } from '@/lib/reporting-client';

interface ChannelData {
  channel: ReportingChannel;
  orders: number;
  grossSalesCents: number;
}

interface ChannelBreakdownProps {
  data: ChannelData[];
  totalSalesCents: number;
}

function formatCents(cents: number) {
  return `€${(cents / 100).toFixed(2)}`;
}

function channelLabel(ch: ReportingChannel) {
  const labels: Record<ReportingChannel, string> = {
    all: 'Todos',
    ecommerce: 'Ecommerce',
    pos: 'TPV',
    admin: 'Admin',
  };
  return labels[ch] ?? ch;
}

function channelColor(ch: ReportingChannel) {
  const colors: Record<ReportingChannel, string> = {
    all: 'bg-gray-100 text-gray-700 border-gray-200',
    ecommerce: 'bg-blue-50 text-blue-800 border-blue-200',
    pos: 'bg-green-50 text-green-800 border-green-200',
    admin: 'bg-purple-50 text-purple-800 border-purple-200',
  };
  return colors[ch] ?? 'bg-gray-100 text-gray-700 border-gray-200';
}

function channelIcon(ch: ReportingChannel) {
  const icons: Record<ReportingChannel, string> = {
    all: '🌐',
    ecommerce: '🛒',
    pos: '🏪',
    admin: '⚙️',
  };
  return icons[ch] ?? '📊';
}

export function ChannelBreakdown({ data, totalSalesCents }: ChannelBreakdownProps) {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
      {data.map((row) => {
        const pct = totalSalesCents > 0
          ? ((row.grossSalesCents / totalSalesCents) * 100).toFixed(1)
          : '0.0';

        return (
          <div
            key={row.channel}
            className={`rounded-xl border p-5 flex flex-col gap-3 ${channelColor(row.channel)}`}
          >
            <div className="flex items-center gap-2">
              <span className="text-2xl" aria-hidden>{channelIcon(row.channel)}</span>
              <p className="font-semibold text-sm">{channelLabel(row.channel)}</p>
            </div>

            <div>
              <p className="text-2xl font-bold">{formatCents(row.grossSalesCents)}</p>
              <p className="text-xs opacity-75">{row.orders} pedidos</p>
            </div>

            <div className="flex items-center gap-2">
              <div className="flex-1 bg-black/10 rounded-full h-2 overflow-hidden">
                <div
                  className="h-full rounded-full"
                  style={{ width: `${pct}%` }}
                />
              </div>
              <span className="text-xs font-medium">{pct}%</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}
