import React from 'react'

function formatNumber(value) {
  return new Intl.NumberFormat('en-US').format(Number(value || 0))
}

function formatPercent(value) {
  return `${Math.round(Number(value || 0) * 100)}%`
}

export default function WorldAnalyticsSourceBreakdown({ sources = [] }) {
  if (!Array.isArray(sources) || sources.length === 0) {
    return null
  }

  const maxViews = Math.max(...sources.map((row) => Number(row.views || 0)), 1)

  return (
    <div className="rounded-[24px] border border-white/10 bg-black/20 p-5">
      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Source breakdown</div>
      <div className="mt-4 grid gap-3">
        {sources.map((row) => (
          <div key={row.source_surface} className="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
            <div className="flex items-center justify-between gap-3">
              <div className="text-sm font-semibold text-white">{row.label}</div>
              <div className="text-xs uppercase tracking-[0.14em] text-slate-400">{formatNumber(row.views)} views</div>
            </div>
            <div className="mt-3 h-2 overflow-hidden rounded-full bg-white/[0.06]">
              <div className="h-full rounded-full bg-sky-300/80" style={{ width: `${Math.max(8, (Number(row.views || 0) / maxViews) * 100)}%` }} />
            </div>
            <div className="mt-3 flex flex-wrap gap-3 text-xs text-slate-400">
              <span>{formatNumber(row.impressions)} impressions</span>
              <span>{formatNumber(row.unique_visitors)} unique</span>
              <span>{formatNumber(row.clicks)} source clicks</span>
              <span>{formatPercent(row.clickthrough_rate)} CTR</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}