/* ============================================================
   Screen 7 — Tahlilchilar (Analyst Team Performance)
   ============================================================ */

function ScreenAnalysts() {
  const [selected, setSelected] = useState(ANALYSTS[0].id);
  const [sort, setSort] = useState({ col: 'resolved', dir: 'desc' });

  // Enrich analysts with derived data
  const enriched = useMemo(() => {
    return ANALYSTS.map(a => {
      const assigned = INQUIRIES.filter(i => i.analyst === a.id);
      const open = assigned.filter(i => i.status !== 'resolved').length;
      const resolvedTotal = assigned.filter(i => i.status === 'resolved').length;
      const urgentOpen = assigned.filter(i => i.priority === 'urgent' && i.status !== 'resolved').length;
      // response-time distribution (box plot)
      const responseTimes = [];
      const baseMin = a.avgMin - 8;
      for (let i = 0; i < 60; i++) {
        responseTimes.push(Math.max(2, Math.round(baseMin + Math.abs(gauss()) * 16)));
      }
      responseTimes.sort((a, b) => a - b);
      const median = responseTimes[30];
      const q1 = responseTimes[15];
      const q3 = responseTimes[45];
      const min = responseTimes[2];
      const max = responseTimes[57];
      // daily activity heatmap: 14 days × 12 hours (8-20)
      const activity = [];
      for (let d = 0; d < 14; d++) {
        const row = [];
        const dow = (d + 5) % 7;
        const weekendMult = (dow === 5 || dow === 6) ? 0.3 : 1;
        for (let h = 0; h < 12; h++) {
          const peakHour = h >= 1 && h <= 4 ? 1.3 : h >= 5 && h <= 8 ? 1.1 : 0.7;
          row.push(Math.max(0, Math.round(rand() * 10 * weekendMult * peakHour + (a.resolved / 80))));
        }
        activity.push(row);
      }
      return {
        ...a,
        assigned: assigned.length,
        open, urgentOpen, resolvedTotal,
        boxStats: { min, q1, median, q3, max },
        activity,
        sat: a.sat ?? Math.round(88 + rand() * 9),
        weeklyResolved: a.resolved,
      };
    });
  }, []);

  const sorted = useMemo(() => {
    const arr = [...enriched];
    arr.sort((a, b) => {
      let av = a[sort.col], bv = b[sort.col];
      if (sort.col === 'name') { av = a.name; bv = b.name; }
      if (sort.col === 'median') { av = a.boxStats.median; bv = b.boxStats.median; }
      if (av < bv) return sort.dir === 'asc' ? -1 : 1;
      if (av > bv) return sort.dir === 'asc' ? 1 : -1;
      return 0;
    });
    return arr;
  }, [enriched, sort]);

  const sortBy = (col) => setSort(s => ({ col, dir: s.col === col && s.dir === 'desc' ? 'asc' : 'desc' }));
  const sortArrow = (col) => sort.col !== col ? '' : (sort.dir === 'asc' ? '↑' : '↓');

  const sel = enriched.find(a => a.id === selected);

  // Team-wide metrics
  const totalAssigned = enriched.reduce((s, a) => s + a.assigned, 0);
  const totalResolved = enriched.reduce((s, a) => s + a.weeklyResolved, 0);
  const totalOpen = enriched.reduce((s, a) => s + a.open, 0);
  const onlineCount = enriched.filter(a => a.online).length;
  const avgSat = enriched.reduce((s, a) => s + a.sat, 0) / enriched.length;
  const avgRt = enriched.reduce((s, a) => s + a.avgMin, 0) / enriched.length;

  return (
    <div className="page" style={{ maxWidth: '100%' }}>
      <div className="page-head">
        <div>
          <div className="page-crumbs">
            <span>Asosiy</span><span>/</span><span style={{ color: 'var(--ink-2)' }}>Tahlilchilar</span>
          </div>
          <h1 className="page-title">Tahlilchilar<span className="ru">Аналитики · Team performance</span></h1>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="plus" size={12} /> Yangi tahlilchi</button>
          <button className="btn btn-primary"><Icon name="download" size={12} /> Smena hisoboti</button>
        </div>
      </div>

      {/* Team KPI strip */}
      <div className="kpi-strip mb-12" style={{ gridTemplateColumns: 'repeat(6, 1fr)' }}>
        <SimpleKpi label="Jamoa" value={ANALYSTS.length} hint={`${onlineCount} onlayn`} />
        <SimpleKpi label="Topshirilgan" value={formatNum(totalAssigned)} hint="jami yuk" />
        <SimpleKpi label="Hal etilgan (haftalik)" value={formatNum(totalResolved)} hint="bu hafta" trend="up" delta="+12.4%" />
        <SimpleKpi label="Ochiq" value={formatNum(totalOpen)} hint={`${((totalOpen / totalAssigned) * 100).toFixed(0)}% yuk`} trend="down" delta="−4.1%" />
        <SimpleKpi label="O‘rt. javob vaqti" value={avgRt.toFixed(0)} hint="daqiqa · jamoa" trend="up" delta="−2.8 daq" />
        <SimpleKpi label="O‘rt. qoniqish" value={avgSat.toFixed(1)} hint="% · fermerlar" trend="up" delta="+1.4" />
      </div>

      {/* Team roster cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
        {enriched.map(a => (
          <AnalystCard key={a.id} a={a} selected={selected === a.id} onClick={() => setSelected(a.id)} />
        ))}
      </div>

      {/* Leaderboard */}
      <Panel
        title="Reyting jadvali"
        sub="ustun nomini bosing → saralash"
        num="01"
        body={false}
        className="mb-12"
      >
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 24, textAlign: 'right' }}>#</th>
              <th onClick={() => sortBy('name')} style={{ cursor: 'pointer' }}>Tahlilchi {sortArrow('name')}</th>
              <th>Boʻlim</th>
              <th onClick={() => sortBy('assigned')} style={{ cursor: 'pointer', width: 130 }}>Topshirilgan {sortArrow('assigned')}</th>
              <th onClick={() => sortBy('weeklyResolved')} style={{ cursor: 'pointer', width: 150 }}>Hal etilgan (hft) {sortArrow('weeklyResolved')}</th>
              <th onClick={() => sortBy('open')} style={{ cursor: 'pointer', width: 110 }}>Ochiq {sortArrow('open')}</th>
              <th onClick={() => sortBy('urgentOpen')} style={{ cursor: 'pointer', width: 90 }}>Shosh. {sortArrow('urgentOpen')}</th>
              <th onClick={() => sortBy('median')} style={{ cursor: 'pointer', width: 130 }}>Med. javob {sortArrow('median')}</th>
              <th onClick={() => sortBy('sat')} style={{ cursor: 'pointer', width: 130 }}>Qoniqish {sortArrow('sat')}</th>
              <th style={{ width: 60 }}>Holat</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((a, i) => (
              <tr key={a.id} style={{ cursor: 'pointer', background: selected === a.id ? 'var(--bg-sunken)' : '' }} onClick={() => setSelected(a.id)}>
                <td style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', color: 'var(--ink-4)', fontSize: 10 }}>{i + 1}</td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ position: 'relative' }}>
                      <Avatar name={a.name} size={26} />
                      <span style={{ position: 'absolute', bottom: -1, right: -1, width: 8, height: 8, borderRadius: '50%', background: a.online ? 'var(--jade)' : 'var(--ink-4)', border: '1.5px solid var(--panel)' }} />
                    </div>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 500 }}>{a.name}</div>
                      <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>{a.role}</div>
                    </div>
                  </div>
                </td>
                <td style={{ fontSize: 11.5 }}>{a.dept}</td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ flex: 1 }}><MiniBar value={a.assigned} max={Math.max(...enriched.map(x => x.assigned))} color="var(--accent)" height={5} /></div>
                    <span className="mono" style={{ fontSize: 11, width: 36, textAlign: 'right' }}>{a.assigned}</span>
                  </div>
                </td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ flex: 1 }}><MiniBar value={a.weeklyResolved} max={Math.max(...enriched.map(x => x.weeklyResolved))} color="var(--jade)" height={5} /></div>
                    <span className="mono" style={{ fontSize: 11, width: 36, textAlign: 'right' }}>{a.weeklyResolved}</span>
                  </div>
                </td>
                <td className="mono" style={{ fontSize: 11 }}>{a.open}</td>
                <td>{a.urgentOpen > 0 && <span className="chip chip-rose" style={{ fontSize: 10 }}>{a.urgentOpen}</span>}</td>
                <td>
                  <span className="mono" style={{ fontSize: 11, color: a.boxStats.median < avgRt ? 'var(--jade)' : 'var(--ink-2)' }}>
                    {a.boxStats.median} daq
                  </span>
                </td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ flex: 1, height: 4, background: 'var(--bg-sunken)', borderRadius: 1, overflow: 'hidden' }}>
                      <div style={{ width: `${a.sat}%`, height: '100%', background: a.sat >= 92 ? 'var(--jade)' : a.sat >= 88 ? 'var(--amber)' : 'var(--rose)' }} />
                    </div>
                    <span className="mono" style={{ fontSize: 11, width: 30, textAlign: 'right' }}>{a.sat}%</span>
                  </div>
                </td>
                <td>
                  <span style={{ fontSize: 10.5, color: a.online ? 'var(--jade)' : 'var(--ink-4)' }}>
                    {a.online ? 'onlayn' : 'oflayn'}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>

      {/* Charts row 1 */}
      <div className="grid-2 mb-12">
        <Panel title="Yuklama taqsimoti" sub="topshirilgan / hal etilgan stacked" num="02">
          <WorkloadStacked data={enriched} />
        </Panel>

        <Panel title="Javob vaqti taqsimoti" sub="box plot · daqiqalarda" num="03">
          <BoxPlotChart data={enriched} highlight={selected} />
        </Panel>
      </div>

    </div>
  );
}

// ============================================================
// Analyst card
// ============================================================
function AnalystCard({ a, selected, onClick }) {
  return (
    <div className="panel interactive" onClick={onClick} style={{ padding: 16, cursor: 'pointer', borderColor: selected ? 'var(--ink)' : 'var(--line)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ position: 'relative' }}>
          <Avatar name={a.name} size={44} />
          <span style={{ position: 'absolute', bottom: 0, right: 0, width: 10, height: 10, borderRadius: '50%', background: a.online ? 'var(--jade)' : 'var(--ink-4)', border: '2px solid var(--panel)' }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13, letterSpacing: '-0.01em' }}>{a.name}</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{a.role}</div>
          <div style={{ fontSize: 10, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)', marginTop: 1 }}>
            {a.id} · {a.dept}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 12px', marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
        <div>
          <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Topshirilgan</div>
          <div className="mono" style={{ fontSize: 15, fontWeight: 500 }}>{a.assigned}</div>
        </div>
        <div>
          <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Hal etilgan (hft)</div>
          <div className="mono" style={{ fontSize: 15, fontWeight: 500, color: 'var(--jade)' }}>{a.weeklyResolved}</div>
        </div>
        <div>
          <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>O‘rt. javob</div>
          <div className="mono" style={{ fontSize: 15, fontWeight: 500 }}>{a.avgMin} <span style={{ fontSize: 10, color: 'var(--ink-3)' }}>daq</span></div>
        </div>
        <div>
          <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Qoniqish</div>
          <div className="mono" style={{ fontSize: 15, fontWeight: 500, color: a.sat >= 92 ? 'var(--jade)' : 'var(--ink)' }}>{a.sat}<span style={{ fontSize: 10, color: 'var(--ink-3)' }}>%</span></div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 4, marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--line)' }}>
        {a.urgentOpen > 0 && <span className="chip chip-rose" style={{ fontSize: 9.5 }}>{a.urgentOpen} shosh.</span>}
        <span className="chip" style={{ fontSize: 9.5 }}>{a.open} ochiq</span>
        <span className="chip chip-jade" style={{ fontSize: 9.5 }}>{a.resolvedTotal} hal</span>
      </div>
    </div>
  );
}

// ============================================================
// Stacked workload bar chart
// ============================================================
function WorkloadStacked({ data }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 280;
  const padL = 90, padR = 60, padT = 10, padB = 14;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const barH = innerH / data.length - 4;
  const maxTotal = Math.max(...data.map(d => d.assigned));

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {data.map((d, i) => {
            const y = padT + i * (barH + 4) + 2;
            const total = d.assigned;
            const resolvedW = (d.resolvedTotal / maxTotal) * innerW;
            const openW = (d.open / maxTotal) * innerW;
            const urgentW = (d.urgentOpen / maxTotal) * innerW;
            return (
              <g key={d.id}>
                <text x={padL - 8} y={y + barH / 2 + 3} fontSize="11" textAnchor="end" fill="var(--ink-2)">{d.name.split(' ').map((s, j) => j === 0 ? s[0] + '.' : s).join(' ')}</text>
                <rect x={padL} y={y} width={resolvedW} height={barH} fill="var(--jade)" opacity="0.8" rx="1" />
                <rect x={padL + resolvedW} y={y} width={openW - urgentW} height={barH} fill="var(--amber)" opacity="0.7" rx="1" />
                <rect x={padL + resolvedW + (openW - urgentW)} y={y} width={urgentW} height={barH} fill="var(--rose)" opacity="0.85" rx="1" />
                <text x={padL + (resolvedW + openW) + 6} y={y + barH / 2 + 3} fontSize="10.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">{total}</text>
              </g>
            );
          })}
          {/* legend */}
          <g transform={`translate(${padL}, ${h - 2})`}>
            <rect x={0} y={-8} width={9} height={6} fill="var(--jade)" opacity="0.8" />
            <text x={13} y={-3} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">hal etilgan</text>
            <rect x={86} y={-8} width={9} height={6} fill="var(--amber)" opacity="0.7" />
            <text x={99} y={-3} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">ochiq</text>
            <rect x={140} y={-8} width={9} height={6} fill="var(--rose)" opacity="0.85" />
            <text x={153} y={-3} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">shoshilinch</text>
          </g>
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Box plot
// ============================================================
function BoxPlotChart({ data, highlight }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 280;
  const padL = 90, padR = 16, padT = 16, padB = 30;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const all = data.flatMap(d => [d.boxStats.min, d.boxStats.max]);
  const xMin = 0;
  const xMax = Math.max(...all) * 1.05;
  const x = (v) => padL + ((v - xMin) / (xMax - xMin)) * innerW;
  const rowH = innerH / data.length;
  const boxH = rowH * 0.55;

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {/* x grid */}
          {[0, 10, 20, 30, 40, 50, 60].map(v => v <= xMax && (
            <g key={v}>
              <line x1={x(v)} x2={x(v)} y1={padT} y2={padT + innerH} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={v === 0 ? '0' : '2 3'} />
              <text x={x(v)} y={h - 14} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{v}</text>
            </g>
          ))}
          <text x={padL + innerW / 2} y={h - 2} fontSize="10" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-3)">daqiqalarda javob vaqti</text>
          {data.map((d, i) => {
            const y = padT + i * rowH + (rowH - boxH) / 2;
            const b = d.boxStats;
            const isSel = d.id === highlight;
            return (
              <g key={d.id}>
                <text x={padL - 8} y={y + boxH / 2 + 3} fontSize="11" textAnchor="end" fill={isSel ? 'var(--ink)' : 'var(--ink-2)'} fontWeight={isSel ? 600 : 400}>{d.name.split(' ').map((s, j) => j === 0 ? s[0] + '.' : s).join(' ')}</text>
                {/* whiskers */}
                <line x1={x(b.min)} x2={x(b.max)} y1={y + boxH / 2} y2={y + boxH / 2} stroke="var(--ink-3)" strokeWidth="1" />
                <line x1={x(b.min)} x2={x(b.min)} y1={y + 4} y2={y + boxH - 4} stroke="var(--ink-3)" strokeWidth="1" />
                <line x1={x(b.max)} x2={x(b.max)} y1={y + 4} y2={y + boxH - 4} stroke="var(--ink-3)" strokeWidth="1" />
                {/* box */}
                <rect x={x(b.q1)} y={y} width={x(b.q3) - x(b.q1)} height={boxH} fill={isSel ? 'var(--accent-soft)' : 'var(--bg-sunken)'} stroke={isSel ? 'var(--accent-ink)' : 'var(--ink-2)'} strokeWidth={isSel ? 1.5 : 1} />
                {/* median */}
                <line x1={x(b.median)} x2={x(b.median)} y1={y} y2={y + boxH} stroke={isSel ? 'var(--accent-ink)' : 'var(--ink)'} strokeWidth="1.5" />
                {/* labels */}
                <text x={x(b.max) + 4} y={y + boxH / 2 + 3} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-3)">med {b.median}</text>
              </g>
            );
          })}
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Activity heatmap (per-analyst)
// ============================================================
function ActivityHeatmap({ data }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 220;
  const padL = 70, padR = 20, padT = 16, padB = 16;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const cols = data[0].length;
  const rows = data.length;
  const cellW = innerW / cols;
  const cellH = innerH / rows;
  const max = Math.max(...data.flat());

  const days = ['Du', 'Se', 'Ch', 'Pa', 'Ju', 'Sh', 'Ya'];
  // we have 14 days; oldest first
  const dayLabels = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(NOW);
    d.setDate(d.getDate() - (13 - i));
    return `${days[(d.getDay() + 6) % 7]} ${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}`;
  });

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {/* hour labels */}
          {Array.from({ length: cols }, (_, h) => 8 + h).map((hr, i) => (
            <text key={i} x={padL + i * cellW + cellW / 2} y={padT - 4} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{String(hr).padStart(2, '0')}</text>
          ))}
          {/* day labels */}
          {dayLabels.map((d, i) => (
            <text key={i} x={padL - 6} y={padT + i * cellH + cellH / 2 + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-3)">{d}</text>
          ))}
          {/* cells */}
          {data.map((row, i) =>
            row.map((v, j) => {
              const t = v / max;
              const fill = v === 0 ? 'var(--bg-sunken)' : `oklch(${(0.95 - t * 0.46).toFixed(3)} ${(0.02 + t * 0.10).toFixed(3)} 195)`;
              return (
                <g key={`${i}-${j}`}>
                  <rect x={padL + j * cellW + 1} y={padT + i * cellH + 1} width={cellW - 2} height={cellH - 2} fill={fill} rx="1" />
                  {v >= max * 0.6 && (
                    <text x={padL + j * cellW + cellW / 2} y={padT + i * cellH + cellH / 2 + 3} fontSize="8.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="oklch(0.30 0.05 195)" fontWeight="600">{v}</text>
                  )}
                </g>
              );
            })
          )}
        </svg>
      )}
    </div>
  );
}

// Gaussian helper
function gauss() {
  let u = 0, v = 0;
  while (u === 0) u = rand();
  while (v === 0) v = rand();
  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}

window.ScreenAnalysts = ScreenAnalysts;
