// Fuelings + Settlement tabs for AdminApp.

// ──────────────────────────────────────────────────────────────
// FUELINGS TAB
// ──────────────────────────────────────────────────────────────
function FuelingsTab({ drivers, vehicles, fuelings, ops }) {
  const [search, setSearch] = React.useState('');
  const [stationFilter, setStationFilter] = React.useState('all');
  const [driverFilter, setDriverFilter] = React.useState('all');
  const [edit, setEdit] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null);

  const filtered = fuelings
    .filter(f => {
      const driver = drivers.find(d => d.id === f.driverId);
      const vehicle = vehicles.find(v => v.id === f.vehicleId);
      const sm = ((driver?.name || '') + ' ' + (vehicle?.plate || '') + ' ' + f.station).toLowerCase().includes(search.toLowerCase());
      const stf = stationFilter === 'all' || f.station === stationFilter;
      const drf = driverFilter === 'all' || f.driverId === Number(driverFilter);
      return sm && stf && drf;
    })
;
  const { sorted: sortedFuelings, sortKey: fSortKey, sortDir: fSortDir, toggleSort: fToggle } = useSort(filtered, 'datetime', 'desc');

  const totalLiters = filtered.reduce((s, f) => s + f.liters, 0);
  const totalAmount = filtered.reduce((s, f) => s + f.amount, 0);

  return (
    <>
      <PageHeader
        title="Tankowania"
        subtitle={`${fuelings.length} rekordów łącznie`}
        action={<Btn icon="plus" onClick={() => setEdit('new')}>Dodaj tankowanie</Btn>}
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        {/* Summary strip */}
        <div style={{ display: 'flex', gap: 24, padding: '14px 20px', marginBottom: 16, background: '#18181b', color: '#fafaf9', borderRadius: 8 }}>
          <SumPill label="Rekordów" value={filtered.length} mono />
          <SumPill label="Litry" value={fmtL(totalLiters)} mono />
          <SumPill label="Kwota" value={fmtPLN(totalAmount)} mono highlight />
          <div style={{ flex: 1 }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: '#a1a1aa' }}>
            <Icon name="filter" size={14} />
            Filtry aktywne: {[stationFilter !== 'all' && stationFilter, driverFilter !== 'all' && drivers.find(d => d.id === Number(driverFilter))?.name, search].filter(Boolean).join(' • ') || 'brak'}
          </div>
        </div>

        <div style={cardStyle}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ position: 'relative', flex: 1, maxWidth: 280, minWidth: 180 }}>
              <div style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', color: '#a1a1aa' }}>
                <Icon name="search" size={15} />
              </div>
              <Input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Szukaj..." style={{ paddingLeft: 34 }} />
            </div>
            <div style={{ width: 160 }}>
              <Select value={driverFilter} onChange={(e) => setDriverFilter(e.target.value)}>
                <option value="all">Wszyscy kierowcy</option>
                {drivers.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </Select>
            </div>
            <div style={{ width: 140 }}>
              <Select value={stationFilter} onChange={(e) => setStationFilter(e.target.value)}>
                <option value="all">Wszystkie stacje</option>
                {STATIONS.map(s => <option key={s} value={s}>{s}</option>)}
              </Select>
            </div>
            <div style={{ marginLeft: 'auto', fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>
              {filtered.length} z {fuelings.length}
            </div>
          </div>
          <table style={tableStyle}>
            <thead>
              <tr>
                <SortTh label="Data"     k="datetime"   cur={fSortKey} dir={fSortDir} onSort={fToggle} />
                <SortTh label="Stacja"   k="station"    cur={fSortKey} dir={fSortDir} onSort={fToggle} />
                <SortTh label="Kierowca" k="driverName" cur={fSortKey} dir={fSortDir} onSort={fToggle} />
                <SortTh label="Pojazd"   k="vehiclePlate" cur={fSortKey} dir={fSortDir} onSort={fToggle} />
                <SortTh label="Litry"    k="liters"     cur={fSortKey} dir={fSortDir} onSort={fToggle} align="right" />
                <th style={{ ...thStyle, textAlign: 'right' }}>Cena/l</th>
                <SortTh label="Kwota"    k="amount"     cur={fSortKey} dir={fSortDir} onSort={fToggle} align="right" />
                <SortTh label="Przebieg" k="mileage"    cur={fSortKey} dir={fSortDir} onSort={fToggle} align="right" />
                <th style={{ ...thStyle, textAlign: 'right' }}>Akcje</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((f) => {
                const driver = drivers.find(d => d.id === f.driverId);
                const vehicle = vehicles.find(v => v.id === f.vehicleId);
                return (
                  <tr key={f.id} style={trStyle}>
                    <td style={tdStyle}>
                      <div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'JetBrains Mono, monospace' }}>{fmtDate(f.datetime)}</div>
                      <div style={{ fontSize: 11, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace' }}>{fmtTime(f.datetime)}</div>
                    </td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        {stationChip(f.station, { size: 22 })}
                        <span style={{ fontWeight: 600, fontSize: 13 }}>{f.station}</span>
                      </div>
                    </td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar name={driver?.name || '?'} size={26} />
                        <span style={{ fontSize: 13 }}>{driver?.name || '—'}</span>
                      </div>
                    </td>
                    <td style={tdStyle}>{vehicle ? <Plate size="sm">{vehicle.plate}</Plate> : <span style={{ color: '#a1a1aa' }}>—</span>}</td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 13 }}>{fmtL(f.liters)}</td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 13, color: '#71717a' }}>{fmtPLN(f.amount / f.liters)}</td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 13 }}>{fmtPLN(f.amount)}</td>
                    <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#71717a' }}>{fmtNum(f.mileage)} km</td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      <div style={{ display: 'inline-flex', gap: 2 }}>
                        <Btn variant="ghost" icon="edit" onClick={() => setEdit(f.id)} />
                        <Btn variant="ghost" icon="trash" onClick={() => setConfirmDel(f.id)} style={{ color: '#dc2626' }} />
                      </div>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr><td colSpan={9} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Brak wyników</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {edit !== null && (
        <FuelingForm
          fueling={edit === 'new' ? null : fuelings.find(f => f.id === edit)}
          drivers={drivers}
          vehicles={vehicles}
          onClose={() => setEdit(null)}
          onSave={(f) => { if (edit === 'new') ops.addFueling(f); else ops.updateFueling(edit, f); setEdit(null); }}
        />
      )}
      {confirmDel !== null && (
        <ConfirmDelete
          title="Usunąć tankowanie?"
          desc={`Rekord #${confirmDel.toString().padStart(3, '0')} zostanie trwale usunięty.`}
          onCancel={() => setConfirmDel(null)}
          onConfirm={() => { ops.deleteFueling(confirmDel); setConfirmDel(null); }}
        />
      )}
    </>
  );
}

function SumPill({ label, value, mono, highlight }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.2, color: '#a1a1aa', textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
      <div style={{
        fontSize: 22, fontWeight: 800, letterSpacing: -0.6,
        fontFamily: mono ? 'JetBrains Mono, monospace' : 'inherit',
        color: highlight ? '#f59e0b' : '#fafaf9',
      }}>{value}</div>
    </div>
  );
}

function FuelingForm({ fueling, drivers, vehicles, onClose, onSave }) {
  const now = new Date(2026, 4, 25, 14, 30);
  const [driverId, setDriverId] = React.useState(fueling?.driverId ?? '');
  const [vehicleId, setVehicleId] = React.useState(fueling?.vehicleId ?? '');
  const [station, setStation] = React.useState(fueling?.station || 'MOYA');
  const [liters, setLiters] = React.useState(fueling?.liters ?? '');
  const [amount, setAmount] = React.useState(fueling?.amount ?? '');
  const [mileage, setMileage] = React.useState(fueling?.mileage ?? '');
  const [datetime, setDatetime] = React.useState(
    fueling ? fueling.datetime.slice(0, 16) : now.toISOString().slice(0, 16)
  );

  // Auto-fill vehicle when driver chosen (default assignment)
  React.useEffect(() => {
    if (driverId && !fueling) {
      const v = vehicles.find(x => x.driverId === Number(driverId));
      if (v) setVehicleId(v.id);
    }
  }, [driverId]);

  const submit = (e) => {
    e.preventDefault();
    if (!driverId || !vehicleId || !liters || !amount) return;
    onSave({
      driverId: Number(driverId),
      vehicleId: Number(vehicleId),
      station,
      liters: Number(liters),
      amount: Number(amount),
      mileage: Number(mileage) || 0,
      datetime: new Date(datetime).toISOString(),
    });
  };

  return (
    <Modal
      open
      onClose={onClose}
      title={fueling ? 'Edytuj tankowanie' : 'Nowe tankowanie'}
      subtitle={fueling ? `ID #${fueling.id.toString().padStart(3, '0')}` : 'Dodaj rekord ręcznie'}
      width={540}
      footer={
        <>
          <Btn variant="secondary" onClick={onClose}>Anuluj</Btn>
          <Btn icon="check" onClick={submit}>Zapisz</Btn>
        </>
      }
    >
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Kierowca" required>
            <Select value={driverId} onChange={(e) => setDriverId(e.target.value)}>
              <option value="">— Wybierz —</option>
              {drivers.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
            </Select>
          </Field>
          <Field label="Pojazd" required>
            <Select value={vehicleId} onChange={(e) => setVehicleId(e.target.value)}>
              <option value="">— Wybierz —</option>
              {vehicles.map(v => <option key={v.id} value={v.id}>{v.plate} • {v.brand} {v.model}</option>)}
            </Select>
          </Field>
        </div>

        <Field label="Stacja paliw">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6 }}>
            {STATIONS.map(s => (
              <button key={s} type="button" onClick={() => setStation(s)} style={{
                padding: '10px 4px', border: `1.5px solid ${station === s ? '#f59e0b' : '#e4e4e7'}`,
                background: station === s ? '#fef3c7' : '#fff', borderRadius: 6, cursor: 'pointer',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                fontFamily: 'inherit', transition: 'all .12s',
              }}>
                {stationChip(s, { size: 22 })}
                <span style={{ fontSize: 10, fontWeight: 700, color: station === s ? '#854d0e' : '#52525b', letterSpacing: 0.5 }}>{s}</span>
              </button>
            ))}
          </div>
        </Field>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <Field label="Litry" required>
            <Input type="number" step="0.01" value={liters} onChange={(e) => setLiters(e.target.value)} placeholder="0,00" />
          </Field>
          <Field label="Kwota (zł)" required>
            <Input type="number" step="0.01" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0,00" />
          </Field>
          <Field label="Przebieg (km)">
            <Input type="number" value={mileage} onChange={(e) => setMileage(e.target.value)} placeholder="0" />
          </Field>
        </div>
        <Field label="Data i godzina">
          <Input type="datetime-local" value={datetime} onChange={(e) => setDatetime(e.target.value)} />
        </Field>
      </form>
    </Modal>
  );
}

// ──────────────────────────────────────────────────────────────
// SETTLEMENT TAB
// ──────────────────────────────────────────────────────────────
function SettlementTab({ drivers, vehicles, fuelings }) {
  const today = new Date();
  const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);

  const [dateFrom, setDateFrom] = React.useState(fmtDateInput(monthStart.toISOString()));
  const [dateTo, setDateTo] = React.useState(fmtDateInput(today.toISOString()));
  const [driverFilter, setDriverFilter] = React.useState('all');
  const [groupBy, setGroupBy] = React.useState('driver'); // driver | vehicle
  const [sSortKey, setSSortKey] = React.useState('datetime');
  const [sSortDir, setSSortDir] = React.useState('desc');
  const sToggle = (k) => { if (sSortKey === k) setSSortDir(d => d === 'asc' ? 'desc' : 'asc'); else { setSSortKey(k); setSSortDir('asc'); } };
  const sortFuelings = (arr) => [...arr].sort((a, b) => {
    let av = a[sSortKey], bv = b[sSortKey];
    if (av == null) av = ''; if (bv == null) bv = '';
    if (typeof av === 'number' && typeof bv === 'number') return sSortDir === 'asc' ? av - bv : bv - av;
    av = String(av).toLowerCase(); bv = String(bv).toLowerCase();
    return sSortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av);
  });

  const inRange = fuelings.filter(f => {
    const d = new Date(f.datetime);
    const from = new Date(dateFrom + 'T00:00:00');
    const to = new Date(dateTo + 'T23:59:59');
    if (d < from || d > to) return false;
    if (driverFilter !== 'all' && f.driverId !== Number(driverFilter)) return false;
    return true;
  }).sort((a, b) => new Date(b.datetime) - new Date(a.datetime));

  const totalLiters = inRange.reduce((s, f) => s + f.liters, 0);
  const totalAmount = inRange.reduce((s, f) => s + f.amount, 0);
  const avgPpl = totalLiters > 0 ? totalAmount / totalLiters : 0;

  // Group breakdown
  const breakdown = React.useMemo(() => {
    const m = new Map();
    inRange.forEach(f => {
      const key = groupBy === 'driver' ? f.driverId : f.vehicleId;
      if (!m.has(key)) m.set(key, { count: 0, liters: 0, amount: 0 });
      const e = m.get(key);
      e.count += 1; e.liters += f.liters; e.amount += f.amount;
    });
    return Array.from(m.entries()).map(([id, e]) => ({ id, ...e })).sort((a, b) => b.amount - a.amount);
  }, [inRange, groupBy]);

  const maxAmount = Math.max(1, ...breakdown.map(b => b.amount));

  // CSV export
  const exportCsv = () => {
    const header = ['Data', 'Godzina', 'Kierowca', 'Tablica', 'Marka', 'Model', 'Stacja', 'Litry', 'Cena/l', 'Kwota', 'Przebieg'];
    const rows = inRange.map(f => {
      const driver = drivers.find(d => d.id === f.driverId);
      const vehicle = vehicles.find(v => v.id === f.vehicleId);
      return [
        fmtDate(f.datetime), fmtTime(f.datetime),
        driver?.name || '', vehicle?.plate || '', vehicle?.brand || '', vehicle?.model || '',
        f.station,
        f.liters.toFixed(2).replace('.', ','),
        (f.amount / f.liters).toFixed(2).replace('.', ','),
        f.amount.toFixed(2).replace('.', ','),
        f.mileage,
      ];
    });
    const csv = '\uFEFF' + [header, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(';')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `rozliczenie_${dateFrom}_${dateTo}.csv`;
    a.click();
  };

  return (
    <>
      <PageHeader
        title="Rozliczenie"
        subtitle="Zestawienie tankowań w wybranym okresie"
        action={
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="secondary" icon="download" onClick={exportCsv}>Eksport CSV</Btn>
            <Btn icon="download" onClick={() => window.print()}>Eksport PDF</Btn>
          </div>
        }
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        {/* Filter bar */}
        <div style={{ ...cardStyle, padding: '16px 20px', marginBottom: 16, display: 'flex', gap: 16, alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <div style={{ minWidth: 140 }}>
            <Field label="Data od">
              <Input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} />
            </Field>
          </div>
          <div style={{ minWidth: 140 }}>
            <Field label="Data do">
              <Input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} />
            </Field>
          </div>
          <div style={{ minWidth: 200, flex: 1 }}>
            <Field label="Kierowca">
              <Select value={driverFilter} onChange={(e) => setDriverFilter(e.target.value)}>
                <option value="all">Wszyscy kierowcy</option>
                {drivers.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </Select>
            </Field>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {[
              { id: 'driver', l: 'Wg kierowcy' },
              { id: 'vehicle', l: 'Wg pojazdu' },
            ].map(o => (
              <button key={o.id} onClick={() => setGroupBy(o.id)} style={{
                padding: '9px 14px', border: `1px solid ${groupBy === o.id ? '#f59e0b' : '#e4e4e7'}`,
                background: groupBy === o.id ? '#fef3c7' : '#fff',
                color: groupBy === o.id ? '#854d0e' : '#52525b',
                fontWeight: groupBy === o.id ? 700 : 500, fontSize: 13, borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
              }}>{o.l}</button>
            ))}
          </div>
        </div>

        {/* Totals strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 16 }}>
          <TotalCard label="Tankowań" value={inRange.length} />
          <TotalCard label="Suma litrów" value={fmtL(totalLiters)} />
          <TotalCard label="Średnia cena / l" value={fmtPLN(avgPpl)} />
          <TotalCard label="Łączna kwota" value={fmtPLN(totalAmount)} highlight />
        </div>

        {/* Breakdown + records grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 16 }}>
          {/* Breakdown */}
          <div style={cardStyle}>
            <div style={cardHeaderStyle}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>
                Podział {groupBy === 'driver' ? 'wg kierowcy' : 'wg pojazdu'}
              </div>
            </div>
            <div style={{ padding: 12 }}>
              {breakdown.map(b => {
                const label = groupBy === 'driver'
                  ? drivers.find(d => d.id === b.id)?.name || '—'
                  : vehicles.find(v => v.id === b.id)?.plate || '—';
                const sub = groupBy === 'driver'
                  ? `${b.count} tankowań`
                  : (() => { const v = vehicles.find(x => x.id === b.id); return `${v?.brand || ''} ${v?.model || ''}`; })();
                return (
                  <div key={b.id} style={{ padding: '10px 8px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                        {groupBy === 'driver'
                          ? <Avatar name={label} size={24} />
                          : <Plate size="sm">{label}</Plate>
                        }
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: '#18181b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{groupBy === 'driver' ? label : sub}</div>
                          <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{groupBy === 'driver' ? sub : `${b.count} tankowań`}</div>
                        </div>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: '#18181b' }}>{fmtPLN(b.amount)}</div>
                    </div>
                    <div style={{ height: 6, background: '#f4f4f5', borderRadius: 3, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${(b.amount / maxAmount) * 100}%`, background: '#f59e0b', borderRadius: 3 }} />
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'flex-end', fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', marginTop: 3 }}>
                      {fmtL(b.liters)}
                    </div>
                  </div>
                );
              })}
              {breakdown.length === 0 && <div style={{ padding: 30, textAlign: 'center', color: '#a1a1aa', fontSize: 13 }}>Brak danych w wybranym okresie</div>}
            </div>
          </div>

          {/* Records list */}
          <div style={cardStyle}>
            <div style={cardHeaderStyle}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>Rekordy ({inRange.length})</div>
              <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>
                {fmtDate(new Date(dateFrom).toISOString())} → {fmtDate(new Date(dateTo).toISOString())}
              </div>
            </div>
            <div style={{ maxHeight: 480, overflow: 'auto' }}>
              <table style={tableStyle}>
                <thead style={{ position: 'sticky', top: 0, zIndex: 1 }}>
                  <tr>
                    <SortTh label="Data"     k="datetime"   cur={sSortKey} dir={sSortDir} onSort={sToggle} />
                    <SortTh label="Kierowca" k="driverName" cur={sSortKey} dir={sSortDir} onSort={sToggle} />
                    <SortTh label="Stacja"   k="station"    cur={sSortKey} dir={sSortDir} onSort={sToggle} />
                    <SortTh label="Litry"    k="liters"     cur={sSortKey} dir={sSortDir} onSort={sToggle} align="right" />
                    <SortTh label="Kwota"    k="amount"     cur={sSortKey} dir={sSortDir} onSort={sToggle} align="right" />
                  </tr>
                </thead>
                <tbody>
                  {inRange.map((f) => {
                    const driver = drivers.find(d => d.id === f.driverId);
                    return (
                      <tr key={f.id}>
                        <td style={{ ...tdStyle, fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>{fmtDate(f.datetime)}</td>
                        <td style={tdStyle}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <Avatar name={driver?.name || '?'} size={24} />
                            <span style={{ fontSize: 13 }}>{driver?.name}</span>
                          </div>
                        </td>
                        <td style={tdStyle}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            {stationChip(f.station, { size: 18 })}
                            <span style={{ fontSize: 12 }}>{f.station}</span>
                          </div>
                        </td>
                        <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>{fmtL(f.liters)}</td>
                        <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 12 }}>{fmtPLN(f.amount)}</td>
                      </tr>
                    );
                  })}
                  {inRange.length === 0 && <tr><td colSpan={5} style={{ ...tdStyle, textAlign: 'center', padding: 40, color: '#a1a1aa' }}>Brak rekordów</td></tr>}
                </tbody>
                {inRange.length > 0 && (
                  <tfoot>
                    <tr style={{ background: '#fafaf9', position: 'sticky', bottom: 0 }}>
                      <td style={{ ...tdStyle, fontWeight: 700, fontSize: 12, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.5 }}>Suma</td>
                      <td style={tdStyle} />
                      <td style={tdStyle} />
                      <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontWeight: 800, fontSize: 13 }}>{fmtL(totalLiters)}</td>
                      <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontWeight: 800, fontSize: 13, color: '#f59e0b' }}>{fmtPLN(totalAmount)}</td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function TotalCard({ label, value, highlight }) {
  return (
    <div style={{
      ...cardStyle, padding: 18,
      background: highlight ? '#18181b' : '#fff',
      borderColor: highlight ? '#18181b' : '#e7e5e4',
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase', color: highlight ? '#a1a1aa' : '#71717a', marginBottom: 8 }}>{label}</div>
      <div style={{
        fontSize: 24, fontWeight: 800, letterSpacing: -0.8, lineHeight: 1.1,
        fontFamily: 'JetBrains Mono, monospace',
        color: highlight ? '#f59e0b' : '#18181b',
      }}>{value}</div>
    </div>
  );
}

Object.assign(window, { FuelingsTab, FuelingForm, SettlementTab, TotalCard, SumPill });


