/* AIWine CRM — founder reports: funnel, win/loss, source ROI, velocity.
   All computed client-side from opportunities (+ wineries for market filter). */

function Reports({ country }) {
  const store = window.UI.useStore();
  const { money, inCountry, Ic } = window.UI;
  const STAGES = window.STAGES || [];
  const WON = window.WON_STAGES || ['customer', 'advocate'];
  const cur = country === 'AU' ? 'AU' : 'NZ';

  const opps = store.t('opportunities')
    .map((o) => ({ o, w: store.get('wineries', o.wineryId) }))
    .filter((x) => x.w && inCountry(x.w, country))
    .map((x) => x.o);

  // ---- funnel: how many deals have reached each stage (cumulative) ----
  const orderIdx = Object.fromEntries(STAGES.map((s, i) => [s.id, i]));
  const reached = (stageId) => opps.filter((o) => {
    if (o.stage === 'lost') return false;
    return (orderIdx[o.stage] != null ? orderIdx[o.stage] : -1) >= orderIdx[stageId];
  }).length;
  const funnel = STAGES.map((s) => ({ ...s, count: reached(s.id) }));
  const top = funnel.length ? funnel[0].count : 0;

  // ---- win / loss ----
  const won = opps.filter((o) => WON.includes(o.stage));
  const lost = opps.filter((o) => o.stage === 'lost');
  const decided = won.length + lost.length;
  const winRate = decided ? Math.round((won.length / decided) * 100) : 0;
  const wonValue = won.reduce((s, o) => s + (+o.value || 0), 0);
  const lossReasons = {};
  lost.forEach((o) => { const k = (o.lossReason || 'Unspecified').trim() || 'Unspecified'; lossReasons[k] = (lossReasons[k] || 0) + 1; });

  // ---- source ROI ----
  const bySource = {};
  opps.forEach((o) => { const k = o.source || 'unknown'; (bySource[k] = bySource[k] || { count: 0, won: 0, value: 0 }); bySource[k].count++; if (WON.includes(o.stage)) { bySource[k].won++; bySource[k].value += (+o.value || 0); } });
  const sources = Object.entries(bySource).sort((a, b) => b[1].count - a[1].count);

  const Bar = ({ frac, color }) => (
    <div style={{ flex: 1, height: 8, background: 'var(--bone-alt)', borderRadius: 999, overflow: 'hidden' }}>
      <div style={{ width: Math.max(2, Math.round((frac || 0) * 100)) + '%', height: '100%', background: color || 'var(--claret)' }}></div>
    </div>
  );

  return (
    <div>
      <div className="page-head">
        <div><div className="label" style={{ marginBottom: 6 }}>{opps.length} opportunities · {country === 'ALL' ? 'NZ + AU' : country}</div><h1 className="page-title">Reports</h1></div>
      </div>

      {opps.length === 0 && <window.UI.Empty msg="No opportunities yet" hint="Add deals in the pipeline and the funnel, win-rate and source reports build themselves." />}

      {opps.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* funnel */}
          <div className="card">
            <div className="card-head"><h3 className="card-title">Pipeline funnel</h3><span className="label" style={{ fontSize: 9 }}>deals that reached each stage</span></div>
            <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {funnel.map((s) => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ width: 92, fontSize: 12.5, color: 'var(--ink-soft)' }}>{s.label}</span>
                  <Bar frac={top ? s.count / top : 0} color={WON.includes(s.id) ? 'var(--green)' : 'var(--claret)'} />
                  <span className="mono" style={{ width: 64, textAlign: 'right', fontSize: 12 }}>{s.count}{top ? ' · ' + Math.round((s.count / top) * 100) + '%' : ''}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="split">
            {/* win/loss */}
            <div className="card">
              <div className="card-head"><h3 className="card-title">Win / loss</h3></div>
              <div className="card-pad">
                <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginBottom: 14 }}>
                  <div className="stat-tile"><div className="label">Win rate</div><div className="num" style={{ fontSize: 26 }}>{winRate}%</div><div className="delta" style={{ color: 'var(--muted)' }}>{won.length}/{decided} decided</div></div>
                  <div className="stat-tile"><div className="label">Won value</div><div className="num" style={{ fontSize: 22 }}>{money(wonValue, cur)}</div></div>
                  <div className="stat-tile"><div className="label">Lost</div><div className="num" style={{ fontSize: 26 }}>{lost.length}</div></div>
                </div>
                <div className="label" style={{ marginBottom: 8 }}>Loss reasons</div>
                {Object.keys(lossReasons).length === 0 && <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>No lost deals recorded.</div>}
                {Object.entries(lossReasons).sort((a, b) => b[1] - a[1]).map(([k, n]) => (
                  <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line-soft)', fontSize: 12.5 }}><span>{k}</span><span className="mono">{n}</span></div>
                ))}
              </div>
            </div>

            {/* source ROI */}
            <div className="card">
              <div className="card-head"><h3 className="card-title">Lead source</h3></div>
              <div className="card-pad">
                <table className="tbl" style={{ minWidth: 0 }}>
                  <thead><tr><th className="l">Source</th><th>Deals</th><th>Won</th><th>Won value</th></tr></thead>
                  <tbody>
                    {sources.map(([k, v]) => (
                      <tr key={k}><td className="l" style={{ textTransform: 'capitalize' }}>{k}</td><td className="num">{v.count}</td><td className="num">{v.won}</td><td className="num">{money(v.value, cur)}</td></tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.Reports = Reports;
