// ── Sortowanie ─────────────────────────────────────────────────
function useSort(data, defaultKey = '', defaultDir = 'asc') {
  const [sortKey, setSortKey] = React.useState(defaultKey);
  const [sortDir, setSortDir] = React.useState(defaultDir);
  const toggleSort = (key) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir('asc'); }
  };
  const sorted = React.useMemo(() => {
    if (!sortKey) return data;
    return [...data].sort((a, b) => {
      let av = a[sortKey], bv = b[sortKey];
      if (av == null) av = ''; if (bv == null) bv = '';
      if (typeof av === 'boolean') av = av ? 1 : 0;
      if (typeof bv === 'boolean') bv = bv ? 1 : 0;
      if (typeof av === 'number' && typeof bv === 'number')
        return sortDir === 'asc' ? av - bv : bv - av;
      av = String(av).toLowerCase(); bv = String(bv).toLowerCase();
      return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av);
    });
  }, [data, sortKey, sortDir]);
  return { sorted, sortKey, sortDir, toggleSort };
}

function SortTh({ label, k, cur, dir, onSort, align = 'left', width }) {
  const active = cur === k;
  return (
    <th onClick={() => onSort(k)}
      style={{ ...thStyle, textAlign: align, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap', width }}
      onMouseEnter={(e) => { e.currentTarget.style.background = '#f1f0ee'; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = '#fafaf9'; }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        {label}
        <span style={{ color: active ? '#f59e0b' : '#d4d4d8', fontSize: 9, lineHeight: 1 }}>
          {active ? (dir === 'asc' ? '▲' : '▼') : '⇅'}
        </span>
      </span>
    </th>
  );
}

// Dashboard, Drivers, Vehicles tabs for AdminApp.

// ──────────────────────────────────────────────────────────────
// DASHBOARD
// ──────────────────────────────────────────────────────────────
function Dashboard({ drivers, vehicles, fuelings, onTab }) {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const thisMonthFuelings = fuelings.filter(f => new Date(f.datetime) >= monthStart);
  const thisMonthCost = thisMonthFuelings.reduce((s, f) => s + f.amount, 0);
  const thisMonthLiters = thisMonthFuelings.reduce((s, f) => s + f.liters, 0);

  const activeDrivers = drivers.filter(d => d.active).length;
  const activeVehicles = vehicles.filter(v => v.status === 'Aktywny').length;

  // Last 14 days of expenses for the bar chart
  const days = [];
  for (let i = 13; i >= 0; i--) {
    const d = new Date(now); d.setDate(d.getDate() - i);
    d.setHours(0, 0, 0, 0);
    const next = new Date(d); next.setDate(next.getDate() + 1);
    const total = fuelings.filter(f => {
      const ft = new Date(f.datetime);
      return ft >= d && ft < next;
    }).reduce((s, f) => s + f.amount, 0);
    days.push({ date: d, total });
  }
  const maxDay = Math.max(1, ...days.map(d => d.total));

  const recent = [...fuelings].sort((a, b) => new Date(b.datetime) - new Date(a.datetime)).slice(0, 6);

  return (
    <>
      <PageHeader
        title="Dashboard"
        subtitle={`Podsumowanie floty • ${fmtDate(now.toISOString())}`}
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        {/* KPI grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
          <KPICard label="Kierowcy" value={drivers.length} sub={`${activeDrivers} aktywnych`} icon="drivers" onClick={() => onTab('drivers')} />
          <KPICard label="Pojazdy" value={vehicles.length} sub={`${activeVehicles} aktywnych`} icon="vehicles" onClick={() => onTab('vehicles')} />
          <KPICard label="Tankowania (miesiąc)" value={thisMonthFuelings.length} sub={`${fmtL(thisMonthLiters)}`} icon="fuel" onClick={() => onTab('fuelings')} />
          <KPICard label="Wydatki (miesiąc)" value={fmtPLN(thisMonthCost)} sub={fmtDate(new Date().toISOString())} icon="settle" highlight onClick={() => onTab('settlement')} />
        </div>

        {/* Chart + recent grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.3fr', gap: 16, alignItems: 'stretch' }}>
          {/* Bar chart */}
          <div style={cardStyle}>
            <div style={cardHeaderStyle}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>Wydatki na paliwo</div>
                <div style={{ fontSize: 12, color: '#71717a', marginTop: 2 }}>Ostatnie 14 dni</div>
              </div>
              <div style={{ display: 'flex', gap: 12, fontSize: 12, fontFamily: 'JetBrains Mono, monospace' }}>
                <div><span style={{ color: '#71717a' }}>SUMA</span> <b>{fmtPLN(days.reduce((s, d) => s + d.total, 0))}</b></div>
              </div>
            </div>
            <div style={{ padding: '24px 24px 20px', height: 260, display: 'flex', alignItems: 'flex-end', gap: 4 }}>
              {days.map((d, i) => {
                const h = (d.total / maxDay) * 100;
                const isToday = i === days.length - 1;
                return (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%', justifyContent: 'flex-end' }}>
                    <div style={{
                      width: '100%', minHeight: d.total > 0 ? 4 : 0, height: `${h}%`,
                      background: isToday ? '#f59e0b' : (d.total > 0 ? '#18181b' : '#e7e5e4'),
                      borderRadius: '2px 2px 0 0',
                      transition: 'height .3s',
                    }} title={fmtPLN(d.total)} />
                    <div style={{ fontSize: 10, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace' }}>
                      {String(d.date.getDate()).padStart(2, '0')}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Recent fuelings */}
          <div style={cardStyle}>
            <div style={cardHeaderStyle}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>Ostatnie tankowania</div>
                <div style={{ fontSize: 12, color: '#71717a', marginTop: 2 }}>6 najnowszych rekordów</div>
              </div>
              <button onClick={() => onTab('fuelings')} style={{ ...btnGhostStyle, fontSize: 12, color: '#f59e0b' }}>
                Wszystkie <Icon name="chevRight" size={14} />
              </button>
            </div>
            <div>
              {recent.map((f, i) => {
                const driver = drivers.find(d => d.id === f.driverId);
                const vehicle = vehicles.find(v => v.id === f.vehicleId);
                return (
                  <div key={f.id} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '12px 20px',
                    borderTop: i === 0 ? 'none' : '1px solid #f4f4f5',
                  }}>
                    {stationChip(f.station, { size: 28 })}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: '#18181b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {driver?.name || '—'}
                      </div>
                      <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>
                        {vehicle?.plate} • {fmtDateTime(f.datetime)}
                      </div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b', fontFamily: 'JetBrains Mono, monospace' }}>{fmtPLN(f.amount)}</div>
                      <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>{fmtL(f.liters)}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

const cardStyle = {
  background: '#fff', border: '1px solid #e7e5e4', borderRadius: 8, overflow: 'hidden',
};
const cardHeaderStyle = {
  padding: '16px 20px', borderBottom: '1px solid #f4f4f5',
  display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
};

function KPICard({ label, value, sub, icon, highlight, onClick }) {
  return (
    <button onClick={onClick} style={{
      ...cardStyle,
      padding: 20, textAlign: 'left', cursor: 'pointer',
      fontFamily: 'inherit', border: highlight ? '1px solid #18181b' : '1px solid #e7e5e4',
      background: highlight ? '#18181b' : '#fff',
      color: highlight ? '#fafaf9' : '#18181b',
      transition: 'transform .12s, box-shadow .12s',
    }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.06)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: highlight ? '#a1a1aa' : '#71717a' }}>{label}</span>
        <span style={{ color: highlight ? '#f59e0b' : '#a1a1aa' }}><Icon name={icon} size={18} /></span>
      </div>
      <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: -1.2, lineHeight: 1, fontFamily: 'JetBrains Mono, monospace' }}>{value}</div>
      <div style={{ fontSize: 12, color: highlight ? '#a1a1aa' : '#71717a', marginTop: 8 }}>{sub}</div>
    </button>
  );
}

// ──────────────────────────────────────────────────────────────
// DRIVERS TAB
// ──────────────────────────────────────────────────────────────
function DriversTab({ drivers, vehicles, ops }) {
  const [search, setSearch] = React.useState('');
  const [edit, setEdit] = React.useState(null); // null | 'new' | id
  const [confirmDel, setConfirmDel] = React.useState(null);

  const filtered = drivers.filter(d => d.name.toLowerCase().includes(search.toLowerCase()) || d.login.toLowerCase().includes(search.toLowerCase()));
  const { sorted: sortedDrivers, sortKey: dSortKey, sortDir: dSortDir, toggleSort: dToggle } = useSort(filtered, 'name');

  return (
    <>
      <PageHeader
        title="Kierowcy"
        subtitle={`${drivers.length} kierowców w systemie`}
        action={<Btn icon="plus" onClick={() => setEdit('new')}>Dodaj kierowcę</Btn>}
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        <div style={cardStyle}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ position: 'relative', flex: 1, maxWidth: 320 }}>
              <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 po imieniu lub loginie..." style={{ paddingLeft: 34 }} />
            </div>
            <div style={{ marginLeft: 'auto', fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>
              {filtered.length} z {drivers.length}
            </div>
          </div>
          <table style={tableStyle}>
            <thead>
              <tr>
                <SortTh label="ID"      k="id"     cur={dSortKey} dir={dSortDir} onSort={dToggle} width={50} />
                <SortTh label="Kierowca" k="name"   cur={dSortKey} dir={dSortDir} onSort={dToggle} />
                <SortTh label="Login"    k="login"  cur={dSortKey} dir={dSortDir} onSort={dToggle} />
                <th style={thStyle}>Pojazd</th>
                <SortTh label="Status"   k="active" cur={dSortKey} dir={dSortDir} onSort={dToggle} />
                <th style={{ ...thStyle, textAlign: 'right' }}>Akcje</th>
              </tr>
            </thead>
            <tbody>
              {sortedDrivers.map((d) => {
                const vehicle = vehicles.find(v => v.driverId === d.id);
                return (
                  <tr key={d.id} style={trStyle}>
                    <td style={{ ...tdStyle, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace', width: 50 }}>#{d.id.toString().padStart(3, '0')}</td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <Avatar name={d.name} size={32} />
                        <span style={{ fontWeight: 600 }}>{d.name}</span>
                      </div>
                    </td>
                    <td style={{ ...tdStyle, fontFamily: 'JetBrains Mono, monospace', fontSize: 13 }}>{d.login}</td>
                    <td style={tdStyle}>
                      {vehicle ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <Plate size="sm">{vehicle.plate}</Plate>
                          <span style={{ fontSize: 12, color: '#71717a' }}>{vehicle.brand} {vehicle.model}</span>
                        </div>
                      ) : <span style={{ color: '#a1a1aa', fontSize: 13, fontStyle: 'italic' }}>Brak przypisania</span>}
                    </td>
                    <td style={tdStyle}><ActivePill active={d.active} /></td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      <div style={{ display: 'inline-flex', gap: 4 }}>
                        <Btn variant="ghost" icon="edit" onClick={() => setEdit(d.id)}>Edytuj</Btn>
                        <Btn variant="ghost" icon="trash" onClick={() => setConfirmDel(d.id)} style={{ color: '#dc2626' }}>Usuń</Btn>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr><td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Brak wyników</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {edit !== null && (
        <DriverForm
          driver={edit === 'new' ? null : drivers.find(d => d.id === edit)}
          onClose={() => setEdit(null)}
          onSave={(d) => { if (edit === 'new') ops.addDriver(d); else ops.updateDriver(edit, d); setEdit(null); }}
        />
      )}
      {confirmDel !== null && (
        <ConfirmDelete
          title="Usunąć kierowcę?"
          desc={`Kierowca „${drivers.find(d => d.id === confirmDel)?.name}” zostanie usunięty. Przypisane pojazdy zostaną zwolnione.`}
          onCancel={() => setConfirmDel(null)}
          onConfirm={() => { ops.deleteDriver(confirmDel); setConfirmDel(null); }}
        />
      )}
    </>
  );
}

function DriverForm({ driver, onClose, onSave }) {
  const [name, setName] = React.useState(driver?.name || '');
  const [login, setLogin] = React.useState(driver?.login || '');
  const [pwd, setPwd] = React.useState(driver?.password || '');
  const [active, setActive] = React.useState(driver?.active ?? true);

  const submit = (e) => { e.preventDefault(); if (!name) return; onSave({ name, login, password: pwd, active }); };

  return (
    <Modal
      open
      onClose={onClose}
      title={driver ? 'Edytuj kierowcę' : 'Nowy kierowca'}
      subtitle={driver ? `ID #${driver.id.toString().padStart(3, '0')}` : 'Wypełnij dane nowego kierowcy'}
      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 }}>
        <Field label="Imię i nazwisko" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="np. Jan Kowalski" />
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Login" required>
            <Input value={login} onChange={(e) => setLogin(e.target.value)} placeholder="jkowalski" />
          </Field>
          <Field label="Hasło" hint="Min. 8 znaków">
            <Input type="text" value={pwd} onChange={(e) => setPwd(e.target.value)} placeholder="••••••••" />
          </Field>
        </div>
        <Field label="Status">
          <div style={{ display: 'flex', gap: 8 }}>
            {[{ v: true, l: 'Aktywny' }, { v: false, l: 'Nieaktywny' }].map((o) => (
              <button key={String(o.v)} type="button" onClick={() => setActive(o.v)} style={{
                flex: 1, padding: '10px 12px', border: `1px solid ${active === o.v ? '#f59e0b' : '#e4e4e7'}`,
                background: active === o.v ? '#fef3c7' : '#fff',
                color: active === o.v ? '#854d0e' : '#52525b',
                fontWeight: active === o.v ? 700 : 500, fontSize: 13, borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
              }}>{o.l}</button>
            ))}
          </div>
        </Field>
      </form>
    </Modal>
  );
}

// ──────────────────────────────────────────────────────────────
// VEHICLES TAB
// ──────────────────────────────────────────────────────────────
function VehiclesTab({ drivers, vehicles, fuelings = [], ops }) {
  const [search, setSearch] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [edit, setEdit] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null);

  const filtered = vehicles.filter(v => {
    const sm = (v.plate + ' ' + v.brand + ' ' + v.model).toLowerCase().includes(search.toLowerCase());
    const sf = statusFilter === 'all' || v.status === statusFilter;
    return sm && sf;
  });
  const { sorted: sortedVehicles, sortKey: vSortKey, sortDir: vSortDir, toggleSort: vToggle } = useSort(filtered, 'plate');

  // Ostatni przebieg dla każdego pojazdu (max mileage z tankowań)
  const vehicleMileage = React.useMemo(() => {
    const map = {};
    fuelings.forEach(f => {
      if (!map[f.vehicleId] || f.mileage > map[f.vehicleId]) {
        map[f.vehicleId] = f.mileage;
      }
    });
    return map;
  }, [fuelings]);

  return (
    <>
      <PageHeader
        title="Pojazdy"
        subtitle={`${vehicles.length} pojazdów we flocie`}
        action={<Btn icon="plus" onClick={() => setEdit('new')}>Dodaj pojazd</Btn>}
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        <div style={cardStyle}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ position: 'relative', flex: 1, maxWidth: 320 }}>
              <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 po tablicy, marce..." style={{ paddingLeft: 34 }} />
            </div>
            <div style={{ width: 180 }}>
              <Select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
                <option value="all">Wszystkie statusy</option>
                {VEHICLE_STATUSES.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 {vehicles.length}
            </div>
          </div>
          <table style={tableStyle}>
            <thead>
              <tr>
                <SortTh label="ID"               k="id"         cur={vSortKey} dir={vSortDir} onSort={vToggle} width={50} />
                <SortTh label="Tablica"          k="plate"      cur={vSortKey} dir={vSortDir} onSort={vToggle} />
                <SortTh label="Marka / Model"    k="brand"      cur={vSortKey} dir={vSortDir} onSort={vToggle} />
                <SortTh label="Przebieg"         k="mileage"    cur={vSortKey} dir={vSortDir} onSort={vToggle} />
                <SortTh label="Nr karty"         k="fuelCard"   cur={vSortKey} dir={vSortDir} onSort={vToggle} />
                <SortTh label="Kierowca"         k="driverName" cur={vSortKey} dir={vSortDir} onSort={vToggle} />
                <SortTh label="Status"           k="status"     cur={vSortKey} dir={vSortDir} onSort={vToggle} />
                <th style={{ ...thStyle, textAlign: 'right' }}>Akcje</th>
              </tr>
            </thead>
            <tbody>
              {sortedVehicles.map((v) => {
                const driver = drivers.find(d => d.id === v.driverId);
                return (
                  <tr key={v.id} style={trStyle}>
                    <td style={{ ...tdStyle, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace', width: 50 }}>#{v.id.toString().padStart(3, '0')}</td>
                    <td style={tdStyle}><Plate>{v.plate}</Plate></td>
                    <td style={tdStyle}>
                      <div style={{ fontWeight: 600 }}>{v.brand}</div>
                      <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{v.model}</div>
                    </td>
                    <td style={tdStyle}>
                      {vehicleMileage[v.id]
                        ? <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 13, fontWeight: 700 }}>
                            {fmtNum(vehicleMileage[v.id])} <span style={{ fontSize: 11, fontWeight: 400, color: '#71717a' }}>km</span>
                          </span>
                        : <span style={{ color: '#a1a1aa', fontSize: 13, fontStyle: 'italic' }}>—</span>}
                    </td>
                    <td style={tdStyle}>
                      {v.fuelCard
                        ? <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 13, fontWeight: 600, background: '#f0fdf4', color: '#166534', padding: '3px 8px', borderRadius: 4, border: '1px solid #bbf7d0' }}>{v.fuelCard}</span>
                        : <span style={{ color: '#a1a1aa', fontSize: 13, fontStyle: 'italic' }}>—</span>}
                    </td>
                    <td style={tdStyle}>
                      {driver ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <Avatar name={driver.name} size={26} />
                          <span style={{ fontSize: 13 }}>{driver.name}</span>
                        </div>
                      ) : <span style={{ color: '#a1a1aa', fontSize: 13, fontStyle: 'italic' }}>—</span>}
                    </td>
                    <td style={tdStyle}><StatusPill status={v.status} /></td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      <div style={{ display: 'inline-flex', gap: 4 }}>
                        <Btn variant="ghost" icon="edit" onClick={() => setEdit(v.id)}>Edytuj</Btn>
                        <Btn variant="ghost" icon="trash" onClick={() => setConfirmDel(v.id)} style={{ color: '#dc2626' }}>Usuń</Btn>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr><td colSpan={6} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Brak wyników</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {edit !== null && (
        <VehicleForm
          vehicle={edit === 'new' ? null : vehicles.find(v => v.id === edit)}
          drivers={drivers}
          vehicles={vehicles}
          onClose={() => setEdit(null)}
          onSave={(v) => { if (edit === 'new') ops.addVehicle(v); else ops.updateVehicle(edit, v); setEdit(null); }}
        />
      )}
      {confirmDel !== null && (
        <ConfirmDelete
          title="Usunąć pojazd?"
          desc={`Pojazd „${vehicles.find(v => v.id === confirmDel)?.plate}” zostanie usunięty z floty.`}
          onCancel={() => setConfirmDel(null)}
          onConfirm={() => { ops.deleteVehicle(confirmDel); setConfirmDel(null); }}
        />
      )}
    </>
  );
}

function VehicleForm({ vehicle, drivers, vehicles, onClose, onSave }) {
  const [brand, setBrand] = React.useState(vehicle?.brand || 'Toyota');
  const [model, setModel] = React.useState(vehicle?.model || 'PROACE');
  const [plate, setPlate] = React.useState(vehicle?.plate || '');
  const [driverId, setDriverId] = React.useState(vehicle?.driverId ?? '');
  const [fuelCard, setFuelCard] = React.useState(vehicle?.fuelCard || '');
  const [status, setStatus] = React.useState(vehicle?.status || 'Aktywny');

  // drivers that don't already have a different vehicle assigned
  const availableDrivers = drivers.filter(d => {
    const v = vehicles.find(x => x.driverId === d.id);
    return !v || v.id === vehicle?.id;
  });

  const submit = (e) => { e.preventDefault(); if (!plate) return; onSave({ brand, model, plate: plate.toUpperCase(), fuelCard: fuelCard.trim() || null, driverId: driverId === '' ? null : Number(driverId), status }); };

  return (
    <Modal
      open
      onClose={onClose}
      title={vehicle ? 'Edytuj pojazd' : 'Nowy pojazd'}
      subtitle={vehicle ? `ID #${vehicle.id.toString().padStart(3, '0')}` : 'Wprowadź dane pojazdu'}
      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="Marka" required>
            <Input value={brand} onChange={(e) => setBrand(e.target.value)} placeholder="Toyota" />
          </Field>
          <Field label="Model" required>
            <Input value={model} onChange={(e) => setModel(e.target.value)} placeholder="PROACE" />
          </Field>
        </div>
        <Field label="Tablica rejestracyjna" required>
          <Input value={plate} onChange={(e) => setPlate(e.target.value.toUpperCase())} placeholder="WX 12345"
            style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: 1 }} />
        </Field>
        <Field label="Nr karty paliwowej" hint="Opcjonalnie — numer karty flotowej lub paliwowej">
          <Input value={fuelCard} onChange={(e) => setFuelCard(e.target.value.toUpperCase())}
            placeholder="np. 1234 5678 9012"
            style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: 1 }} />
        </Field>
        <Field label="Przypisany kierowca" hint="Pojazd bez kierowcy zachowa status „Wolny”">
          <Select value={driverId} onChange={(e) => setDriverId(e.target.value)}>
            <option value="">— Brak przypisania —</option>
            {availableDrivers.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
          </Select>
        </Field>
        <Field label="Status">
          <Select value={status} onChange={(e) => setStatus(e.target.value)}>
            {VEHICLE_STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
          </Select>
        </Field>
      </form>
    </Modal>
  );
}

// ──────────────────────────────────────────────────────────────
// SHARED — table, confirm delete
// ──────────────────────────────────────────────────────────────
const tableStyle = { width: '100%', borderCollapse: 'collapse', fontSize: 14 };
const thStyle = {
  padding: '11px 16px', textAlign: 'left',
  background: '#fafaf9', borderBottom: '1px solid #e7e5e4',
  fontSize: 11, fontWeight: 700, color: '#71717a',
  textTransform: 'uppercase', letterSpacing: 0.8,
};
const tdStyle = { padding: '14px 16px', borderTop: '1px solid #f4f4f5', verticalAlign: 'middle' };
const trStyle = { transition: 'background .1s' };

function ConfirmDelete({ title, desc, onCancel, onConfirm }) {
  return (
    <Modal
      open
      onClose={onCancel}
      title={title}
      width={420}
      footer={
        <>
          <Btn variant="secondary" onClick={onCancel}>Anuluj</Btn>
          <Btn variant="danger" icon="trash" onClick={onConfirm}>Usuń</Btn>
        </>
      }
    >
      <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
        <div style={{
          width: 40, height: 40, borderRadius: '50%', background: '#fee2e2', color: '#dc2626',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name="trash" size={20} />
        </div>
        <p style={{ margin: 0, fontSize: 14, color: '#3f3f46', lineHeight: 1.5 }}>{desc}</p>
      </div>
    </Modal>
  );
}

Object.assign(window, {
  Dashboard, KPICard, cardStyle, cardHeaderStyle,
  DriversTab, DriverForm, VehiclesTab, VehicleForm,
  ConfirmDelete, tableStyle, thStyle, tdStyle, trStyle,
  useSort, SortTh,
});


