// Main App component

function App() {
  const store = useStore();
  const [theme, setTheme] = React.useState(() => {
    const saved = localStorage.getItem("ac.theme");
    return AC_THEMES[saved] ? saved : "operator";
  });
  const [view, setView] = React.useState(() => localStorage.getItem("ac.view") || "dashboard");
  const [activeSession, setActiveSession] = React.useState(() => localStorage.getItem("ac.session") || null);
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);
  const [showThemes, setShowThemes] = React.useState(false);
  const [showNewSession, setShowNewSession] = React.useState(false);

  const t = AC_THEMES[theme] || AC_THEMES.operator;

  React.useEffect(() => { localStorage.setItem("ac.view", view); }, [view]);
  React.useEffect(() => { if (activeSession) localStorage.setItem("ac.session", activeSession); }, [activeSession]);
  React.useEffect(() => { localStorage.setItem("ac.theme", theme); }, [theme]);

  // Store user globally for sidebar
  React.useEffect(() => { window.__AC_USER = store.user; }, [store.user]);

  // Auth gate
  if (!store.authChecked) {
    return <div style={{ height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: t.bg, color: t.fg, fontFamily: t.fontSans }}>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: 14, color: t.fg2 }}>Loading...</div>
      </div>
    </div>;
  }

  if (store.authRequired && !store.user) {
    return <LoginPage theme={t} />;
  }

  const openSession = (id) => { setActiveSession(id); setView("chat"); };

  const handleNewSession = () => {
    if (store.machines.length === 0) return;
    if (store.machines.length === 1) {
      store.createSession(store.machines[0].id).then(s => { if (s?.id) openSession(s.id); });
    } else {
      setShowNewSession(true);
    }
  };

  const goBackToDashboard = () => { setView("dashboard"); setActiveSession(null); };

  const session = view === "chat" ? store.sessions.find(s => s.id === activeSession) : null;
  const machine = session ? store.machines.find(m => m.id === session.machine_id) : null;

  return (
    <div style={{ display: "flex", height: "100vh", width: "100vw", background: t.bg, color: t.fg }}>
      <Sidebar
        theme={t}
        machines={store.machines}
        sessions={store.sessions}
        activeId={view === "chat" ? activeSession : null}
        onSelect={openSession}
        view={view}
        onNavigate={(v) => setView(v)}
        collapsed={sidebarCollapsed}
        onNewSession={handleNewSession}
      />
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        {/* Top bar with theme/collapse controls */}
        <div style={{
          height: 36, display: "flex", alignItems: "center", justifyContent: "flex-end",
          padding: "0 16px", background: t.bg2, borderBottom: `1px solid ${t.line}`, gap: 8, flexShrink: 0,
        }}>
          {!store.connected && <span style={{ fontSize: 10, fontFamily: t.fontMono, color: t.warn }}>reconnecting...</span>}
          {store.connected && <span style={{ fontSize: 10, fontFamily: t.fontMono, color: t.accent }}>connected</span>}
          <div style={{ flex: 1 }} />
          <button onClick={() => setSidebarCollapsed(!sidebarCollapsed)} style={{ ...iconBtn(t), width: 30, height: 30 }} title="Toggle sidebar">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12h18M3 6h18M3 18h18"/></svg>
          </button>
          <div style={{ position: "relative" }}>
            <button onClick={() => setShowThemes(!showThemes)} style={{ ...iconBtn(t), width: 30, height: 30 }} title="Theme">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
            </button>
            {showThemes && <ThemeDropdown theme={t} current={theme} onSelect={(k) => { setTheme(k); setShowThemes(false); }} onClose={() => setShowThemes(false)} />}
          </div>
        </div>

        {/* Content */}
        <div style={{ flex: 1, display: "flex", minHeight: 0 }}>
          {view === "dashboard" && (
            <Dashboard theme={t} machines={store.machines} sessions={store.sessions}
              onOpenSession={openSession} onAddMachine={store.createMachine} onDeleteMachine={store.deleteMachine} />
          )}
          {view === "chat" && session && <ChatView theme={t} session={session} machine={machine} onBack={goBackToDashboard} onDeleted={goBackToDashboard} />}
          {view === "chat" && !session && (
            <Dashboard theme={t} machines={store.machines} sessions={store.sessions}
              onOpenSession={openSession} onAddMachine={store.createMachine} onDeleteMachine={store.deleteMachine} />
          )}
          {view === "agents" && <AgentsPage theme={t} />}
          {view === "extension" && <ExtensionPage theme={t} />}
        </div>
      </div>
      {showNewSession && <NewSessionModal theme={t} machines={store.machines}
        onCreate={async (machineId) => { const s = await store.createSession(machineId); setShowNewSession(false); if (s?.id) openSession(s.id); }}
        onClose={() => setShowNewSession(false)} />}
    </div>
  );
}

function LoginPage({ theme }) {
  const t = theme;
  return (
    <div style={{
      height: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: t.bg, color: t.fg, fontFamily: t.fontSans,
    }}>
      <div style={{ textAlign: "center", maxWidth: 360, padding: 40 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12, background: t.accent,
          display: "flex", alignItems: "center", justifyContent: "center",
          margin: "0 auto 20px", color: t.bg, fontWeight: 700, fontSize: 22, fontFamily: t.fontMono,
        }}>/</div>
        <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 24, marginBottom: 8 }}>agents control</div>
        <div style={{ fontSize: 13, color: t.fg2, marginBottom: 28, lineHeight: 1.5 }}>
          Control your dev agents from anywhere. Sign in to get started.
        </div>
        <a href="/auth/github" style={{
          display: "inline-flex", alignItems: "center", gap: 10,
          padding: "12px 24px", background: t.fg, color: t.bg,
          borderRadius: t.radius, textDecoration: "none", fontSize: 14, fontWeight: 600,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
          Sign in with GitHub
        </a>
      </div>
    </div>
  );
}

function ThemeDropdown({ theme, current, onSelect, onClose }) {
  const t = theme;
  return (
    <div style={{
      position: "absolute", top: 28, right: 0, width: 180, background: t.panel,
      border: `1px solid ${t.line2}`, borderRadius: t.radius, padding: 6,
      boxShadow: "0 10px 30px rgba(0,0,0,0.3)", zIndex: 100, animation: "ac-fade 0.15s",
    }}>
      {Object.entries(AC_THEMES).map(([key, th]) => (
        <button key={key} onClick={() => onSelect(key)} style={{
          width: "100%", display: "flex", alignItems: "center", gap: 8, padding: "8px 10px",
          background: current === key ? t.panel2 : "transparent",
          border: current === key ? `1px solid ${t.line2}` : "1px solid transparent",
          borderRadius: t.radius - 2, color: t.fg, cursor: "pointer",
          fontFamily: t.fontSans, fontSize: 12, textAlign: "left",
        }}>
          <span style={{ width: 10, height: 10, borderRadius: 999, background: th.accent, flexShrink: 0 }} />
          <span style={{ fontWeight: current === key ? 600 : 400 }}>{th.name}</span>
        </button>
      ))}
    </div>
  );
}

function NewSessionModal({ theme, machines, onCreate, onClose }) {
  const t = theme;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 200 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 400, background: t.panel, border: `1px solid ${t.line2}`, borderRadius: t.radius + 4, padding: 24, fontFamily: t.fontSans, color: t.fg, animation: "ac-fade 0.2s" }}>
        <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 18, marginBottom: 16 }}>New session</div>
        <div style={{ fontSize: 12, color: t.fg2, marginBottom: 12 }}>Select a machine:</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 300, overflowY: "auto" }}>
          {machines.map(m => (
            <button key={m.id} onClick={() => onCreate(m.id)} style={{
              display: "flex", alignItems: "center", gap: 10, padding: "12px 14px",
              background: t.panel2, border: `1px solid ${t.line}`, borderRadius: t.radius,
              cursor: "pointer", fontFamily: t.fontSans, color: t.fg, textAlign: "left",
            }}
            onMouseEnter={e => e.currentTarget.style.borderColor = t.accent}
            onMouseLeave={e => e.currentTarget.style.borderColor = t.line}>
              <StatusDot status={m.status} theme={t} size={8} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{m.name}</div>
                <div style={{ fontSize: 10.5, fontFamily: t.fontMono, color: t.fg3, marginTop: 2 }}>{m.connector_version || "no connector"} - {m.status}</div>
              </div>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 16 }}>
          <button onClick={onClose} style={{ padding: "8px 16px", background: "transparent", border: `1px solid ${t.line2}`, borderRadius: t.radius, color: t.fg2, cursor: "pointer", fontSize: 13 }}>Cancel</button>
        </div>
      </div>
    </div>
  );
}

window.App = App;
window.LoginPage = LoginPage;
