// Commitment Trends · committed-vs-actual cycle calibration.
//   Per engineer + per module. Sourced from DATA.etaCalibration /
//   DATA.moduleCalibration (committed cycle vs observed actual cycle).

function CommitmentTrends({ navigate }) {
  const renderCalibration = (rows, leftCell) => {
    const maxScale = Math.max(...rows.map(r => Math.max(r.avgEst, r.avgAct))) * 1.05;
    rows.sort((a, b) => b.cal.multiplier - a.cal.multiplier);
    const trackColor = 'var(--surface-2)';
    const estColor = 'var(--accent)';
    return (
      <div className="card" style={{ padding: '14px 16px' }}>
        <div style={{ display: 'grid', gap: 14 }}>
          {rows.map(({ key, cal, avgEst, avgAct }) => {
            const m = cal.multiplier;
            const tone = m > 1.3 ? 'bad' : m > 1.1 ? 'warn' : 'good';
            const actColor = m > 1.3 ? 'var(--bad)' : m > 1.1 ? 'var(--warn)' : 'var(--good)';
            const estPct = (avgEst / maxScale) * 100;
            const actPct = (avgAct / maxScale) * 100;
            return (
              <div key={key} style={{ display: 'grid', gridTemplateColumns: '180px 1fr 110px', gap: 14, alignItems: 'center' }}>
                {leftCell(key)}
                <div style={{ display: 'grid', gap: 5 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <em className="mono" style={{ fontStyle: 'normal', fontSize: 9.5, color: 'var(--text-3)', width: 70, letterSpacing: '0.06em' }}>COMMITTED</em>
                    <div style={{ flex: 1, position: 'relative', height: 10, background: trackColor, borderRadius: 3 }}>
                      <div style={{ position: 'absolute', inset: 0, width: estPct + '%', background: estColor, borderRadius: 3, opacity: 0.78 }} />
                    </div>
                    <span className="mono" style={{ fontSize: 11, width: 44, textAlign: 'right' }}>{avgEst.toFixed(1)}d</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <em className="mono" style={{ fontStyle: 'normal', fontSize: 9.5, color: 'var(--text-3)', width: 70, letterSpacing: '0.06em' }}>ACTUAL</em>
                    <div style={{ flex: 1, position: 'relative', height: 10, background: trackColor, borderRadius: 3 }}>
                      <div style={{ position: 'absolute', inset: 0, width: estPct + '%', background: estColor, borderRadius: 3, opacity: 0.18 }} />
                      <div style={{ position: 'absolute', inset: 0, width: actPct + '%', background: actColor, borderRadius: 3 }} />
                    </div>
                    <span className="mono" style={{ fontSize: 11, width: 44, textAlign: 'right' }}>{avgAct.toFixed(1)}d</span>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8 }}>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--text-3)' }}>{cal.points.length} tk</span>
                  <span className={`tag mono tone-${tone}`}>{m}×</span>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ display: 'flex', gap: 16, marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--border)', fontSize: 11, color: 'var(--text-3)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <i style={{ width: 10, height: 10, background: estColor, borderRadius: 2, opacity: 0.78 }} /> Committed (avg)
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <i style={{ width: 10, height: 10, background: 'var(--good)', borderRadius: 2 }} /> Actual · on target
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <i style={{ width: 10, height: 10, background: 'var(--warn)', borderRadius: 2 }} /> Actual · 10–30% over
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <i style={{ width: 10, height: 10, background: 'var(--bad)', borderRadius: 2 }} /> Actual · >30% over
          </span>
          <span style={{ marginLeft: 'auto' }}>Sorted by overrun multiplier</span>
        </div>
      </div>
    );
  };

  // Per-team rollup · pool every engineer-level calibration point from each
  // team, then average. Team multiplier is recomputed from the team-aggregated
  // averages so it stays consistent with the rendered bars.
  const teamMap = new Map();
  DATA.engineers.forEach(e => {
    const cal = DATA.etaCalibration[e.id];
    if (!cal) return;
    if (!teamMap.has(e.team)) teamMap.set(e.team, { name: e.team, points: [], devCount: 0 });
    const t = teamMap.get(e.team);
    t.points.push(...cal.points);
    t.devCount += 1;
  });
  const teamRows = [...teamMap.values()].map(t => {
    const n = t.points.length;
    const avgEst = t.points.reduce((s, p) => s + p.est, 0) / n;
    const avgAct = t.points.reduce((s, p) => s + p.actual, 0) / n;
    const multiplier = Math.round((avgAct / avgEst) * 100) / 100;
    return {
      key: t.name,
      cal: { multiplier, points: t.points },
      team: t,
      avgEst, avgAct,
    };
  });

  const moduleRows = DATA.modules.map(mod => {
    const cal = DATA.moduleCalibration[mod.id];
    const n = cal.points.length;
    return {
      key: mod.id, cal, mod,
      avgEst: cal.points.reduce((s, p) => s + p.est, 0) / n,
      avgAct: cal.points.reduce((s, p) => s + p.actual, 0) / n,
    };
  });

  const teamLeft = (name) => {
    const t = teamMap.get(name);
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        <Icon name="users" size={16} />
        <span style={{ fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</span>
        <span className="mono" style={{ fontSize: 10, color: 'var(--text-3)', flexShrink: 0 }}>· {t.devCount} eng</span>
      </div>
    );
  };
  const moduleLeft = (id) => {
    const mod = DATA.modules.find(m => m.id === id);
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        <Icon name="layers" size={16} />
        <span className="mono" style={{ fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{mod.name}</span>
      </div>
    );
  };

  return (
    <div className="page page-fade">
      <div style={{ marginBottom: 14 }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>Commitment trends</h1>
      </div>

      <div className="section-head">
        <div>
          <div className="section-eyebrow">Committed vs actual cycle (calendar days) · all engineers pooled per team</div>
          <div className="section-title">Commitment calibration · per team</div>
        </div>
      </div>
      {renderCalibration(teamRows, teamLeft)}

      <div className="section-head">
        <div>
          <div className="section-eyebrow">Committed vs actual cycle (calendar days)</div>
          <div className="section-title">Commitment calibration · per module</div>
        </div>
      </div>
      {renderCalibration(moduleRows, moduleLeft)}
    </div>
  );
}

window.CommitmentTrends = CommitmentTrends;
