// Zakładka Spalanie — ranking + wykresy spalania pojazdów

function ConsumptionTab() {
  const [data,    setData]    = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [expanded, setExpanded] = React.useState(null);
  const { sorted, sortKey, sortDir, toggleSort } = useSort(data, 'avgConsumption', 'asc');

  React.useEffect(() => {
    api.getConsumptionAll()
      .then(d => setData(d))
      .catch(e => { if (e.status === 401) { api.logout(); window.location.reload(); } })
      .finally(() => setLoading(false));
  }, []);

  // Zakres spalania dla skali wykresu
  const values = data.filter(d => d.avgConsumption !== null).map(d => d.avgConsumption);
  const maxCons = values.length ? Math.max(...values) : 20;
  const minCons = values.length ? Math.min(...values) : 0;

  const consColor = (val) => {
    if (val === null) return '#e7e5e4';
    if (val < 8)  return '#22c55e';
    if (val < 11) return '#f59e0b';
    return '#ef4444';
  };

  return (
    <>
      <PageHeader
        title="Spalanie"
        subtitle="Średnie zużycie paliwa per pojazd na podstawie tankowań"
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>

        {/* Podsumowanie KPI */}
        {!loading && data.length > 0 && (() => {
          const withCons = data.filter(d => d.avgConsumption !== null);
          const avg = withCons.length
            ? Math.round(withCons.reduce((s, d) => s + d.avgConsumption, 0) / withCons.length * 100) / 100
            : null;
          const best  = withCons.length ? withCons.reduce((a, b) => a.avgConsumption < b.avgConsumption ? a : b) : null;
          const worst = withCons.length ? withCons.reduce((a, b) => a.avgConsumption > b.avgConsumption ? a : b) : null;
          return (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginBottom: 24 }}>
              {[
                { label: 'Średnia floty',    value: avg   ? `${avg} l/100km`   : '—', sub: `${withCons.length} pojazdów z danymi`, color: '#18181b' },
                { label: 'Najoszczędniejszy', value: best  ? `${best.avgConsumption} l/100km`  : '—', sub: best  ? best.plate  : '—', color: '#166534' },
                { label: 'Największe spalanie', value: worst ? `${worst.avgConsumption} l/100km` : '—', sub: worst ? worst.plate : '—', color: '#991b1b' },
              ].map((kpi, i) => (
                <div key={i} style={{ background: '#fff', border: '1px solid #e7e5e4', borderRadius: 8, padding: 20 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>{kpi.label}</div>
                  <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: -1, color: kpi.color, fontFamily: 'JetBrains Mono, monospace' }}>{kpi.value}</div>
                  <div style={{ fontSize: 12, color: '#71717a', marginTop: 6 }}>{kpi.sub}</div>
                </div>
              ))}
            </div>
          );
        })()}

        {/* Tabela */}
        <div style={cardStyle}>
          <table style={tableStyle}>
            <thead>
              <tr>
                <th style={{ ...thStyle, width: 36 }}>#</th>
                <SortTh label="Pojazd"          k="plate"          cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Kierowca"         k="driverName"     cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Śr. spalanie"     k="avgConsumption" cur={sortKey} dir={sortDir} onSort={toggleSort} align="right" />
                <SortTh label="Łącznie km"       k="totalKm"        cur={sortKey} dir={sortDir} onSort={toggleSort} align="right" />
                <SortTh label="Łącznie litry"    k="totalLiters"    cur={sortKey} dir={sortDir} onSort={toggleSort} align="right" />
                <SortTh label="Tankowania"       k="fuelingsCount"  cur={sortKey} dir={sortDir} onSort={toggleSort} align="right" />
                <th style={thStyle}></th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr><td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Ładowanie…</td></tr>
              )}
              {!loading && sorted.length === 0 && (
                <tr><td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Brak danych — dodaj tankowania z przebiegiem</td></tr>
              )}
              {!loading && sorted.map((v, idx) => (
                <React.Fragment key={v.vehicleId}>
                  <tr style={{ ...trStyle, cursor: 'pointer', background: expanded === v.vehicleId ? '#fafaf9' : '' }}
                    onClick={() => setExpanded(expanded === v.vehicleId ? null : v.vehicleId)}>
                    <td style={{ ...tdStyle, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, textAlign: 'center' }}>{idx + 1}</td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Plate size="sm">{v.plate}</Plate>
                        <span style={{ fontSize: 12, color: '#71717a' }}>{v.brand} {v.model}</span>
                      </div>
                    </td>
                    <td style={tdStyle}>
                      {v.driverName
                        ? <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Avatar name={v.driverName} size={26} /><span style={{ fontSize: 13 }}>{v.driverName}</span></div>
                        : <span style={{ color: '#a1a1aa', fontStyle: 'italic', fontSize: 13 }}>—</span>}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {v.avgConsumption !== null ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
                          {/* Mini bar */}
                          <div style={{ width: 64, height: 6, background: '#f4f4f5', borderRadius: 3, overflow: 'hidden' }}>
                            <div style={{ width: `${Math.min(100, (v.avgConsumption / maxCons) * 100)}%`, height: '100%', background: consColor(v.avgConsumption), borderRadius: 3, transition: 'width .3s' }} />
                          </div>
                          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 14, color: consColor(v.avgConsumption) }}>
                            {v.avgConsumption}
                          </span>
                          <span style={{ fontSize: 11, color: '#71717a' }}>l/100km</span>
                        </div>
                      ) : (
                        <span style={{ color: '#a1a1aa', fontSize: 13, fontStyle: 'italic' }}>Za mało danych</span>
                      )}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 13 }}>
                      {v.totalKm > 0 ? `${fmtNum(v.totalKm)} km` : '—'}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 13 }}>
                      {fmtL(v.totalLiters)}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 13 }}>
                      {v.fuelingsCount}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'center', width: 32 }}>
                      <Icon name={expanded === v.vehicleId ? 'chevDown' : 'chevRight'} size={16} color="#a1a1aa" />
                    </td>
                  </tr>

                  {/* Rozwinięte segmenty */}
                  {expanded === v.vehicleId && v.segments.length > 0 && (
                    <tr>
                      <td colSpan={8} style={{ ...tdStyle, background: '#fafaf9', padding: 0 }}>
                        <div style={{ padding: '12px 24px 16px', borderTop: '1px solid #f4f4f5' }}>
                          <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 10 }}>
                            Historia segmentów ({v.segments.length})
                          </div>
                          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                            {v.segments.map((seg, i) => (
                              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '8px 12px', background: '#fff', borderRadius: 6, border: '1px solid #e7e5e4', fontSize: 13 }}>
                                <span style={{ color: '#71717a', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, width: 90, flexShrink: 0 }}>{fmtDate(seg.date)}</span>
                                <span style={{ fontFamily: 'JetBrains Mono, monospace', color: '#71717a', width: 80, flexShrink: 0 }}>{fmtNum(seg.km)} km</span>
                                <span style={{ fontFamily: 'JetBrains Mono, monospace', color: '#71717a', width: 70, flexShrink: 0 }}>{fmtL(seg.liters)}</span>
                                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
                                  <div style={{ flex: 1, height: 5, background: '#f4f4f5', borderRadius: 3 }}>
                                    <div style={{ width: `${Math.min(100, (seg.consumption / maxCons) * 100)}%`, height: '100%', background: consColor(seg.consumption), borderRadius: 3 }} />
                                  </div>
                                  <span style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, color: consColor(seg.consumption), minWidth: 60, textAlign: 'right' }}>
                                    {seg.consumption} l/100km
                                  </span>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>

        {/* Legenda kolorów */}
        <div style={{ display: 'flex', gap: 20, marginTop: 16, fontSize: 12, color: '#71717a' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 3, background: '#22c55e', display: 'inline-block' }} /> Oszczędne (&lt;8 l/100km)</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 3, background: '#f59e0b', display: 'inline-block' }} /> Średnie (8–11 l/100km)</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 3, background: '#ef4444', display: 'inline-block' }} /> Wysokie (&gt;11 l/100km)</div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { ConsumptionTab });
