// Dashboard view — INLEARN CRM (three-entity model)
// KPI grid, funnel, source breakdown, hot deals, today's calls, new leads.

function Dashboard({ deals, contacts, rawLeads, onSelectDeal, onSetView }) {
  const active = deals.filter(d => isActiveStage(d.stage));
  const won = deals.filter(d => d.stage === 'FulfillmentReady');
  const wonRevenue = won.reduce((s,d) => s + (d.customPackagePrice || 0), 0);
  const pipelineValue = deals
    .filter(d => ['OfferMade','FormSent','InvoiceSent'].includes(d.stage))
    .reduce((s,d) => s + (d.customPackagePrice || 0), 0);

  const total = deals.length;
  const wonCount = won.length;
  const conversionRate = total ? Math.round((wonCount / total) * 100) : 0;

  const funnelStages = STAGES.filter(s => s.id !== 'LostDisqualified' && !s.archived);
  const maxCount = Math.max(...funnelStages.map(s => deals.filter(d => d.stage === s.id).length), 1);

  // Source breakdown (deals)
  const sourceMap = {};
  deals.forEach(d => { const src = d.utmSource || 'Direct'; sourceMap[src] = (sourceMap[src] || 0) + 1; });
  const sourceEntries = Object.entries(sourceMap).sort((a,b)=>b[1]-a[1]);
  const sourceMax = Math.max(...sourceEntries.map(([_,v]) => v), 1);

  const calls = deals.filter(d => d.stage === 'CallScheduled');

  const hot = deals
    .filter(d => ['OfferMade','InvoiceSent','FormSent'].includes(d.stage))
    .sort((a,b) => (b.customPackagePrice || 0) - (a.customPackagePrice || 0))
    .slice(0, 5);

  const studentName = (d) => { const s = getContact(contacts, d.studentId); return s ? contactFullName(s) : d.title; };

  return (
    <div className="px-7 py-6 space-y-6 max-w-[1400px] mx-auto">
      {/* New leads strip */}
      {rawLeads.length > 0 && (
        <button onClick={() => onSetView('leads')}
          className="w-full flex items-center gap-3 bg-emerald-50 border border-emerald-200 rounded-xl px-5 py-3.5 hover:bg-emerald-100/60 transition-colors text-left">
          <span className="h-8 w-8 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center"><Icon.Inbox size={16}/></span>
          <div className="flex-1">
            <div className="text-sm font-semibold text-emerald-900">{rawLeads.length} new lead{rawLeads.length > 1 ? 's' : ''} waiting to be qualified</div>
            <div className="text-[12px] text-emerald-700">Triage them into Contacts + Deals before they go cold.</div>
          </div>
          <span className="text-emerald-700 inline-flex items-center gap-1 text-[12px] font-semibold">Go to Leads <Icon.ChevronRight size={13}/></span>
        </button>
      )}

      {/* KPI grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Metric label="Active deals" value={active.length} sub={`${total} deals total`} icon={<Icon.Layers size={14}/>} trend={12}/>
        <Metric label="Pipeline value" value={fmtZAR(pipelineValue) + '/mo'} sub="Open offers + invoices" icon={<Icon.Money size={14}/>} trend={8}/>
        <Metric label="Won revenue" value={fmtZAR(wonRevenue) + '/mo'} sub={`${wonCount} wins`} icon={<Icon.Sparkles size={14}/>} trend={24}/>
        <Metric label="Conversion rate" value={conversionRate + '%'} sub="Deal → Won" icon={<Icon.Trend size={14}/>} trend={-3}/>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Funnel */}
        <div className="lg:col-span-2 bg-white border border-slate-200 rounded-xl p-5">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Sales Funnel</h3>
              <p className="text-xs text-slate-500">Deal count by pipeline stage</p>
            </div>
            <button onClick={() => onSetView('deals')} className="text-xs font-medium text-indigo-600 hover:text-indigo-700 inline-flex items-center gap-1">
              View pipeline <Icon.ChevronRight size={12}/>
            </button>
          </div>
          <div className="space-y-2.5">
            {funnelStages.map(stage => {
              const count = deals.filter(d => d.stage === stage.id).length;
              const tok = STAGE_TOKENS[stage.color];
              const pct = (count / maxCount) * 100;
              return (
                <div key={stage.id} className="flex items-center gap-3">
                  <div className="w-32 shrink-0"><StageChip stageId={stage.id} /></div>
                  <div className="flex-1 h-7 bg-slate-50 rounded-md overflow-hidden relative">
                    <div className="h-full rounded-md transition-all" style={{ width: pct + '%', background: tok.soft, borderRight: `2px solid ${tok.dot}` }} />
                    <div className="absolute inset-0 px-2.5 flex items-center text-[11px] text-slate-600">{stage.hint}</div>
                  </div>
                  <div className="w-12 text-right text-sm font-semibold text-slate-900 tabular-nums">{count}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Sources */}
        <div className="bg-white border border-slate-200 rounded-xl p-5">
          <div className="mb-4">
            <h3 className="text-sm font-semibold text-slate-900">Deal Sources</h3>
            <p className="text-xs text-slate-500">Where deals originated</p>
          </div>
          <div className="space-y-2.5">
            {sourceEntries.map(([src, count]) => (
              <div key={src}>
                <div className="flex items-center justify-between mb-1">
                  <span className="text-xs text-slate-700 font-medium">{src}</span>
                  <span className="text-xs text-slate-500 tabular-nums">{count}</span>
                </div>
                <div className="h-1.5 bg-slate-100 rounded-full overflow-hidden">
                  <div className="h-full bg-indigo-500 rounded-full" style={{ width: (count / sourceMax) * 100 + '%' }}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Calls */}
        <div className="bg-white border border-slate-200 rounded-xl">
          <div className="flex items-center justify-between p-5 pb-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Clarity calls booked</h3>
              <p className="text-xs text-slate-500">{calls.length} scheduled — prep and run them</p>
            </div>
            <Icon.Calendar size={16}/>
          </div>
          <div className="divide-y divide-slate-100">
            {calls.length === 0 ? (
              <Empty title="No calls booked" hint="Calls you book will appear here." icon={<Icon.Calendar size={18}/>} />
            ) : calls.map(d => (
              <button key={d.id} onClick={() => onSelectDeal(d)} className="w-full flex items-center gap-3 px-5 py-3 hover:bg-slate-50 text-left">
                <Avatar name={studentName(d)} size={32}/>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-slate-900 truncate">{d.title}</div>
                  <div className="text-[11px] text-slate-500 truncate">{d.gradeOrYear} • {(d.subjects||[]).join(', ')}</div>
                </div>
                <div className="text-right">
                  <div className="text-sm font-semibold text-slate-900 tabular-nums">{d.clarityCallTime}</div>
                  <div className="text-[11px] text-slate-500">{fmtDate(d.clarityCallDate)}</div>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Hot deals */}
        <div className="bg-white border border-slate-200 rounded-xl">
          <div className="flex items-center justify-between p-5 pb-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Hot deals</h3>
              <p className="text-xs text-slate-500">High-value deals close to closing</p>
            </div>
            <Icon.Flame size={16}/>
          </div>
          <div className="divide-y divide-slate-100">
            {hot.length === 0 ? (
              <Empty title="Nothing hot right now" hint="Once you make offers they'll show here." icon={<Icon.Flame size={18}/>} />
            ) : hot.map(d => (
              <button key={d.id} onClick={() => onSelectDeal(d)} className="w-full flex items-center gap-3 px-5 py-3 hover:bg-slate-50 text-left">
                <Avatar name={studentName(d)} size={32}/>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <div className="text-sm font-medium text-slate-900 truncate">{d.title}</div>
                    <StageChip stageId={d.stage}/>
                  </div>
                  <div className="text-[11px] text-slate-500 truncate">{d.selectedPackage || '—'} package • {(d.subjects||[]).join(', ')}</div>
                </div>
                <div className="text-right">
                  <div className="text-sm font-semibold text-slate-900 tabular-nums">{fmtZAR(d.customPackagePrice)}</div>
                  <div className="text-[11px] text-slate-500">/ month</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
window.Dashboard = Dashboard;
