// AdminApp — panel administratora z prawdziwym API.

const NAV = [
  { id: 'dashboard',  label: 'Dashboard',   icon: 'dashboard' },
  { id: 'drivers',    label: 'Kierowcy',    icon: 'drivers' },
  { id: 'vehicles',   label: 'Pojazdy',     icon: 'vehicles' },
  { id: 'reports',    label: 'Zgłoszenia',  icon: 'history' },
  { id: 'fuelings',   label: 'Tankowania',  icon: 'fuel' },
  { id: 'settlement', label: 'Rozliczenie', icon: 'settle' },
];

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

  // Sprawdź token przy starcie
  React.useEffect(() => {
    if (api.isLoggedIn()) {
      api.me()
        .then(u => { if (u.role === 'admin') setUser(u); 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: 14, fontFamily: 'JetBrains Mono, monospace', letterSpacing: 1 }}>Ładowanie…</div>
    </div>
  );

  if (!user) return (
    <AdminLogin width={width} height={height} onLogin={(u) => { setUser(u); setChecking(false); }} />
  );

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

// ── Dashboard (po zalogowaniu) ──────────────────────────────────
function AdminDashboard({ width, height, user, onLogout }) {
  const [tab,      setTab]      = React.useState('dashboard');
  const [drivers,  setDrivers]  = React.useState([]);
  const [vehicles, setVehicles] = React.useState([]);
  const [fuelings, setFuelings] = React.useState([]);
  const [loading,  setLoading]  = React.useState(true);
  const [errMsg,   setErrMsg]   = React.useState(null);

  const loadData = React.useCallback(async () => {
    setLoading(true);
    try {
      const [d, v, f] = await Promise.all([
        api.getDrivers(),
        api.getVehicles(),
        api.getFuelings({ limit: 500 }),
      ]);
      setDrivers(d);
      setVehicles(v);
      setFuelings(f);
      setErrMsg(null);
    } catch (err) {
      if (err.status === 401) { api.logout(); window.location.reload(); return; }
      setErrMsg(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const ops = {
    addDriver:     async (d)    => { try { await api.createDriver(d);     await loadData(); } catch(e) { alert(e.message); } },
    updateDriver:  async (id,d) => { try { await api.updateDriver(id,d);  await loadData(); } catch(e) { alert(e.message); } },
    deleteDriver:  async (id)   => { try { await api.deleteDriver(id);    await loadData(); } catch(e) { alert(e.message); } },
    addVehicle:    async (v)    => { try { await api.createVehicle(v);    await loadData(); } catch(e) { alert(e.message); } },
    updateVehicle: async (id,v) => { try { await api.updateVehicle(id,v); await loadData(); } catch(e) { alert(e.message); } },
    deleteVehicle: async (id)   => { try { await api.deleteVehicle(id);   await loadData(); } catch(e) { alert(e.message); } },
    addFueling:    async (f)    => { try { await api.createFueling(f);    await loadData(); } catch(e) { alert(e.message); } },
    updateFueling: async (id,f) => { try { await api.updateFueling(id,f); await loadData(); } catch(e) { alert(e.message); } },
    deleteFueling: async (id)   => { try { await api.deleteFueling(id);   await loadData(); } catch(e) { alert(e.message); } },
  };

  return (
    <div style={{
      width, height, display: 'flex', overflow: 'hidden',
      background: '#fafaf9', color: '#18181b',
      fontFamily: '"Manrope", system-ui, sans-serif', fontSize: 14, lineHeight: 1.45,
    }}>
      <AdminSidebar tab={tab} onTab={setTab} user={user} onLogout={onLogout} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
        {loading && (
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: '#f59e0b', zIndex: 10,
            animation: 'tf-fade-in .2s' }} />
        )}
        {errMsg && (
          <div style={{ padding: '10px 24px', background: '#fee2e2', color: '#991b1b', fontSize: 13, borderBottom: '1px solid #fecaca' }}>
            Błąd: {errMsg} — <button onClick={loadData} style={{ background: 'none', border: 'none', color: '#991b1b', cursor: 'pointer', textDecoration: 'underline', fontFamily: 'inherit' }}>Spróbuj ponownie</button>
          </div>
        )}
        {tab === 'dashboard'  && <Dashboard  drivers={drivers} vehicles={vehicles} fuelings={fuelings} onTab={setTab} />}
        {tab === 'drivers'    && <DriversTab    drivers={drivers} vehicles={vehicles} ops={ops} />}
        {tab === 'vehicles'   && <VehiclesTab   drivers={drivers} vehicles={vehicles} fuelings={fuelings} ops={ops} />}
        {tab === 'reports'    && <ReportsTab />}
        {tab === 'fuelings'   && <FuelingsTab   drivers={drivers} vehicles={vehicles} fuelings={fuelings} ops={ops} />}
        {tab === 'settlement' && <SettlementTab drivers={drivers} vehicles={vehicles} fuelings={fuelings} />}
      </main>
    </div>
  );
}

// ── Login ───────────────────────────────────────────────────────
function AdminLogin({ 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 !== 'admin') { setErrMsg('To konto nie ma uprawnień administratora'); return; }
      api.setToken(res.token);
      onLogin(res.user);
    } catch (err) {
      setErrMsg(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ width, height, background: '#0c0a09', color: '#fafaf9', fontFamily: '"Manrope", system-ui, sans-serif', display: 'flex', overflow: 'hidden', position: 'relative' }}>
      {/* Left brand panel */}
      <div style={{ flex: 1, padding: 56, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative', zIndex: 2 }}>
          <BrandMark size={32} />
          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 13, fontWeight: 600, letterSpacing: 2 }}>TANKFOOD</span>
        </div>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <div style={{ fontSize: 64, fontWeight: 800, letterSpacing: -2, lineHeight: 1, color: '#fafaf9' }}>
            Tankowania<br/><span style={{ color: '#f59e0b' }}>pod kontrolą.</span>
          </div>
          <div style={{ marginTop: 24, fontSize: 16, color: '#a1a1aa', maxWidth: 440, lineHeight: 1.6 }}>
            System ewidencji paliwa dla floty. Rozliczenia, kierowcy, pojazdy — wszystko w jednym miejscu.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 32, fontSize: 12, color: '#52525b', fontFamily: 'JetBrains Mono, monospace', letterSpacing: 0.5, position: 'relative', zIndex: 2 }}>
          <span>PANEL ADMINISTRATORA</span>
        </div>
        {/* decorative bg */}
        <div style={{ position: 'absolute', inset: 0, opacity: 0.04, zIndex: 1, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: '#fff', userSelect: 'none', overflow: 'hidden', padding: 56 }}>
          {Array.from({ length: 40 }).map((_, i) => (
            <div key={i} style={{ whiteSpace: 'nowrap' }}>
              {Array.from({ length: 30 }).map((_, j) => (
                <span key={j} style={{ marginRight: 14 }}>{((i*7+j*13)%100).toString().padStart(2,'0')}.{((i*11+j*3)%100).toString().padStart(2,'0')}l</span>
              ))}
            </div>
          ))}
        </div>
      </div>

      {/* Right form panel */}
      <div style={{ width: 480, background: '#fafaf9', color: '#18181b', padding: '72px 56px', display: 'flex', flexDirection: 'column', justifyContent: 'center', borderLeft: '1px solid #18181b' }}>
        <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase', color: '#71717a', marginBottom: 8 }}>Logowanie</div>
        <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.8, marginBottom: 8 }}>Witaj z powrotem</div>
        <div style={{ fontSize: 14, color: '#71717a', marginBottom: 32 }}>Zaloguj się aby kontynuować</div>

        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Field label="Login" required>
            <div style={{ position: 'relative' }}>
              <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#a1a1aa' }}><Icon name="user" size={16} /></div>
              <Input value={login} onChange={(e) => setLogin(e.target.value)} style={{ paddingLeft: 36 }} placeholder="login" autoComplete="username" />
            </div>
          </Field>
          <Field label="Hasło" required>
            <div style={{ position: 'relative' }}>
              <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#a1a1aa' }}><Icon name="lock" size={16} /></div>
              <Input type={showPwd ? 'text' : 'password'} value={pwd} onChange={(e) => setPwd(e.target.value)} style={{ paddingLeft: 36, paddingRight: 36 }} autoComplete="current-password" />
              <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: 4 }}>
                <Icon name="eye" size={16} />
              </button>
            </div>
          </Field>

          {errMsg && (
            <div style={{ padding: '10px 14px', background: '#fee2e2', border: '1px solid #fecaca', borderRadius: 6, fontSize: 13, color: '#991b1b' }}>
              {errMsg}
            </div>
          )}

          <button type="submit" disabled={loading} style={{ ...btnPrimaryStyle, padding: '13px 16px', fontSize: 14, justifyContent: 'center', marginTop: 8, opacity: loading ? 0.7 : 1 }}>
            {loading ? 'Logowanie…' : 'Zaloguj się'}
            {!loading && <Icon name="arrowLeft" size={16} style={{ transform: 'rotate(180deg)' }} />}
          </button>
        </form>
      </div>
    </div>
  );
}

function BrandMark({ size = 32, color = '#f59e0b' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <rect x="0" y="0" width="32" height="32" rx="6" fill={color}/>
      <path d="M16 7 L22 22 H10 Z" fill="#0c0a09"/>
      <circle cx="16" cy="19" r="2.5" fill={color}/>
    </svg>
  );
}

function AdminSidebar({ tab, onTab, user, onLogout }) {
  const initials = (user?.name || 'AD').split(' ').map(s => s[0]).slice(0,2).join('').toUpperCase();
  return (
    <aside style={{ width: 232, background: '#0c0a09', color: '#fafaf9', display: 'flex', flexDirection: 'column', flexShrink: 0, borderRight: '1px solid #18181b' }}>
      <div style={{ padding: '22px 20px 28px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid #1c1917' }}>
        <BrandMark size={28} />
        <div>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 600, letterSpacing: 2 }}>TANKFOOD</div>
          <div style={{ fontSize: 10, color: '#71717a', letterSpacing: 0.5, marginTop: 1 }}>Panel administratora</div>
        </div>
      </div>
      <nav style={{ flex: 1, padding: '16px 12px', display: 'flex', flexDirection: 'column', gap: 2 }}>
        {NAV.map((n) => {
          const active = tab === n.id;
          return (
            <button key={n.id} onClick={() => onTab(n.id)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: active ? '#f59e0b' : 'transparent', color: active ? '#0c0a09' : '#d4d4d8', border: 'none', borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, fontWeight: active ? 700 : 500, letterSpacing: -0.1, textAlign: 'left', transition: 'background .12s, color .12s' }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = '#1c1917'; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
              <Icon name={n.icon} size={18} />{n.label}
            </button>
          );
        })}
      </nav>
      <div style={{ padding: 12, borderTop: '1px solid #1c1917', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 36, height: 36, borderRadius: 18, background: '#f59e0b', color: '#0c0a09', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 13 }}>{initials}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#fafaf9', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user?.name || 'Administrator'}</div>
          <div style={{ fontSize: 11, color: '#71717a' }}>{user?.login}</div>
        </div>
        <button onClick={onLogout} title="Wyloguj" style={{ background: 'transparent', border: 'none', color: '#a1a1aa', cursor: 'pointer', padding: 6, borderRadius: 5 }}
          onMouseEnter={(e) => { e.currentTarget.style.background = '#1c1917'; e.currentTarget.style.color = '#fafaf9'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = '#a1a1aa'; }}>
          <Icon name="logout" size={16} />
        </button>
      </div>
    </aside>
  );
}

function PageHeader({ title, subtitle, action }) {
  return (
    <div style={{ padding: '20px 32px 18px', borderBottom: '1px solid #e7e5e4', background: '#fff', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexShrink: 0 }}>
      <div>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.6, color: '#18181b', lineHeight: 1.2 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 13, color: '#71717a', marginTop: 4 }}>{subtitle}</div>}
      </div>
      {action}
    </div>
  );
}

Object.assign(window, { AdminApp, AdminLogin, AdminDashboard, BrandMark, PageHeader });
