/* passenger/app.jsx — root */

function ToastSystem() {
  const [toasts, setToasts] = React.useState([]);

  React.useEffect(() => {
    window.showToast = (msg, kind = "info", undo = null) => {
      const id = Date.now();
      setToasts(prev => [...prev.slice(-4), { id, msg, kind, undo }]);
      setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), undo ? 10000 : 4000);
    };
  }, []);

  const dismiss = id => setToasts(prev => prev.filter(t => t.id !== id));

  return (
    <div className="toast-stack">
      {toasts.map(t => (
        <div key={t.id} className={"toast toast-" + t.kind}>
          <span>{t.msg}</span>
          <div style={{ display: "flex", gap: 8, alignItems: "center", flexShrink: 0 }}>
            {t.undo && (
              <button onClick={() => { t.undo(); dismiss(t.id); }}
                style={{ border: "1px solid rgba(255,255,255,0.3)", background: "transparent", color: "white", padding: "2px 8px", borderRadius: 4, cursor: "pointer", fontSize: 12, fontFamily: "inherit" }}>
                Undo
              </button>
            )}
            <button onClick={() => dismiss(t.id)}
              style={{ border: "none", background: "transparent", color: "rgba(255,255,255,0.6)", cursor: "pointer", fontSize: 16, padding: 0, lineHeight: 1 }}>
              ×
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}

function PlaceholderScreen({ title, icon }) {
  return (
    <>
      <Topbar title={title} />
      <div className="page" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 400 }}>
        <div style={{ textAlign: "center", color: "var(--text-3)" }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>{icon}</div>
          <div style={{ fontSize: 18, fontWeight: 600, color: "var(--text-2)", marginBottom: 6 }}>{title}</div>
          <div style={{ fontSize: 14 }}>Екран у розробці — буде в наступному етапі</div>
        </div>
      </div>
    </>
  );
}

function App() {
  const [user, setUser] = React.useState(null);
  const [bootChecked, setBootChecked] = React.useState(false);
  const [screen, setScreen] = React.useState("overview");
  const [paletteOpen, setPaletteOpen] = React.useState(false);

  // Перевірка існуючої сесії при mount.
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await window.passengerApi.auth.whoami();
        if (!cancelled) {
          setUser({ actor: res.actor, role: res.role, capabilities: res.capabilities });
        }
      } catch (err) {
        if (!cancelled) setUser(null);
      } finally {
        if (!cancelled) setBootChecked(true);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  React.useEffect(() => {
    window.openPalette = () => setPaletteOpen(true);
    return () => { delete window.openPalette; };
  }, []);

  React.useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); setPaletteOpen(p => !p); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  const handleLogin = (u) => { setUser(u); setScreen("overview"); };
  const handleLogout = async () => {
    try { await window.passengerApi.auth.logout(); } catch (e) { /* ignore */ }
    setUser(null);
    setScreen("overview");
  };

  if (!bootChecked) {
    return (
      <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", color: "var(--text-3)", fontSize: 14 }}>
        <div>
          <span style={{ display: "inline-block", animation: "spin 1s linear infinite", marginRight: 6 }}>⟳</span>
          Перевірка сесії…
        </div>
      </div>
    );
  }

  if (!user) return <Login onLogin={handleLogin} />;

  const caps = user.capabilities || {};
  const allowedScreen = (s) => {
    if (s === "settings") return !!caps.settings_write;
    return true;
  };
  const safeScreen = allowedScreen(screen) ? screen : "overview";

  return (
    <div className="app-layout">
      <Sidebar active={safeScreen} onNav={setScreen} user={user} onLogout={handleLogout} />
      <div className="main-area">
        {safeScreen === "overview"   && <Overview onNav={setScreen} />}
        {safeScreen === "stops"      && <Stops onNav={setScreen} />}
        {safeScreen === "routes"     && <Routes onNav={setScreen} />}
        {safeScreen === "monitoring" && <Monitoring onNav={setScreen} />}
        {safeScreen === "analytics"  && <Analytics />}
        {safeScreen === "history"    && <History />}
        {safeScreen === "settings"   && caps.settings_write && <Settings />}
      </div>
      <ToastSystem />
      <CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} onNav={setScreen} />
    </div>
  );
}

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