// ============================================================
// MOORE AI v13 — DASHBOARD TAB
// Requires: shared/utils.js, shared/components.jsx loaded first
// ============================================================

const DashboardView = ({ crmData, setActiveTab, setSelectedLead, setChatOpen, setChatMode, calEvents, fetchCalendar, handleSendMessage, actionItems, activeCalls }) => {
  const { useEffect } = React;
  useEffect(() => { if (calEvents.length === 0) fetchCalendar(); }, []);

  const recentOpps = crmData.opportunities.slice(0, 5);

  return (
    <div className="p-8 space-y-8 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex items-end justify-between">
        <div>
          <div className="text-xs mono text-blue-500/70 uppercase tracking-[0.3em] mb-2">Real-time Telemetry</div>
          <h1 className="text-5xl font-black text-white italic tracking-tighter leading-none">Command<br /><span className="text-blue-500">Center</span></h1>
        </div>
        <div className="flex items-center gap-3">
          <div className="text-right">
            <div className="text-xs mono text-slate-500">Good morning,</div>
            <div className="font-black text-white italic text-lg tracking-tight">Jake Moore</div>
            <div className="text-xs mono text-blue-400/70">{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</div>
          </div>
          <button onClick={() => { setChatOpen(true); setChatMode('open'); }}
            className="flex items-center gap-2 px-4 py-2.5 bg-blue-600/10 border border-blue-500/20 rounded-xl text-sm font-bold text-blue-400 hover:bg-blue-600/20 transition-all btn-glow">
            <Icon name="brain-circuit" size={15} />
            Ask Jake
          </button>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-4 gap-4">
        <StatCard label="Pipeline Value" value={fmt$(crmData.stats.pipelineValue)} icon="trending-up" color="#3b82f6" trend={12} />
        <StatCard label="Total Leads" value={crmData.stats.totalLeads} icon="users" color="#8b5cf6" />
        <StatCard label="Win Rate" value={`${crmData.stats.winRate || 0}%`} icon="trophy" color="#10b981" trend={5} />
        <StatCard label="AI Actions" value={crmData.stats.aiActions || '—'} icon="zap" color="#f59e0b" sub="This session" />
      </div>

      {/* Two columns */}
      <div className="grid grid-cols-3 gap-6">
        {/* Recent Pipeline */}
        <div className="col-span-2 bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
          <div className="flex items-center justify-between px-6 py-4 border-b border-slate-800/50">
            <div className="font-bold text-white text-sm">Recent Pipeline Activity</div>
            <button onClick={() => setActiveTab('pipeline')} className="text-xs mono text-blue-400 hover:text-blue-300 flex items-center gap-1">View all <Icon name="arrow-right" size={11} /></button>
          </div>
          <div className="divide-y divide-slate-800/40">
            {recentOpps.length === 0
              ? <div className="py-12 text-center text-xs mono text-slate-700 uppercase tracking-widest animate-pulse">Loading pipeline...</div>
              : recentOpps.map(opp => (
                <div key={opp.id} onClick={() => { setActiveTab('pipeline'); setSelectedLead(opp); }}
                  className="flex items-center gap-4 px-6 py-4 hover:bg-slate-800/20 cursor-pointer transition-colors group">
                  <Avatar name={opp.name} size={36} />
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-white text-sm truncate group-hover:text-blue-300 transition-colors">{opp.name}</div>
                    <div className="text-xs text-slate-500">{opp.contact} · {opp.stageName}</div>
                  </div>
                  <div className="flex items-center gap-3">
                    <StatusBadge status={opp.status} />
                    <div className="font-bold text-white mono text-sm">{fmt$(opp.value)}</div>
                  </div>
                </div>
              ))}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-4">
          {/* Upcoming events */}
          <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
            <div className="flex items-center justify-between px-5 py-4 border-b border-slate-800/50">
              <div className="font-bold text-white text-sm">Upcoming</div>
              <button onClick={() => setActiveTab('calendar')} className="text-[10px] mono text-blue-400 hover:text-blue-300">Calendar →</button>
            </div>
            <div className="p-4 space-y-2">
              {calEvents.slice(0, 3).length === 0
                ? <div className="text-xs text-slate-700 mono text-center py-4">No upcoming events</div>
                : calEvents.slice(0, 3).map(ev => (
                  <div key={ev.id} className="flex items-start gap-3 p-3 bg-slate-900/60 rounded-xl">
                    <div className="p-1.5 bg-blue-600/20 rounded-lg shrink-0">
                      <Icon name="calendar" size={12} className="text-blue-400" />
                    </div>
                    <div>
                      <div className="text-xs font-bold text-white leading-snug">{ev.title}</div>
                      <div className="text-[10px] mono text-slate-600 mt-0.5">{fmtDate(ev.startTime)} · {fmtTime(ev.startTime)}</div>
                    </div>
                  </div>
                ))}
            </div>
          </div>

          {/* Active calls widget */}
          {activeCalls && activeCalls.length > 0 && (
            <div className="bg-emerald-950/20 border border-emerald-700/40 rounded-2xl overflow-hidden">
              <div className="px-5 py-3 flex items-center gap-2">
                <span className="w-2 h-2 bg-emerald-400 rounded-full animate-pulse" />
                <div className="font-bold text-emerald-300 text-xs mono uppercase tracking-wider">Live Calls</div>
              </div>
              <div className="px-5 pb-3 space-y-1">
                {activeCalls.map((c,i) => (
                  <div key={i} className="text-xs text-emerald-400">{c.contactName} · {c.status}</div>
                ))}
              </div>
            </div>
          )}

          {/* Quick Commands */}
          <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
            <div className="px-5 py-4 border-b border-slate-800/50 flex items-center justify-between">
              <div className="font-bold text-white text-sm">Quick Commands</div>
              <div className="text-[10px] mono text-slate-600">Sends to Jake AI</div>
            </div>
            <div className="p-4 space-y-2">
              {[
                { cmd: "Summarize my pipeline", icon: "bar-chart-2" },
                { cmd: "Who needs follow-up?", icon: "clock" },
                { cmd: "Who's closest to closing?", icon: "target" },
                { cmd: "Call my top lead", icon: "phone" },
                { cmd: "Show open deals by value", icon: "trending-up" },
                { cmd: "Create action items from my pipeline", icon: "check-square" },
              ].map(({ cmd, icon }, i) => (
                <button key={i} onClick={() => {
                  setActiveTab('ai-command');
                  setTimeout(() => handleSendMessage(null, cmd), 150);
                }}
                  className="w-full text-left px-3 py-2.5 bg-slate-900/60 hover:bg-blue-600/10 border border-slate-800/50 hover:border-blue-500/30 rounded-xl text-xs text-slate-400 hover:text-blue-300 transition-all flex items-center gap-2 group">
                  <Icon name={icon} size={12} className="text-slate-600 group-hover:text-blue-500 shrink-0" />
                  {cmd}
                </button>
              ))}
            </div>
          </div>

          {/* Action items preview */}
          {actionItems && actionItems.filter(a => !a.done).length > 0 && (
            <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
              <div className="px-5 py-4 border-b border-slate-800/50 flex items-center justify-between">
                <div className="font-bold text-white text-sm">Pending Actions</div>
                <button onClick={() => setActiveTab('action-items')} className="text-[10px] mono text-blue-400">View all →</button>
              </div>
              <div className="p-4 space-y-2">
                {actionItems.filter(a => !a.done).slice(0,3).map((item,i) => (
                  <div key={i} className="flex items-center gap-2 text-xs text-slate-400">
                    <span className="w-1.5 h-1.5 bg-amber-500 rounded-full shrink-0" />
                    <span className="truncate">{item.title}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
