// KPI row + Sales Command (charts + leaderboard) + Projects table
const DSV = window.NCSPresaleDesignSystem_3f9137;
const R = window.Recharts || {};

const CARD = { background: 'var(--surface-card, linear-gradient(145deg,#1e293b 0%,#0f172a 100%))', border: '1px solid var(--border-card, rgba(255,255,255,0.07))', borderRadius: 14 };
const TT = { backgroundColor: 'var(--surface-card-solid, rgba(11,17,32,0.97))', borderColor: 'var(--border-brand, rgba(220,38,38,0.2))', color: 'var(--text-heading, #f8fafc)', borderRadius: 8, fontWeight: 700, fontSize: 11 };
const TXF = '#64748b';
const GR = 'rgba(100,116,139,0.2)';

/* ── KPI row ─────────────────────────────────────────────── */
function KpiRow() {
  const active = window.PROJECTS.filter(p => p.status === 'Active');
  const total = active.reduce((s, p) => s + p.value, 0);
  const weighted = active.reduce((s, p) => s + p.value * p.win / 100, 0);
  const won = window.PROJECTS.filter(p => p.stage === 'Win / Handover').length;
  const atRisk = active.filter(p => p.win < 30).length;
  const winRate = Math.round((won / window.PROJECTS.length) * 100);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 14 }} className="ncs-fade-in">
      <DSV.KpiCard label="Total Pipeline" value={baht(total)} tone="red" icon={<Icon name="dollar-sign" size={16} />} sub="Weighted coverage" subValue={Math.round(weighted/total*100)+'%'} subColor="#10b981" />
      <DSV.KpiCard label="Weighted Forecast" value={baht(weighted)} tone="emerald" icon={<Icon name="trending-up" size={16} />} sub="Probability-adjusted" subValue={baht(total-weighted)+' gap'} />
      <DSV.KpiCard label="Active Deals" value={active.length} tone="violet" icon={<Icon name="activity" size={16} />} pct={winRate} sub="In pipeline" subValue={won+' Won'} subColor="#10b981" />
      <DSV.KpiCard label="At Risk" value={atRisk} tone="rose" icon={<Icon name="alert-triangle" size={16} />} sub="Prob < 30%" subValue={atRisk>0?Math.round(atRisk/active.length*100)+'% of deals':'All healthy'} subColor={atRisk>0?'#f43f5e':'#10b981'} />
      <DSV.KpiCard label="Win Rate" value={winRate+'%'} tone="cyan" icon={<Icon name="award" size={16} />} pct={winRate} sub="Deals closed won" subValue={won+' / '+window.PROJECTS.length} subColor="rgba(255,255,255,0.5)" />
    </div>
  );
}

/* ── Sales Command view ──────────────────────────────────── */
function SalesCommand() {
  const stageAgg = window.STAGES.map(s => ({ name: s, value: window.PROJECTS.filter(p => p.stage === s).reduce((a, p) => a + p.value, 0), projects: window.PROJECTS.filter(p => p.stage === s).length })).filter(d => d.projects > 0);
  const totalDeals = stageAgg.reduce((s, d) => s + d.projects, 0);
  const leaderboard = window.SALES.map(name => {
    const rows = window.PROJECTS.filter(p => p.sale === name);
    return { sale: name, group: rows[0].group, projects: rows.length, won: rows.filter(r => r.stage === 'Win / Handover').length, pipeline: rows.reduce((a, r) => a + r.value, 0), weighted: rows.reduce((a, r) => a + r.value * r.win / 100, 0), avg: Math.round(rows.reduce((a, r) => a + r.win, 0) / rows.length) };
  }).sort((a, b) => b.pipeline - a.pipeline);

  const mobile = window.useIsMobile();

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 16 }}>
        <div style={{ ...CARD, padding: 22 }}>
          <div style={{ fontSize: 13, fontWeight: 900, color: 'var(--text-heading, #f0f6ff)', marginBottom: 2 }}>Pipeline by Quarter</div>
          <div style={{ fontSize: 10, color: TXF, marginBottom: 14 }}>Total vs Weighted (฿M)</div>
          <div style={{ height: 200 }}>
            {R.ResponsiveContainer && <R.ResponsiveContainer width="100%" height="100%">
              <R.ComposedChart data={window.QUARTERS} margin={{ top: 4, right: 12, left: -10, bottom: 0 }}>
                <R.CartesianGrid strokeDasharray="3 3" stroke={GR} vertical={false} />
                <R.XAxis dataKey="quarter" stroke={TXF} tick={{ fontSize: 10, fill: TXF, fontWeight: 600 }} />
                <R.YAxis stroke={TXF} tick={{ fontSize: 9, fill: TXF }} width={36} />
                <R.Tooltip contentStyle={TT} />
                <R.Legend wrapperStyle={{ fontSize: 10, fontWeight: 700, paddingTop: 6 }} />
                <R.Line type="monotone" dataKey="pipeline" name="Total" stroke="#3b82f6" strokeWidth={2.5} dot={{ r: 4, fill: '#3b82f6' }} />
                <R.Line type="monotone" dataKey="weighted" name="Weighted" stroke="#8b5cf6" strokeWidth={2} strokeDasharray="5 3" dot={{ r: 3, fill: '#8b5cf6' }} />
              </R.ComposedChart>
            </R.ResponsiveContainer>}
          </div>
        </div>
        <div style={{ ...CARD, padding: 22 }}>
          <div style={{ fontSize: 13, fontWeight: 900, color: 'var(--text-heading, #f0f6ff)', marginBottom: 16 }}>Sales Pipeline by Stage</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 150, height: 150, flexShrink: 0 }}>
              {R.ResponsiveContainer && <R.ResponsiveContainer width="100%" height="100%">
                <R.PieChart>
                  <R.Pie data={stageAgg} cx="50%" cy="50%" innerRadius={46} outerRadius={70} dataKey="projects" paddingAngle={2} startAngle={90} endAngle={-270}>
                    {stageAgg.map(e => <R.Cell key={e.name} fill={window.STAGE_COLORS[e.name]} />)}
                  </R.Pie>
                  <R.Tooltip contentStyle={TT} formatter={(v, n) => [v + ' deals', n]} />
                </R.PieChart>
              </R.ResponsiveContainer>}
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 7, minWidth: 0 }}>
              {stageAgg.map(d => (
                <div key={d.name} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: window.STAGE_COLORS[d.name], flexShrink: 0 }} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-heading, #f0f6ff)' }}>{d.name}</div>
                    <div style={{ fontSize: 10, color: TXF }}>{d.projects} deals · {Math.round(d.projects/totalDeals*100)}%</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div style={{ ...CARD, padding: 22 }}>
        <div style={{ fontSize: 13, fontWeight: 900, color: 'var(--text-heading, #f0f6ff)', marginBottom: 16 }}>Sales Leaderboard</div>
        {mobile ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {leaderboard.map((r, i) => (
              <div key={r.sale} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 10, background: 'var(--surface-chip, rgba(255,255,255,0.04))', border: '1px solid var(--border-subtle, rgba(255,255,255,0.06))' }}>
                <span style={{ width: 26, height: 26, borderRadius: 7, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, flexShrink: 0, background: i < 3 ? 'rgba(245,158,11,0.15)' : 'var(--surface-glass-hover, rgba(255,255,255,0.06))', color: i < 3 ? '#fbbf24' : TXF, border: i < 3 ? '1px solid rgba(245,158,11,0.3)' : '1px solid var(--border-strong, rgba(255,255,255,0.08))' }}>{i + 1}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 800, color: 'var(--text-heading, #f0f6ff)', fontSize: 13 }}>{r.sale}</div>
                  <div style={{ fontSize: 10, color: TXF }}>{r.group} · {r.projects} deals · {r.won} won · {r.avg}%</div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 900, color: '#10b981' }}>{baht(r.pipeline)}</div>
                  <div style={{ fontSize: 10, color: '#8b5cf6', fontWeight: 700 }}>{baht(r.weighted)} wtd</div>
                </div>
              </div>
            ))}
          </div>
        ) : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead><tr>
              {['#', 'Sale Owner', 'Team', 'Projects', 'Won', 'Avg%', 'Pipeline', 'Weighted'].map((h, i) => (
                <th key={h} style={{ padding: '8px 12px', fontSize: 9, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: TXF, background: 'var(--surface-chip, rgba(255,255,255,0.04))', borderBottom: '1px solid var(--border-subtle, rgba(255,255,255,0.06))', textAlign: i >= 3 ? 'right' : 'left' }}>{h}</th>
              ))}
            </tr></thead>
            <tbody>
              {leaderboard.map((r, i) => (
                <tr key={r.sale} style={{ borderBottom: '1px solid var(--border-subtle, rgba(255,255,255,0.04))' }}>
                  <td style={{ padding: '9px 12px', textAlign: 'center' }}><span style={{ width: 22, height: 22, borderRadius: 6, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 800, background: i < 3 ? 'rgba(245,158,11,0.15)' : 'rgba(255,255,255,0.06)', color: i < 3 ? '#fbbf24' : TXF, border: i < 3 ? '1px solid rgba(245,158,11,0.3)' : '1px solid rgba(255,255,255,0.08)' }}>{i + 1}</span></td>
                  <td style={{ padding: '9px 12px', fontWeight: 800, color: 'var(--text-heading, #f0f6ff)' }}>{r.sale}</td>
                  <td style={{ padding: '9px 12px', color: TXF, fontSize: 10 }}>{r.group}</td>
                  <td style={{ padding: '9px 12px', textAlign: 'right', color: '#cbd5e1' }}>{r.projects}</td>
                  <td style={{ padding: '9px 12px', textAlign: 'right', color: '#10b981', fontWeight: 700 }}>{r.won}</td>
                  <td style={{ padding: '9px 12px', textAlign: 'right', color: r.avg >= 60 ? '#10b981' : r.avg >= 30 ? '#f59e0b' : '#f87171', fontWeight: 700 }}>{r.avg}%</td>
                  <td style={{ padding: '9px 12px', textAlign: 'right', color: '#10b981', fontWeight: 800 }}>{baht(r.pipeline)}</td>
                  <td style={{ padding: '9px 12px', textAlign: 'right', color: '#8b5cf6' }}>{baht(r.weighted)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        )}
      </div>
    </div>
  );
}

/* ── Projects table view ─────────────────────────────────── */
const STAGE_TONE = { 'Requirement': 'requirement', 'Proposal': 'proposal', 'POC / Demo': 'poc', 'Negotiation': 'negotiation', 'Win / Handover': 'won', 'Lost': 'lost' };
function DealCard({ p }) {
  return (
    <div style={{ ...CARD, padding: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 800, color: 'var(--text-heading, #fff)', fontSize: 14 }}>{p.customer}</div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-red, #f87171)', marginTop: 2 }}>{p.project}</div>
        </div>
        <DSV.Badge tone={STAGE_TONE[p.stage]}>{p.stage}</DSV.Badge>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 12px', marginTop: 12, fontSize: 11 }}>
        {[['Sale', p.sale, 'var(--text-body, #e2e8f0)'], ['Presale', p.presale, 'var(--fg-violet, #c4b5fd)'], ['Vendor', p.vendor, 'var(--text-body, #e2e8f0)'], ['Solution', p.solution, 'var(--fg-cyan, #00d4ff)']].map(([k, v, c]) => (
          <div key={k}>
            <div style={{ fontSize: 8, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: TXF }}>{k}</div>
            <div style={{ color: c, fontWeight: 600, marginTop: 2 }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--border-subtle, rgba(255,255,255,0.05))' }}>
        <span style={{ fontSize: 11, fontWeight: 800, color: p.win >= 70 ? '#10b981' : p.win >= 40 ? '#f59e0b' : '#f87171' }}>Win {p.win}%</span>
        <span style={{ fontSize: 15, fontWeight: 900, color: '#10b981' }}>{baht(p.value)}</span>
      </div>
    </div>
  );
}

function ProjectsView({ query, chips }) {
  const mobile = window.useIsMobile();
  let rows = window.PROJECTS;
  if (query) { const q = query.toLowerCase(); rows = rows.filter(p => [p.customer, p.project, p.sale, p.presale, p.vendor, p.solution, p.ncs].some(v => v.toLowerCase().includes(q))); }

  if (mobile) {
    return (
      <div className="ncs-fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {rows.map(p => <DealCard key={p.id} p={p} />)}
      </div>
    );
  }

  return (
    <div style={{ ...CARD, padding: 0, overflow: 'hidden' }} className="ncs-fade-in">
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, textAlign: 'left' }}>
        <thead><tr style={{ background: 'var(--surface-chip, rgba(255,255,255,0.04))' }}>
          {['Customer / Project', 'Sale / Presale', 'Vendor · Solution', 'Stage', 'Win%', 'Value (THB)'].map((h, i) => (
            <th key={h} style={{ padding: '12px 16px', fontSize: 9, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: TXF, textAlign: i >= 4 ? 'right' : 'left', whiteSpace: 'nowrap' }}>{h}</th>
          ))}
        </tr></thead>
        <tbody>
          {rows.map(p => (
            <tr key={p.id} style={{ borderTop: '1px solid var(--border-subtle, rgba(255,255,255,0.05))' }}>
              <td style={{ padding: '12px 16px' }}>
                <div style={{ fontWeight: 800, color: 'var(--text-heading, #fff)', fontSize: 13 }}>{p.customer}</div>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-red, #f87171)', marginTop: 2 }}>{p.project}</div>
                <div style={{ fontSize: 9, color: TXF, fontFamily: 'var(--font-mono)', marginTop: 3 }}>{p.ncs}</div>
              </td>
              <td style={{ padding: '12px 16px', fontSize: 11 }}>
                <div style={{ color: 'var(--text-body, #e2e8f0)', fontWeight: 600 }}>{p.sale}</div>
                <div style={{ color: 'var(--fg-violet, #c4b5fd)', marginTop: 2 }}>{p.presale}</div>
              </td>
              <td style={{ padding: '12px 16px', fontSize: 11 }}>
                <div style={{ color: 'var(--text-body, #e2e8f0)', fontWeight: 600 }}>{p.vendor}</div>
                <div style={{ color: 'var(--fg-cyan, #00d4ff)', marginTop: 2 }}>{p.solution}</div>
              </td>
              <td style={{ padding: '12px 16px' }}><DSV.Badge tone={STAGE_TONE[p.stage]}>{p.stage}</DSV.Badge></td>
              <td style={{ padding: '12px 16px', textAlign: 'right', fontWeight: 800, color: p.win >= 70 ? '#10b981' : p.win >= 40 ? '#f59e0b' : '#f87171' }}>{p.win}%</td>
              <td style={{ padding: '12px 16px', textAlign: 'right', fontWeight: 800, color: '#10b981', whiteSpace: 'nowrap' }}>{baht(p.value)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { KpiRow, SalesCommand, ProjectsView });
