// DriverApp — aplikacja mobilna kierowcy z prawdziwym API.

// ── Główny komponent ────────────────────────────────────────────
function DriverApp({ width, height }) {
  const [user,     setUser]     = React.useState(null);
  const [vehicle,  setVehicle]  = React.useState(null);
  const [checking, setChecking] = React.useState(true);

  React.useEffect(() => {
    if (api.isLoggedIn()) {
      api.me()
        .then(u => { if (u.role === 'kierowca') { setUser(u); setVehicle(u.vehicle); } else api.logout(); })
        .catch(() => api.logout())
        .finally(() => setChecking(false));
    } else {
      setChecking(false);
    }
  }, []);

  if (checking) return (
    <div style={{ width, height, background: '#0c0a09', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ color: '#f59e0b', fontSize: 13, fontFamily: 'JetBrains Mono, monospace' }}>Ładowanie…</div>
    </div>
  );

  if (!user) return (
    <DriverLogin width={width} height={height}
      onLogin={(u, v) => { setUser(u); setVehicle(v); }} />
  );

  return (
    <DriverMain width={width} height={height} user={user} vehicle={vehicle}
      onLogout={() => { api.logout(); setUser(null); setVehicle(null); }} />
  );
}

// ── Główny widok po zalogowaniu ─────────────────────────────────
function DriverMain({ width, height, user, vehicle, onLogout }) {
  const [fuelings,  setFuelings]  = React.useState([]);
  const [view,      setView]      = React.useState('list'); // list | add | report | vehicle
  const [toast,     setToast]     = React.useState(null);
  const [loading,   setLoading]   = React.useState(true);
  const [curVehicle, setCurVehicle] = React.useState(vehicle);
  const [magazynVehicles, setMagazynVehicles] = React.useState([]);

  // Odśwież dane pojazdu
  const loadVehicle = React.useCallback(async () => {
    try {
      const me = await api.me();
      setCurVehicle(me.vehicle);
    } catch (e) {}
  }, []);

  // Załaduj pojazdy z magazynu
  const loadMagazyn = React.useCallback(async () => {
    try {
      const vehicles = await api.getVehicles();
      setMagazynVehicles(vehicles.filter(v => v.status === 'Magazyn' && !v.driverId));
    } catch (e) {}
  }, []);

  const loadFuelings = React.useCallback(async () => {
    try {
      const data = await api.getFuelings({ limit: 200 });
      setFuelings(data.sort((a, b) => new Date(b.datetime) - new Date(a.datetime)));
    } catch (err) {
      if (err.status === 401) { api.logout(); window.location.reload(); }
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { loadFuelings(); }, [loadFuelings]);

  const handleMagazyn = async () => {
    try {
      await api.vehicleMagazyn(curVehicle.id);
      setCurVehicle(null);
      setToast('Pojazd oddany do magazynu');
      setTimeout(() => setToast(null), 2500);
      setView('list');
    } catch (e) { alert(e.message); }
  };

  const handleClaim = async (vehicleId) => {
    try {
      await api.vehicleClaim(vehicleId);
      await loadVehicle();
      setToast('Pojazd przypisany pomyślnie');
      setTimeout(() => setToast(null), 2500);
      setView('list');
    } catch (e) { alert(e.message); }
  };

  const addFueling = async (f) => {
    try {
      await api.createFueling(f);
      await loadFuelings();
      setView('list');
      setToast('Tankowanie zapisane ✓');
      setTimeout(() => setToast(null), 2500);
    } catch (err) {
      alert('Błąd: ' + err.message);
    }
  };

  return (
    <div style={{ width, height, position: 'relative', overflow: 'hidden', background: '#0c0a09', fontFamily: '"Manrope", system-ui, sans-serif' }}>
      <PhoneStatusBar />

      {view === 'list' && (
        <DriverListView
          driver={user}
          vehicle={curVehicle}
          fuelings={fuelings}
          loading={loading}
          onAdd={() => setView('add')}
          onLogout={onLogout}
          onReport={() => setView('report')}
          onVehicleClick={() => { loadMagazyn(); setView('vehicle'); }}
        />
      )}
      {view === 'add' && (
        <DriverAddView
          driver={user}
          vehicle={curVehicle}
          onClose={() => setView('list')}
          onSave={addFueling}
        />
      )}
      {view === 'report' && (
        <DriverReportView
          driver={user}
          vehicle={curVehicle}
          onClose={() => setView('list')}
          onSave={async (data) => {
            await api.createReport(data);
            setView('list');
            setToast('Zgłoszenie wysłane ✓');
            setTimeout(() => setToast(null), 2500);
          }}
        />
      )}
      {view === 'vehicle' && (
        <DriverVehicleView
          driver={user}
          vehicle={curVehicle}
          magazynVehicles={magazynVehicles}
          onLoad={loadMagazyn}
          onMagazyn={handleMagazyn}
          onClaim={handleClaim}
          onClose={() => setView('list')}
        />
      )}

      <PhoneNavBar />

      {toast && (
        <div style={{ position: 'absolute', bottom: 56, left: 16, right: 16, background: '#166534', color: '#fff', padding: '14px 16px', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.35)', fontSize: 14, fontWeight: 600, zIndex: 20, animation: 'tf-slide-up .25s ease-out' }}>
          <div style={{ width: 28, height: 28, borderRadius: 14, background: '#22c55e', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="check" size={16} color="#fff" />
          </div>
          {toast}
        </div>
      )}
    </div>
  );
}

// ── Status bar ──────────────────────────────────────────────────
function PhoneStatusBar() {
  const [time, setTime] = React.useState(() => {
    const d = new Date(); const p = x => String(x).padStart(2,'0');
    return `${p(d.getHours())}:${p(d.getMinutes())}`;
  });
  React.useEffect(() => {
    const t = setInterval(() => {
      const d = new Date(); const p = x => String(x).padStart(2,'0');
      setTime(`${p(d.getHours())}:${p(d.getMinutes())}`);
    }, 10000);
    return () => clearInterval(t);
  }, []);
  return (
    <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 32, background: '#0c0a09', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 20px', zIndex: 10 }}>
      <span style={{ fontSize: 13, fontWeight: 700, color: '#fafaf9', fontFamily: 'JetBrains Mono, monospace' }}>{time}</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        {[0.4,0.6,0.8,1].map((o,i) => <div key={i} style={{ width: 3, height: 6+i*3, background: '#fafaf9', borderRadius: 1, opacity: o }} />)}
        <div style={{ marginLeft: 3, width: 20, height: 10, border: '1.5px solid #fafaf9', borderRadius: 2, position: 'relative', marginTop: 1 }}>
          <div style={{ position: 'absolute', top: 1, left: 1, bottom: 1, width: '60%', background: '#4ade80', borderRadius: 1 }} />
          <div style={{ position: 'absolute', right: -4, top: 2, bottom: 2, width: 2.5, background: '#fafaf9', borderRadius: 1 }} />
        </div>
      </div>
    </div>
  );
}

function PhoneNavBar({ dark = true }) {
  return (
    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', background: dark ? '#0c0a09' : '#fff', zIndex: 10 }}>
      <div style={{ width: 108, height: 4, borderRadius: 2, background: dark ? '#fff' : '#18181b', opacity: 0.5 }} />
    </div>
  );
}

// ── Login ───────────────────────────────────────────────────────
function DriverLogin({ width, height, onLogin }) {
  const [login,   setLogin]   = React.useState('');
  const [pwd,     setPwd]     = React.useState('');
  const [showPwd, setShowPwd] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [errMsg,  setErrMsg]  = React.useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!login || !pwd) { setErrMsg('Wpisz login i hasło'); return; }
    setLoading(true); setErrMsg('');
    try {
      const res = await api.login(login, pwd);
      if (res.user.role !== 'kierowca') { setErrMsg('Administratorzy logują się przez panel webowy'); return; }
      api.setToken(res.token);
      const me = await api.me();
      onLogin(me, me.vehicle);
    } catch (err) {
      setErrMsg(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ width, height, position: 'relative', overflow: 'hidden', background: '#0c0a09', color: '#fafaf9', fontFamily: '"Manrope", system-ui, sans-serif', display: 'flex', flexDirection: 'column' }}>
      <PhoneStatusBar />
      <div style={{ flex: 1, padding: '32px 28px 24px', display: 'flex', flexDirection: 'column', marginTop: 32 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 48 }}>
          <BrandMark size={36} />
          <div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 14, fontWeight: 700, letterSpacing: 2.5 }}>TANKFOOD</div>
            <div style={{ fontSize: 10, color: '#71717a', letterSpacing: 1, marginTop: 1, textTransform: 'uppercase' }}>Aplikacja kierowcy</div>
          </div>
        </div>
        <div style={{ marginBottom: 36 }}>
          <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: -1, lineHeight: 1.1 }}>Dzień dobry.<br/><span style={{ color: '#f59e0b' }}>Zaloguj się.</span></div>
          <div style={{ fontSize: 14, color: '#a1a1aa', marginTop: 12, lineHeight: 1.5 }}>Wprowadź dane otrzymane od administratora floty.</div>
        </div>

        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18, flex: 1 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 8 }}>Login</div>
            <div style={{ position: 'relative' }}>
              <div style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: '#71717a' }}><Icon name="user" size={18} /></div>
              <input value={login} onChange={(e) => setLogin(e.target.value)} autoComplete="username" style={{ width: '100%', padding: '14px 14px 14px 44px', background: '#18181b', border: '1px solid #27272a', borderRadius: 10, color: '#fafaf9', fontSize: 16, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} />
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 8 }}>Hasło</div>
            <div style={{ position: 'relative' }}>
              <div style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: '#71717a' }}><Icon name="lock" size={18} /></div>
              <input type={showPwd ? 'text' : 'password'} value={pwd} onChange={(e) => setPwd(e.target.value)} autoComplete="current-password" style={{ width: '100%', padding: '14px 44px 14px 44px', background: '#18181b', border: '1px solid #27272a', borderRadius: 10, color: '#fafaf9', fontSize: 16, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} />
              <button type="button" onClick={() => setShowPwd(!showPwd)} style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', color: '#71717a', cursor: 'pointer', padding: 6 }}><Icon name="eye" size={18} /></button>
            </div>
          </div>

          {errMsg && <div style={{ padding: '10px 14px', background: 'rgba(239,68,68,0.15)', border: '1px solid rgba(239,68,68,0.3)', borderRadius: 8, fontSize: 13, color: '#fca5a5' }}>{errMsg}</div>}

          <div style={{ flex: 1 }} />
          <button type="submit" disabled={loading} style={{ padding: '16px', background: loading ? '#78716c' : '#f59e0b', color: '#0c0a09', border: 'none', borderRadius: 12, cursor: loading ? 'not-allowed' : 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 16, letterSpacing: -0.2, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            {loading ? 'Logowanie…' : <><span>Zaloguj się</span><Icon name="arrowLeft" size={18} style={{ transform: 'rotate(180deg)' }} color="#0c0a09" strokeWidth={2.2} /></>}
          </button>
          <div style={{ fontSize: 12, color: '#71717a', textAlign: 'center', lineHeight: 1.5 }}>Problemy z logowaniem?<br/>Skontaktuj się z administratorem floty.</div>
        </form>
      </div>
      <PhoneNavBar />
    </div>
  );
}

// ── List view ───────────────────────────────────────────────────
function DriverListView({ driver, vehicle, fuelings, loading, onAdd, onLogout, onReport, onVehicleClick }) {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthFuelings = fuelings.filter(f => new Date(f.datetime) >= monthStart);
  const monthLiters   = monthFuelings.reduce((s, f) => s + f.liters, 0);
  const monthAmount   = monthFuelings.reduce((s, f) => s + f.amount, 0);
  const monthName     = now.toLocaleString('pl-PL', { month: 'long' });

  const grouped = {};
  fuelings.forEach(f => {
    const key = fmtDate(f.datetime);
    if (!grouped[key]) grouped[key] = [];
    grouped[key].push(f);
  });

  return (
    <div style={{ position: 'absolute', inset: 0, top: 32, bottom: 22, display: 'flex', flexDirection: 'column' }}>
      <div style={{ background: '#0c0a09', color: '#fafaf9', padding: '16px 20px 20px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Avatar name={driver.name} size={36} />
            <div>
              <div style={{ fontSize: 11, color: '#71717a', letterSpacing: 0.5, textTransform: 'uppercase' }}>Cześć,</div>
              <div style={{ fontSize: 15, fontWeight: 700 }}>{driver.name.split(' ')[0]}</div>
            </div>
          </div>
          <button onClick={onLogout} style={{ background: '#18181b', border: '1px solid #27272a', color: '#a1a1aa', padding: 8, borderRadius: 8, cursor: 'pointer' }}><Icon name="logout" size={16} /></button>
        </div>
        {vehicle ? (
          <div onClick={onVehicleClick} style={{ background: '#18181b', border: '1px solid #27272a', borderRadius: 12, padding: 14, display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer', transition: 'opacity .15s' }}
            onMouseEnter={e=>e.currentTarget.style.opacity='.8'} onMouseLeave={e=>e.currentTarget.style.opacity='1'}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: '#f59e0b', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="car" size={22} color="#0c0a09" strokeWidth={2} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, color: '#71717a', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 3 }}>Twój pojazd</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Plate>{vehicle.plate}</Plate><span style={{ fontSize: 13, fontWeight: 600 }}>{vehicle.brand} {vehicle.model}</span></div>
            </div>
          </div>
        ) : (
          <div onClick={onVehicleClick} style={{ background: '#1c1917', border: '2px dashed #44403c', borderRadius: 12, padding: 14, color: '#a8a29e', cursor: 'pointer', transition: 'border-color .15s' }}
            onMouseEnter={e=>e.currentTarget.style.borderColor='#f59e0b'} onMouseLeave={e=>e.currentTarget.style.borderColor='#44403c'}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#d4d4d8', marginBottom: 4 }}>Brak przypisanego pojazdu</div>
            <div style={{ fontSize: 12, lineHeight: 1.5 }}>Kliknij aby pobrać auto z magazynu.</div>
          </div>
        )}
        <div style={{ display: 'flex', gap: 12, marginTop: 16 }}>
          <div style={{ flex: 1, background: '#18181b', borderRadius: 10, padding: '10px 14px' }}>
            <div style={{ fontSize: 10, color: '#71717a', letterSpacing: 0.5, textTransform: 'uppercase' }}>Litry ({monthName})</div>
            <div style={{ fontSize: 17, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{fmtL(monthLiters)}</div>
          </div>
          <div style={{ flex: 1, background: '#18181b', borderRadius: 10, padding: '10px 14px' }}>
            <div style={{ fontSize: 10, color: '#71717a', letterSpacing: 0.5, textTransform: 'uppercase' }}>Kwota ({monthName})</div>
            <div style={{ fontSize: 17, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace', marginTop: 2, color: '#f59e0b' }}>{fmtPLN(monthAmount)}</div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', background: '#fafaf9', padding: '16px 16px 100px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, fontWeight: 700, color: '#71717a', letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 10, paddingLeft: 4 }}>
          <span>Moje tankowania</span>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', letterSpacing: 0 }}>{loading ? '…' : fuelings.length}</span>
        </div>
        {!loading && fuelings.length === 0 && (
          <div style={{ textAlign: 'center', padding: 40, color: '#a1a1aa', fontSize: 14 }}>Brak tankowań.<br/>Naciśnij + aby dodać pierwsze.</div>
        )}
        {Object.entries(grouped).map(([dateKey, items]) => (
          <div key={dateKey} style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace', padding: '6px 4px' }}>{dateKey}</div>
            <div style={{ background: '#fff', borderRadius: 12, border: '1px solid #e7e5e4', overflow: 'hidden' }}>
              {items.map((f, i) => (
                <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 14px', borderTop: i === 0 ? 'none' : '1px solid #f4f4f5' }}>
                  {stationChip(f.station, { size: 36 })}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>{f.station}</div>
                    <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>{fmtTime(f.datetime)} • {fmtL(f.liters)}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 15, fontWeight: 800, color: '#18181b', fontFamily: 'JetBrains Mono, monospace' }}>{fmtPLN(f.amount)}</div>
                    <div style={{ fontSize: 11, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>{fmtNum(f.mileage)} km</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Przycisk zgłoszenia usterki */}
      {vehicle && (
        <button onClick={onReport} style={{ position: 'absolute', bottom: 104, right: 20, width: 48, height: 48, borderRadius: 24, background: '#dc2626', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 4px 16px rgba(220,38,38,0.5)', zIndex: 5 }}>
          <span style={{ color: '#fff', fontSize: 24, fontWeight: 900, lineHeight: 1, marginTop: -2 }}>!</span>
        </button>
      )}
      {/* FAB + tankowanie */}
      {vehicle && (
        <button onClick={onAdd} style={{ position: 'absolute', bottom: 28, right: 20, width: 64, height: 64, borderRadius: 32, background: '#f59e0b', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 8px 24px rgba(245,158,11,0.45), 0 2px 6px rgba(0,0,0,0.2)', zIndex: 5 }}>
          <Icon name="plus" size={28} color="#0c0a09" strokeWidth={2.4} />
        </button>
      )}
    </div>
  );
}

// ── Add view ────────────────────────────────────────────────────
function DriverAddView({ driver, vehicle, onClose, onSave }) {
  const [station, setStation] = React.useState('MOYA');
  const [liters,  setLiters]  = React.useState('');
  const [amount,  setAmount]  = React.useState('');
  const [mileage, setMileage] = React.useState('');
  const [saving,  setSaving]  = React.useState(false);
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => { setMounted(true); }, []);

  const now = new Date();
  const canSave = vehicle && liters && amount && !saving;

  const handleSave = async () => {
    if (!canSave) return;
    setSaving(true);
    await onSave({
      driverId:  driver.id,
      vehicleId: vehicle.id,
      station,
      liters:  Number(String(liters).replace(',', '.')),
      amount:  Number(String(amount).replace(',', '.')),
      mileage: Number(mileage) || 0,
      datetime: now.toISOString(),
    });
    setSaving(false);
  };

  return (
    <div style={{ position: 'absolute', inset: 0, top: 32, bottom: 22, display: 'flex', flexDirection: 'column', background: '#fafaf9', transform: mounted ? 'translateY(0)' : 'translateY(100%)', transition: 'transform .3s cubic-bezier(.2,.7,.3,1)' }}>
      <div style={{ background: '#0c0a09', color: '#fafaf9', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 18, background: '#18181b', border: '1px solid #27272a', color: '#fafaf9', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}><Icon name="arrowLeft" size={18} /></button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase' }}>Nowy rekord</div>
          <div style={{ fontSize: 17, fontWeight: 700 }}>Nowe tankowanie</div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '20px 20px 120px' }}>
        <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
          {vehicle && (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 10px', borderRadius: 999, background: '#fff', border: '1px solid #e7e5e4' }}>
              <Icon name="car" size={14} color="#71717a" /><Plate size="sm">{vehicle.plate}</Plate>
            </div>
          )}
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 999, background: '#fff', border: '1px solid #e7e5e4', fontSize: 12, color: '#52525b', fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>
            <Icon name="calendar" size={13} color="#71717a" />{fmtDate(now.toISOString())} • {fmtTime(now.toISOString())}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 22 }}>
          <BigNumField label="Kwota" unit="zł" value={amount} onChange={setAmount} placeholder="0,00" accent />
          <BigNumField label="Litry" unit="l"  value={liters} onChange={setLiters} placeholder="0,00" />
        </div>

        <div style={{ marginBottom: 22 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="speedometer" size={13} color="#71717a" />Przebieg pojazdu</div>
          <div style={{ position: 'relative' }}>
            <input type="number" inputMode="numeric" value={mileage} onChange={(e) => setMileage(e.target.value)} placeholder="np. 124530" style={{ width: '100%', padding: '16px 56px 16px 16px', background: '#fff', border: '1px solid #e7e5e4', borderRadius: 12, fontFamily: 'JetBrains Mono, monospace', fontSize: 17, fontWeight: 700, color: '#18181b', outline: 'none', boxSizing: 'border-box' }} />
            <div style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)', fontSize: 13, fontWeight: 700, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>km</div>
          </div>
        </div>

        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10 }}>Stacja paliw</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {STATIONS.map(s => {
              const selected = station === s;
              return (
                <button key={s} onClick={() => setStation(s)} style={{ padding: '12px 4px', background: selected ? '#0c0a09' : '#fff', border: `1.5px solid ${selected ? '#f59e0b' : '#e7e5e4'}`, borderRadius: 12, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, fontFamily: 'inherit', transition: 'all .12s' }}>
                  {stationChip(s, { size: 28 })}
                  <span style={{ fontSize: 11, fontWeight: 700, color: selected ? '#f59e0b' : '#3f3f46', letterSpacing: 0.4 }}>{s}</span>
                </button>
              );
            })}
          </div>
        </div>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'linear-gradient(to top, #fafaf9 70%, rgba(250,250,249,0))', padding: '24px 20px 20px' }}>
        <button onClick={handleSave} disabled={!canSave} style={{ width: '100%', padding: '17px', background: canSave ? '#f59e0b' : '#d4d4d8', color: canSave ? '#0c0a09' : '#71717a', border: 'none', borderRadius: 14, cursor: canSave ? 'pointer' : 'not-allowed', fontFamily: 'inherit', fontWeight: 800, fontSize: 16, letterSpacing: -0.2, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, transition: 'all .15s' }}>
          <Icon name="check" size={20} color={canSave ? '#0c0a09' : '#71717a'} strokeWidth={2.4} />
          {saving ? 'Zapisywanie…' : 'Zapisz tankowanie'}
        </button>
      </div>
    </div>
  );
}

function BigNumField({ label, unit, value, onChange, placeholder, accent }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8 }}>{label}</div>
      <div style={{ position: 'relative', background: accent ? '#0c0a09' : '#fff', border: `1.5px solid ${accent ? '#f59e0b' : '#e7e5e4'}`, borderRadius: 14, padding: '16px 14px 14px' }}>
        <input type="text" inputMode="decimal" value={value} onChange={(e) => onChange(e.target.value.replace(/[^\d.,]/g, ''))} placeholder={placeholder} style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', fontFamily: 'JetBrains Mono, monospace', fontSize: 28, fontWeight: 800, letterSpacing: -1, color: accent ? '#f59e0b' : '#18181b', padding: 0, boxSizing: 'border-box' }} />
        <div style={{ position: 'absolute', right: 14, bottom: 14, fontSize: 14, fontWeight: 700, color: '#a1a1aa', fontFamily: 'JetBrains Mono, monospace' }}>{unit}</div>
      </div>
    </div>
  );
}


// ── Widok zgłoszenia usterki ────────────────────────────────────
function DriverReportView({ driver, vehicle, onClose, onSave }) {
  const [description, setDescription] = React.useState('');
  const [photos,      setPhotos]      = React.useState([]); // { file, preview }
  const [saving,      setSaving]      = React.useState(false);
  const [mounted,     setMounted]     = React.useState(false);
  React.useEffect(() => { setMounted(true); }, []);

  const canSave = description.trim().length > 0 && !saving;

  const handlePhoto = (e) => {
    const files = Array.from(e.target.files);
    files.forEach(file => {
      const reader = new FileReader();
      reader.onload = ev => setPhotos(prev => [...prev, { file, preview: ev.target.result }]);
      reader.readAsDataURL(file);
    });
  };

  const removePhoto = (i) => setPhotos(prev => prev.filter((_, idx) => idx !== i));

  const handleSave = async () => {
    if (!canSave) return;
    setSaving(true);
    try {
      // Upload zdjęć
      const keys = [];
      for (const { file } of photos) {
        const res = await api.uploadPhoto(file);
        keys.push(res.key);
      }
      await onSave({
        driverId:  driver.id,
        vehicleId: vehicle?.id,
        type:      'usterka',
        description: description.trim(),
        photoKeys: keys,
      });
    } catch (e) { alert('Błąd: ' + e.message); setSaving(false); }
  };

  return (
    <div style={{ position: 'absolute', inset: 0, top: 32, bottom: 22, display: 'flex', flexDirection: 'column', background: '#fafaf9', transform: mounted ? 'translateY(0)' : 'translateY(100%)', transition: 'transform .3s cubic-bezier(.2,.7,.3,1)' }}>
      {/* Top bar */}
      <div style={{ background: '#dc2626', color: '#fff', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 18, background: 'rgba(255,255,255,0.15)', border: 'none', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}>
          <Icon name="arrowLeft" size={18} />
        </button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, opacity: 0.8, letterSpacing: 1, textTransform: 'uppercase' }}>Nowe zgłoszenie</div>
          <div style={{ fontSize: 17, fontWeight: 700 }}>Zgłoszenie usterki</div>
        </div>
        <span style={{ fontSize: 28, fontWeight: 900 }}>!</span>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '20px 20px 120px' }}>
        {/* Pojazd */}
        {vehicle && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', background: '#18181b', borderRadius: 10, marginBottom: 20 }}>
            <Icon name="car" size={16} color="#f59e0b" />
            <Plate size="sm">{vehicle.plate}</Plate>
            <span style={{ fontSize: 13, color: '#d4d4d8', fontWeight: 600 }}>{vehicle.brand} {vehicle.model}</span>
          </div>
        )}

        {/* Opis */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8 }}>Opis usterki *</div>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            placeholder="Opisz problem jak najdokładniej..."
            rows={5}
            style={{ width: '100%', padding: '14px', background: '#fff', border: '1px solid #e7e5e4', borderRadius: 12, fontFamily: 'inherit', fontSize: 14, color: '#18181b', resize: 'none', outline: 'none', boxSizing: 'border-box', lineHeight: 1.5 }}
          />
        </div>

        {/* Zdjęcia */}
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8 }}>Zdjęcia (opcjonalnie)</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {photos.map((p, i) => (
              <div key={i} style={{ position: 'relative', aspectRatio: '1' }}>
                <img src={p.preview} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 10, border: '1px solid #e7e5e4' }} />
                <button onClick={() => removePhoto(i)} style={{ position: 'absolute', top: 4, right: 4, width: 22, height: 22, borderRadius: 11, background: '#dc2626', border: 'none', color: '#fff', fontSize: 14, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>×</button>
              </div>
            ))}
            <label style={{ aspectRatio: '1', border: '2px dashed #e7e5e4', borderRadius: 10, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4, cursor: 'pointer', background: '#fafaf9' }}>
              <Icon name="plus" size={22} color="#a1a1aa" />
              <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 600 }}>Dodaj</span>
              <input type="file" accept="image/*" multiple onChange={handlePhoto} style={{ display: 'none' }} />
            </label>
          </div>
        </div>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'linear-gradient(to top, #fafaf9 70%, transparent)', padding: '24px 20px 20px' }}>
        <button onClick={handleSave} disabled={!canSave} style={{ width: '100%', padding: '17px', background: canSave ? '#dc2626' : '#d4d4d8', color: '#fff', border: 'none', borderRadius: 14, cursor: canSave ? 'pointer' : 'not-allowed', fontFamily: 'inherit', fontWeight: 800, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
          <Icon name="check" size={20} color="#fff" strokeWidth={2.4} />
          {saving ? 'Wysyłanie…' : 'Wyślij zgłoszenie'}
        </button>
      </div>
    </div>
  );
}

// ── Widok zarządzania pojazdem ──────────────────────────────────
function DriverVehicleView({ driver, vehicle, magazynVehicles, onLoad, onMagazyn, onClaim, onClose }) {
  const [loading, setLoading] = React.useState(false);
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => { setMounted(true); onLoad(); }, []);

  const doMagazyn = async () => {
    if (!confirm(`Oddać ${vehicle.plate} do magazynu? Stracisz przypisanie do tego pojazdu.`)) return;
    setLoading(true);
    await onMagazyn();
    setLoading(false);
  };

  const doClaim = async (v) => {
    setLoading(true);
    await onClaim(v.id);
    setLoading(false);
  };

  return (
    <div style={{ position: 'absolute', inset: 0, top: 32, bottom: 22, display: 'flex', flexDirection: 'column', background: '#0c0a09', transform: mounted ? 'translateY(0)' : 'translateY(100%)', transition: 'transform .3s cubic-bezier(.2,.7,.3,1)' }}>
      {/* Top bar */}
      <div style={{ background: '#0c0a09', color: '#fafaf9', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid #1c1917' }}>
        <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 18, background: '#18181b', border: '1px solid #27272a', color: '#fafaf9', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}>
          <Icon name="arrowLeft" size={18} />
        </button>
        <div style={{ fontSize: 17, fontWeight: 700 }}>Zarządzaj pojazdem</div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
        {vehicle ? (
          <>
            {/* Aktualny pojazd */}
            <div style={{ background: '#18181b', border: '1px solid #27272a', borderRadius: 14, padding: 16, marginBottom: 24 }}>
              <div style={{ fontSize: 11, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 10 }}>Twój aktualny pojazd</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
                <div style={{ width: 44, height: 44, borderRadius: 10, background: '#f59e0b', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="car" size={22} color="#0c0a09" strokeWidth={2} />
                </div>
                <div>
                  <Plate>{vehicle.plate}</Plate>
                  <div style={{ fontSize: 13, color: '#d4d4d8', marginTop: 4 }}>{vehicle.brand} {vehicle.model}</div>
                </div>
              </div>
              <button
                onClick={doMagazyn}
                disabled={loading}
                style={{ width: '100%', padding: '13px', background: loading ? '#374151' : '#1c1917', border: '1px solid #ea580c', borderRadius: 10, color: '#fed7aa', fontFamily: 'inherit', fontWeight: 700, fontSize: 14, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                <Icon name="arrowLeft" size={16} color="#fb923c" style={{ transform: 'rotate(180deg)' }} />
                {loading ? 'Oddawanie…' : 'Oddaj do magazynu'}
              </button>
            </div>
          </>
        ) : (
          <>
            <div style={{ textAlign: 'center', padding: '20px 0 24px', color: '#a1a1aa' }}>
              <div style={{ fontSize: 40, marginBottom: 8 }}>🚗</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: '#d4d4d8', marginBottom: 4 }}>Brak przypisanego pojazdu</div>
              <div style={{ fontSize: 13, lineHeight: 1.5 }}>Wybierz auto z magazynu</div>
            </div>
          </>
        )}

        {/* Pojazdy w magazynie */}
        {!vehicle && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 12 }}>
              Dostępne w magazynie ({magazynVehicles.length})
            </div>
            {magazynVehicles.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', color: '#52525b', fontSize: 13 }}>Brak dostępnych pojazdów w magazynie</div>
            ) : (
              magazynVehicles.map(v => (
                <button key={v.id} onClick={() => doClaim(v)} disabled={loading}
                  style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: '#18181b', border: '1px solid #27272a', borderRadius: 12, marginBottom: 8, cursor: 'pointer', fontFamily: 'inherit', transition: 'border-color .15s' }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = '#f59e0b'}
                  onMouseLeave={e => e.currentTarget.style.borderColor = '#27272a'}>
                  <div style={{ width: 40, height: 40, borderRadius: 8, background: '#27272a', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name="car" size={18} color="#a1a1aa" />
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>
                    <Plate size="sm">{v.plate}</Plate>
                    <div style={{ fontSize: 12, color: '#71717a', marginTop: 3 }}>{v.brand} {v.model}</div>
                  </div>
                  <Icon name="chevRight" size={16} color="#71717a" />
                </button>
              ))
            )}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DriverApp, DriverLogin, DriverMain, DriverListView, DriverAddView,
  DriverReportView, DriverVehicleView, BigNumField, PhoneStatusBar, PhoneNavBar });
