// Campaigns (Beta) — marketing campaigns derived from deal/lead attribution.

function CampaignsView({ deals, rawLeads, leadSources }) {
  // Aggregate by campaign name (fall back to source).
  const map = {};
  (deals || []).forEach(d => {
    const key = d.utmCampaign || `${d.utmSource || 'Direct'} (untagged)`;
    if (!map[key]) map[key] = { name: key, source: d.utmSource || 'Direct', leads: 0, won: 0, pipeline: 0, revenue: 0 };
    map[key].leads += 1;
    if (d.stage === 'FulfillmentReady') { map[key].won += 1; map[key].revenue += (d.customPackagePrice || 0); }
    else if (isActiveStage(d.stage)) map[key].pipeline += (d.customPackagePrice || 0);
  });
  (rawLeads || []).forEach(l => {
    const key = l.campaign || `${l.source || 'Direct'} (untagged)`;
    if (!map[key]) map[key] = { name: key, source: l.source || 'Direct', leads: 0, won: 0, pipeline: 0, revenue: 0, inbox: 0 };
    map[key].leads += 1; map[key].inbox = (map[key].inbox || 0) + 1;
  });
  const campaigns = Object.values(map).sort((a, b) => b.leads - a.leads);
  const totalLeads = campaigns.reduce((s, c) => s + c.leads, 0);
  const totalWon = campaigns.reduce((s, c) => s + c.won, 0);
  const totalRevenue = campaigns.reduce((s, c) => s + c.revenue, 0);

  return (
    <div className="px-7 py-6 max-w-[1200px] mx-auto">
      {/* Beta banner */}
      <div className="mb-5 flex items-start gap-3 bg-amber-50/60 border border-amber-200 rounded-xl px-4 py-3">
        <span className="text-amber-600 mt-0.5"><Icon.Sparkles size={16}/></span>
        <div className="flex-1">
          <div className="text-sm font-semibold text-amber-900 flex items-center gap-2">
            Campaigns <span className="text-[9px] px-1.5 h-4 rounded-full font-bold uppercase tracking-wide inline-flex items-center bg-amber-100 text-amber-700">Beta</span>
          </div>
          <div className="text-[12px] text-amber-800 mt-0.5">An early view of marketing performance, built from the campaign tags on your leads and deals. Full campaign creation &amp; ad-spend tracking is coming soon.</div>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-5">
        <Metric label="Active campaigns" value={campaigns.length} icon={<Icon.Trend size={14}/>}/>
        <Metric label="Attributed leads" value={totalLeads} icon={<Icon.Users size={14}/>}/>
        <Metric label="Won deals" value={totalWon} icon={<Icon.Sparkles size={14}/>}/>
        <Metric label="Won revenue" value={fmtZAR(totalRevenue) + '/mo'} icon={<Icon.Money size={14}/>}/>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between">
          <h3 className="text-sm font-semibold text-slate-900">Campaign performance</h3>
          <span className="text-[11px] text-slate-500">Sorted by attributed leads</span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr className="text-left text-[11px] uppercase tracking-wider text-slate-500 font-semibold">
                <th className="px-5 py-2.5">Campaign</th>
                <th className="px-4 py-2.5">Source</th>
                <th className="px-4 py-2.5 text-right">Leads</th>
                <th className="px-4 py-2.5 text-right">Won</th>
                <th className="px-4 py-2.5 text-right">Conv.</th>
                <th className="px-4 py-2.5 text-right">Pipeline</th>
                <th className="px-4 py-2.5 text-right">Won rev.</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {campaigns.map(c => {
                const conv = c.leads ? Math.round((c.won / c.leads) * 100) : 0;
                return (
                  <tr key={c.name} className="hover:bg-slate-50">
                    <td className="px-5 py-3 font-medium text-slate-900">{c.name}</td>
                    <td className="px-4 py-3 text-slate-600 text-[12.5px]">{c.source}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-slate-800">{c.leads}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-emerald-700 font-medium">{c.won}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-slate-600">{conv}%</td>
                    <td className="px-4 py-3 text-right tabular-nums text-slate-700">{c.pipeline ? fmtZARShort(c.pipeline) : '—'}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-slate-900 font-medium">{c.revenue ? fmtZARShort(c.revenue) : '—'}</td>
                  </tr>
                );
              })}
              {campaigns.length === 0 && (
                <tr><td colSpan={7}><Empty title="No campaign data yet" hint="Tag your leads and deals with campaigns to see performance here." icon={<Icon.Trend size={18}/>}/></td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
window.CampaignsView = CampaignsView;
