// Main app entry point: router state, auth gate, sidebar nav, breadcrumbs, placeholder screens.
// Mounts ToastProvider + ConfirmProvider, then renders App into #root.

const { useState, useEffect } = React;

// ─── Coming soon placeholder ─────────────────────────────────────────────
const ComingSoon = ({ title, icon: IconC = I.Clock }) => (
  <div className="coming-soon">
    <IconC className="icon" />
    <h2>{title}</h2>
    <p>This section is coming soon.</p>
  </div>
);

// ─── Dashboard stub with real system stats ───────────────────────────────
const DashboardScreen = ({ capacity, isAdmin }) => {
  const { data, loading, refetch } = useApi(
    () => isAdmin ? SystemApi.stats() : Promise.resolve(null), [isAdmin]
  );

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Dashboard</h1>
          <div className="page-sub">System overview and health.</div>
        </div>
        <button className="btn" onClick={refetch}><I.Refresh /> Refresh</button>
      </div>
      <div className="kpi-row">
        <Kpi label="Total bots" value={loading ? "…" : (data?.totalBots ?? data?.bots?.total ?? "—")} />
        <Kpi label="Active bots" value={loading ? "…" : (data?.activeBots ?? data?.bots?.active ?? "—")} />
        <Kpi label="Active sessions" value={loading ? "…" : (data?.activeSessions ?? data?.sessions?.active ?? "—")} />
        <Kpi label="Messages forwarded" value={loading ? "…" : (data?.totalMessages ?? data?.messages?.forwarded ?? "—")} />
      </div>
      {capacity?.limits && (
        <Card title="System capacity" className="mt-4">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '1rem' }}>
            {Object.entries(capacity.limits).map(([key, { current, max }]) => {
              const pct = Math.round((current / max) * 100);
              const tone = systemCapacityTone(current, max);
              const full = tone === 'danger';
              return (
                <div key={key} style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                  <div style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                    {key.replace(/([A-Z])/g, ' $1').trim()}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: '0.25rem' }}>
                    <span style={{ fontSize: 20, fontWeight: 600, color: full ? 'var(--red)' : 'var(--fg)' }}>
                      {current}
                    </span>
                    <span style={{ fontSize: 13, color: 'var(--fg-3)' }}>/ {max}</span>
                  </div>
                  <div style={{ position: 'relative', height: 4, backgroundColor: 'var(--bg-card-2)', borderRadius: 2, overflow: 'hidden' }}>
                    <div style={{ 
                      position: 'absolute', 
                      left: 0, 
                      top: 0, 
                      bottom: 0, 
                      width: `${Math.min(pct, 100)}%`,
                      backgroundColor: full ? 'var(--red)' : (tone === 'warning' ? 'var(--yellow)' : 'var(--accent)'),
                      transition: 'width 0.3s' 
                    }} />
                  </div>
                  {full && (
                    <div style={{ fontSize: 11, color: 'var(--red)', fontWeight: 500 }}>
                      <I.AlertTriangle size={12} style={{ verticalAlign: '-1px', marginRight: 4 }} />
                      At limit
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </Card>
      )}
      <Card title="System status">
        <div className="muted" style={{ fontSize: 13 }}>
          Server is running. Use the sidebar to manage bots, configs, and groups.
        </div>
      </Card>
    </div>
  );
};

// ─── Auth screen: list + launch wizard ──────────────────────────────────
const AuthScreen = ({ onStartWizard }) => {
  const toast = useToast();
  const { data: bots, loading } = useApi(BotApi.list, []);

  const handleReset = async (botId) => {
    try {
      await BotApi.requestCode(botId);
      toast.success("New verification code sent");
      onStartWizard(botId, "otp");
    } catch (e) {
      toast.error(e.message || "Failed to resend code");
    }
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Auth & 2FA</h1>
          <div className="page-sub">Authenticated phone numbers and their status.</div>
        </div>
        <button className="btn primary" onClick={() => onStartWizard()}><I.Plus /> Authenticate new</button>
      </div>
      <Card flush>
        <table className="table">
          <thead>
            <tr>
              <th>Bot</th><th>Phone</th><th>Platform</th><th>Status</th><th style={{ width: 120 }}>Action</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <SkeletonRows cols={5} rows={3} />
            ) : (bots || []).length === 0 ? (
              <tr><td colSpan={5}><Empty icon={I.Bot} title="No bots" sub="Add a bot to authenticate." /></td></tr>
            ) : (
              (bots || []).map((b) => (
                <tr key={b._id}>
                  <td style={{ fontWeight: 500 }}>{b.name}</td>
                  <td className="mono">{b.phone}</td>
                  <td><PlatformChip platform={b.platform} /></td>
                  <td><StatusBadge status={b.status} /></td>
                  <td>
                    {isAuthWaiting(b.status) ? (
                      <button className="btn ghost sm" onClick={() => handleReset(b._id)}>Reset</button>
                    ) : (
                      <button className="btn ghost sm" onClick={() => onStartWizard(b._id)}>Re-auth</button>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// ─── Breadcrumb map ──────────────────────────────────────────────────────
const crumbsFor = (route) => {
  switch (route.screen) {
    case "dashboard":  return ["Operate", "Dashboard"];
    case "sessions":   return ["Operate", "Active Sessions"];
    case "events":     return ["Operate", "Event Stream"];
    case "bots":       return ["Configure", "Bots"];
    case "bot-detail": return ["Configure", "Bots", route.params?.botName || "Detail"];
    case "configs":    return ["Configure", "Bot Configs"];
    case "sources":    return ["Configure", "Source"];
    case "ocr-image":  return ["Configure", "OCR Image"];
    case "targets":    return ["Configure", "Target"];
    case "react-campaigns": return ["Configure", "Auto React"];
    case "react-history": return ["Configure", "Auto React", "History"];
    case "groups":     return ["Configure", "Source"];
    case "ai":         return ["Configure", "AI Rewrite"];
    case "auth":       return ["System", "Auth & 2FA"];
    case "auth-wizard":return ["System", "Auth & 2FA", "Wizard"];
    case "proxies":    return ["System", "Proxies"];
    case "settings":   return ["System", "Settings"];
    case "users":      return ["System", "Users"];
    default:           return [route.screen];
  }
};

// ─── Active nav item (handles sub-screens) ───────────────────────────────
const activeNavFor = (screen) => {
  if (screen === "bot-detail") return "bots";
  if (screen === "auth-wizard") return "auth";
  if (screen === "react-history") return "react-campaigns";
  return screen;
};

// ─── Main app component ──────────────────────────────────────────────────
const App = () => {
  const [authed, setAuthed] = useState(AuthStore.isLoggedIn());
  const [currentUser, setCurrentUser] = useState(AuthStore.getUser());
  const [route, setRoute] = useState({ screen: "dashboard", params: {} });
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [listQuery, setListQuery] = useState("");

  useEffect(() => { setListQuery(""); }, [route.screen]);

  // Listen for forced logout (401 from apiFetch)
  useEffect(() => {
    const handler = () => { setAuthed(false); setCurrentUser(null); };
    window.addEventListener("auth:logout", handler);
    return () => window.removeEventListener("auth:logout", handler);
  }, []);

  // Expose global navigate for cross-screen links (e.g. bot-detail → auth-wizard)
  useEffect(() => {
    window.__navigate = (screen, params = {}) => setRoute({ screen, params });
  }, []);

  const handleLogin = (token, user) => {
    AuthStore.setToken(token);
    AuthStore.setUser(user);
    setAuthed(true);
    setCurrentUser(user);
  };

  const handleLogout = () => {
    AuthStore.clear();
    setAuthed(false);
    setCurrentUser(null);
  };

  // Fetch capacity only when logged in; keep admin-only stats private.
  const { data: capacity, refetch: refreshCapacity } = useApi(
    () => authed ? SystemApi.capacity() : Promise.resolve(null), [authed]
  );
  useEffect(() => {
    if (!authed) return;
    window.addEventListener('capacity:changed', refreshCapacity);
    const interval = setInterval(refreshCapacity, 30000);
    return () => {
      window.removeEventListener('capacity:changed', refreshCapacity);
      clearInterval(interval);
    };
  }, [authed]);

  // Show login screen if not authenticated
  if (!authed) {
    return (
      <ToastProvider>
        <LoginScreen onLogin={handleLogin} />
      </ToastProvider>
    );
  }

  const navigate = (id) => {
    setListQuery("");
    setRoute({ screen: id, params: {} });
  };

  const renderScreen = () => {
    const { screen, params } = route;
    switch (screen) {
      case "dashboard":
        return <DashboardScreen capacity={capacity} isAdmin={currentUser?.role === 'admin'} />;
      case "bots":
        return <BotsList stats={capacity} listQuery={listQuery} onQuery={setListQuery} onOpenBot={(id, name) => setRoute({ screen: "bot-detail", params: { botId: id, botName: name } })} />;
      case "bot-detail":
        return <BotDetail botId={params.botId} onBack={() => setRoute({ screen: "bots", params: {} })} />;
      case "configs":
        return <ConfigsScreen stats={capacity} listQuery={listQuery} onQuery={setListQuery} />;
      case "sources":
        return <GroupsScreen key="source" role="source" stats={capacity} listQuery={listQuery} onQuery={setListQuery} />;
      case "ocr-image":
        return <OcrImageScreen />;
      case "targets":
        return <GroupsScreen key="target" role="target" stats={capacity} listQuery={listQuery} onQuery={setListQuery} />;
      case "react-campaigns":
        return <ReactCampaignsScreen listQuery={listQuery} onQuery={setListQuery} onOpenHistory={(c) => setRoute({ screen: "react-history", params: { campaignId: c._id, campaignName: c.name } })} />;
      case "react-history":
        return <ReactHistoryScreen campaignId={params.campaignId} listQuery={listQuery} onQuery={setListQuery} onBack={() => setRoute({ screen: "react-campaigns", params: {} })} />;
      case "groups":
        return <GroupsScreen key="source" role="source" stats={capacity} listQuery={listQuery} onQuery={setListQuery} />;
      case "auth":
        return (
          <AuthScreen
            onStartWizard={(preselectedBotId, initialStep) =>
              setRoute({ screen: "auth-wizard", params: { preselectedBotId, initialStep } })
            }
          />
        );
      case "auth-wizard":
        return (
          <AuthWizard
            preselectedBotId={params.preselectedBotId}
            initialStep={params.initialStep}
            onNavigateToBotDetail={(id) => setRoute({ screen: "bot-detail", params: { botId: id } })}
            onCancel={() => setRoute({ screen: "auth", params: {} })}
          />
        );
      case "sessions":
        return <SessionsScreen />;
      case "events":
        return <EventStreamScreen />;
      case "users":
        return currentUser?.role === "admin" ? <UserManagementScreen currentUser={currentUser} /> : <DashboardScreen capacity={capacity} isAdmin={currentUser?.role === 'admin'} />;
      case "ai":
        return <ComingSoon title="AI Rewrite" icon={I.Sparkles} />;
      case "proxies":
        return <ComingSoon title="Proxies" icon={I.Server} />;
      case "settings":
        return <ComingSoon title="Settings" icon={I.Settings} />;
      default:
        return <DashboardScreen capacity={capacity} isAdmin={currentUser?.role === 'admin'} />;
    }
  };

  return (
    <ToastProvider>
      <ConfirmProvider>
        <div className="app">
          <Sidebar
            active={activeNavFor(route.screen)}
            onNavigate={navigate}
            collapsed={sidebarCollapsed}
            onToggleCollapsed={() => setSidebarCollapsed((v) => !v)}
            currentUser={currentUser}
          />
          <div className="main-col">
            <Topbar
              crumbs={crumbsFor(route)}
              currentUser={currentUser}
              onLogout={handleLogout}
            />
            <div className="content">{renderScreen()}</div>
          </div>
        </div>
      </ConfirmProvider>
    </ToastProvider>
  );
};

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