// zlap-termin — app shell z prawdziwym API backend
const { useState, useEffect, useMemo, useRef, useCallback } = React;

const API = window.ZlapApi;
const A = API.adapters;

/* Topbar */
function TopBar({ state, email, onLogout, startedAt }) {
  return (
    <header style={{
      display: "flex", alignItems: "center", gap: 12,
      padding: "0 16px",
      height: 48,
      borderBottom: "1px solid var(--border)",
      background: "var(--bg-raised)",
      position: "sticky", top: 0, zIndex: 20,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--mono)", fontSize: 14, fontWeight: 600, letterSpacing: "-0.01em" }}>
        <span style={{
          width: 22, height: 22, borderRadius: 3,
          background: "var(--hit)", color: "var(--bg)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon name="zap" size={13} stroke={2.4}/>
        </span>
        <span>zlap<span style={{color:"var(--fg-muted)"}}>-termin</span></span>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 8, marginLeft: 10 }} className="topbar-status">
        <StatusBadge state={state} />
        {startedAt && (
          <span className="mono" style={{ fontSize: 11, color: "var(--fg-muted)" }}>
            uptime <TickingSince date={startedAt} live={state === "online"} />
          </span>
        )}
      </div>

      <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
        <span className="mono topbar-user" style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>
          {email || ""}
        </span>
        <button className="btn ghost" onClick={onLogout} title="Wyloguj">
          <Icon name="logout" size={13} />
        </button>
      </div>

      <style>{`
        @media (max-width: 640px) { .topbar-user { display: none !important; } }
        @media (max-width: 520px) { .topbar-status .mono { display: none; } }
      `}</style>
    </header>
  );
}

/* Sidebar */
const NAV = [
  { id: "dashboard", label: "Dashboard",   icon: "activity" },
  { id: "check",     label: "Sprawdź",     icon: "search" },
  { id: "auto",      label: "Auto-task",   icon: "zap" },
  { id: "reservations", label: "Rezerwacje", icon: "check" },
  { id: "slots",     label: "Terminy",     icon: "clock" },
  { id: "logs",      label: "Logi",        icon: "terminal" },
  { id: "settings",  label: "Ustawienia",  icon: "settings" },
];

function Sidebar({ active, onNav, collapsed, setCollapsed }) {
  return (
    <>
      <nav className="sidebar-desktop" style={{
        width: collapsed ? 52 : 200,
        transition: "width 200ms ease",
        borderRight: "1px solid var(--border)",
        background: "var(--bg-raised)",
        display: "flex", flexDirection: "column",
        flexShrink: 0,
      }}>
        <div style={{ padding: 10, display: "flex", flexDirection: "column", gap: 2, flex: 1 }}>
          {NAV.map(n => {
            const on = active === n.id;
            return (
              <button key={n.id} onClick={() => onNav(n.id)}
                style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "8px 10px",
                  background: on ? "var(--bg-hover)" : "transparent",
                  border: "none",
                  borderLeft: on ? "2px solid var(--fg)" : "2px solid transparent",
                  color: on ? "var(--fg)" : "var(--fg-muted)",
                  cursor: "pointer",
                  borderRadius: 3,
                  fontSize: 13,
                  fontWeight: on ? 500 : 400,
                  textAlign: "left",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                }}>
                <Icon name={n.icon} size={15} />
                {!collapsed && <span>{n.label}</span>}
              </button>
            );
          })}
        </div>
        <div style={{ padding: 10, borderTop: "1px solid var(--border)" }}>
          <button className="btn ghost" onClick={() => setCollapsed(!collapsed)} style={{ width: "100%", justifyContent: "center" }}>
            <Icon name={collapsed ? "chevRight" : "chevLeft"} size={13} />
          </button>
        </div>
      </nav>

      <nav className="bottom-nav" style={{
        position: "fixed", bottom: 0, left: 0, right: 0,
        background: "var(--bg-raised)",
        borderTop: "1px solid var(--border)",
        display: "none",
        zIndex: 30,
      }}>
        {NAV.slice(0, 5).map(n => {
          const on = active === n.id;
          return (
            <button key={n.id} onClick={() => onNav(n.id)}
              style={{
                flex: 1,
                display: "flex", flexDirection: "column", alignItems: "center", gap: 3,
                padding: "8px 4px",
                background: "transparent",
                border: "none",
                borderTop: on ? "2px solid var(--fg)" : "2px solid transparent",
                color: on ? "var(--fg)" : "var(--fg-muted)",
                cursor: "pointer",
                fontSize: 10.5,
              }}>
              <Icon name={n.icon} size={17} />
              <span>{n.label}</span>
            </button>
          );
        })}
      </nav>

      <style>{`
        @media (max-width: 720px) {
          .sidebar-desktop { display: none !important; }
          .bottom-nav { display: flex !important; }
          .app-main { padding-bottom: 56px !important; }
        }
      `}</style>
    </>
  );
}

/* Toast host */
function useToasts() {
  const [toasts, setToasts] = useState([]);
  const push = useCallback((msg, tone = "ok") => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, msg, tone }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 5000);
  }, []);
  const node = (
    <div style={{
      position: "fixed", top: 60, right: 14,
      display: "flex", flexDirection: "column", gap: 8,
      zIndex: 100,
      pointerEvents: "none",
    }}>
      {toasts.map(t => (
        <div key={t.id} className="toast-in" style={{
          background: "var(--bg-raised)",
          border: "1px solid var(--border-strong)",
          borderLeft: `3px solid ${
            t.tone === "ok"   ? "var(--ok)" :
            t.tone === "warn" ? "var(--warn)" :
            t.tone === "err"  ? "var(--err)" :
            t.tone === "hit"  ? "var(--hit)" : "var(--info)"
          }`,
          padding: "10px 14px",
          borderRadius: 4,
          fontSize: 12.5,
          minWidth: 260,
          maxWidth: 380,
          boxShadow: "0 8px 32px rgba(0,0,0,0.4)",
          pointerEvents: "auto",
        }}>
          {t.msg}
        </div>
      ))}
    </div>
  );
  return [push, node];
}

/* ============================ APP ============================ */
function App() {
  const [session, setSession] = useState(null); // {email, csrf_token} albo null
  const [loading, setLoading] = useState(true);
  const [route, setRoute] = useState("dashboard");
  const [status, setStatus] = useState(null);
  const [navCollapsed, setNavCollapsed] = useState(false);
  const [toast, toastNode] = useToasts();

  // Bootstrap: sprawdź session
  useEffect(() => {
    API.session()
      .then(s => setSession(s))
      .catch(() => setSession(null))
      .finally(() => setLoading(false));
  }, []);

  // Polling statusu (co 3s gdy zalogowany)
  useEffect(() => {
    if (!session) return;
    let cancelled = false;
    const tick = async () => {
      try {
        const s = await API.status();
        if (!cancelled) setStatus(s);
      } catch (e) {
        if (e.status === 401 && !cancelled) setSession(null);
      }
    };
    tick();
    const iv = setInterval(tick, 3000);
    return () => { cancelled = true; clearInterval(iv); };
  }, [session]);

  const handleLogin = async (email, password) => {
    try {
      const res = await API.login(email, password);
      setSession(res);
      toast("Zalogowano", "ok");
    } catch (e) {
      toast(`Błąd logowania: ${e.message || e}`, "err");
      throw e;
    }
  };

  const handleLogout = async () => {
    try { await API.logout(); } catch (_) {}
    setSession(null);
    toast("Wylogowano", "info");
  };

  if (loading) {
    return (
      <div style={{
        minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
        background: "var(--bg)", color: "var(--fg-muted)",
      }}>
        <div className="mono">Ładowanie…</div>
      </div>
    );
  }

  if (!session) {
    return <LoginView onLogin={handleLogin} />;
  }

  const botState = status?.state || "offline";
  const startedAt = status?.started_at ? new Date(status.started_at) : null;

  const view = () => {
    switch (route) {
      case "dashboard":    return <DashboardView status={status} toast={toast} />;
      case "check":        return <CheckNowView toast={toast} />;
      case "auto":         return <AutoTasksView toast={toast} />;
      case "reservations": return <ReservationsView toast={toast} />;
      case "slots":        return <SlotsView />;
      case "logs":         return <LogsView />;
      case "settings":     return <SettingsView toast={toast} />;
      default:             return null;
    }
  };

  return (
    <div className="app-bg app-root" style={{ minHeight: "100vh", display: "flex", flexDirection: "column", position: "relative" }}>
      <TopBar state={botState} email={session.email} onLogout={handleLogout} startedAt={startedAt} />
      <div style={{ display: "flex", flex: 1, minHeight: 0, position: "relative", zIndex: 1 }}>
        <Sidebar active={route} onNav={setRoute} collapsed={navCollapsed} setCollapsed={setNavCollapsed} />
        <main className="app-main" style={{ flex: 1, minWidth: 0, overflowY: "auto", height: "calc(100vh - 48px)" }}>
          {view()}
        </main>
      </div>
      {toastNode}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
