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

const AnalyticsView = ({ analytics, crmData, loadingTabs, fetchAnalytics }) => {
  const { useEffect } = React;
  useEffect(() => { if (!analytics) fetchAnalytics(); }, []);

  const data = analytics?.totals || {};
  const stageData = analytics?.stageCounts || {};
  const sourceData = analytics?.sourceBreakdown || {};

  const maxStageCount = Math.max(...Object.values(stageData), 1);
  const maxSourceCount = Math.max(...Object.values(sourceData), 1);

  return (
    <div className="p-6 space-y-6">
      <div>
        <div className="text-xs mono text-slate-500 uppercase tracking-widest mb-1">Performance Intelligence</div>
        <h2 className="font-black text-white text-2xl italic tracking-tight">Analytics</h2>
      </div>

      {loadingTabs.analytics ? (
        <div className="flex justify-center py-20"><div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" /></div>
      ) : (
        <>
          <div className="grid grid-cols-4 gap-4">
            <StatCard label="Total Pipeline" value={fmt$(data.totalValue || crmData.stats.pipelineValue)} icon="dollar-sign" color="#3b82f6" />
            <StatCard label="Open Deals" value={data.open || crmData.opportunities.filter(o => o.status === 'open').length} icon="target" color="#8b5cf6" />
            <StatCard label="Won Deals" value={data.won || crmData.opportunities.filter(o => o.status === 'won').length} icon="trophy" color="#10b981" />
            <StatCard label="Lost Deals" value={data.lost || crmData.opportunities.filter(o => o.status === 'lost').length} icon="x-circle" color="#ef4444" />
          </div>

          <div className="grid grid-cols-2 gap-6">
            <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl p-6">
              <div className="font-bold text-white mb-5">Pipeline by Stage</div>
              <div className="space-y-3">
                {Object.entries(stageData).length === 0 ? (
                  (() => {
                    const stages = {};
                    crmData.opportunities.forEach(o => { stages[o.stageName || 'Prospect'] = (stages[o.stageName || 'Prospect'] || 0) + 1; });
                    const max = Math.max(...Object.values(stages), 1);
                    return Object.entries(stages).map(([stage, count], i) => (
                      <div key={i}>
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-xs font-bold text-slate-400">{stage}</span>
                          <span className="text-xs mono text-slate-500">{count}</span>
                        </div>
                        <div className="h-2 bg-slate-800 rounded-full overflow-hidden">
                          <div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${(count / max) * 100}%` }} />
                        </div>
                      </div>
                    ));
                  })()
                ) : Object.entries(stageData).map(([stage, count], i) => (
                  <div key={i}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs font-bold text-slate-400">{stage}</span>
                      <span className="text-xs mono text-slate-500">{count}</span>
                    </div>
                    <div className="h-2 bg-slate-800 rounded-full overflow-hidden">
                      <div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${(count / maxStageCount) * 100}%` }} />
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl p-6">
              <div className="font-bold text-white mb-5">Lead Sources</div>
              <div className="space-y-3">
                {Object.entries(sourceData).length === 0 ? (
                  (() => {
                    const sources = {};
                    crmData.opportunities.forEach(o => { sources[o.source || 'Direct'] = (sources[o.source || 'Direct'] || 0) + 1; });
                    const max = Math.max(...Object.values(sources), 1);
                    const colors = ['#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ec4899'];
                    return Object.entries(sources).map(([src, count], i) => (
                      <div key={i}>
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-xs font-bold text-slate-400">{src}</span>
                          <span className="text-xs mono text-slate-500">{count}</span>
                        </div>
                        <div className="h-2 bg-slate-800 rounded-full overflow-hidden">
                          <div className="h-full rounded-full transition-all" style={{ width: `${(count / max) * 100}%`, background: colors[i % colors.length] }} />
                        </div>
                      </div>
                    ));
                  })()
                ) : Object.entries(sourceData).map(([src, count], i) => {
                  const colors = ['#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ec4899'];
                  return (
                    <div key={i}>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-xs font-bold text-slate-400">{src}</span>
                        <span className="text-xs mono text-slate-500">{count}</span>
                      </div>
                      <div className="h-2 bg-slate-800 rounded-full overflow-hidden">
                        <div className="h-full rounded-full transition-all" style={{ width: `${(count / maxSourceCount) * 100}%`, background: colors[i % colors.length] }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl p-6">
            <div className="font-bold text-white mb-5">Conversion Funnel</div>
            <div className="flex items-center justify-around">
              {[
                { label: 'Total Leads', value: data.total || crmData.stats.totalLeads, color: '#3b82f6' },
                { label: 'Open', value: data.open || crmData.opportunities.filter(o => o.status === 'open').length, color: '#8b5cf6' },
                { label: 'Won', value: data.won || crmData.opportunities.filter(o => o.status === 'won').length, color: '#10b981' },
                { label: 'Lost', value: data.lost || crmData.opportunities.filter(o => o.status === 'lost').length, color: '#ef4444' },
              ].map((item, i) => (
                <div key={i} className="text-center">
                  <div className="w-24 h-24 rounded-full border-4 flex items-center justify-center mx-auto mb-3" style={{ borderColor: item.color + '40', background: item.color + '10' }}>
                    <div className="font-black text-white text-2xl mono">{item.value}</div>
                  </div>
                  <div className="text-xs font-bold text-slate-500 uppercase tracking-wider">{item.label}</div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
};
