import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Gem, LogOut, Zap, Rocket, BarChart3, LogIn, MessageCircle, PanelLeftClose, PanelLeftOpen, Menu, X, Rss, Crown, Gift, Home, Search, Settings, BookOpen, Flame } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useAuth } from "@/hooks/useAuth";
import { useIsMobile } from "@/hooks/use-mobile";
import { useLockBodyScroll } from "@/hooks/useLockBodyScroll";
import { usePlanData } from "@/hooks/usePlanData";
import { LoadingBar } from "@/components/routing/LoadingBar";
import { OAuthRedirectHandler } from "@/components/auth/OAuthRedirectHandler";
import { TrendingTable } from "@/components/trending/TrendingTable";
import {
  type TrendingSort,
  type TrendingListSize,
  DEFAULT_TRENDING_LIST_SIZE,
} from "@/components/trending/TrendingFiltersPopover";
import { LandingPerformanceDialog } from "@/components/landing/LandingPerformanceDialog";
import EarlyCallsPromoCard from "@/components/landing/EarlyCallsPromoCard";
import GetPremiumPromoCard from "@/components/landing/GetPremiumPromoCard";
import { isTrendingAllowedEmail } from "@/config/trendingAllowlist";
import { getSidebarOpen, setSidebarOpen } from "@/utils/sidebarState";
import { LiveStatusPanel } from "@/components/landing/LiveStatusPanel";
import UnlockFeaturesStrip from "@/components/landing/UnlockFeaturesStrip";
import { MobileLandingSplash } from "@/components/landing/MobileLandingSplash";
import PremiumRewardsStrip from "@/components/landing/PremiumRewardsStrip";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { TelegramDropdown } from "@/components/feed/TelegramDropdown";
import { DiscordDropdown } from "@/components/feed/DiscordDropdown";
import { HistoricalCallsSearchDialog } from "@/components/feed/HistoricalCallsSearchDialog";
import { MobileNavDock } from "@/components/feed/MobileNavDock";
import { setLastListPage } from "@/utils/lastListPage";
import { TelegramUsernameForm } from "@/components/telegram/TelegramUsernameForm";
import { TelegramBotSelector } from "@/components/telegram/TelegramBotSelector";
import { TelegramBotInstructions } from "@/components/telegram/TelegramBotInstructions";
import { useTelegramHandlers } from "@/hooks/useTelegramHandlers";
import { useStandaloneMode } from "@/hooks/useStandaloneMode";

import { logger } from "@/services/logger";
import { trackMobileLandingDwell, trackBottomDockTap, trackSettingsOpened, trackSidePanelItemClicked } from "@/services/analyticsService";
import { useQueryClient } from "@tanstack/react-query";
import { fetchPerformanceData } from "@/services/performanceService";

const XIcon = ({ className }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="currentColor">
    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
  </svg>
);

const DiscordIcon = ({ className }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="currentColor">
    <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z" />
  </svg>
);

const Landing = () => {
  const navigate = useNavigate();
  const { authenticated, ready, user, login, logout, getAccessToken } = useAuth();
  const { isPremium, cachedPremium, loading: planLoading, planData, refetch: refetchPlanData } = usePlanData();
  const isMobile = useIsMobile();
  // Freeze the document on mobile so the trending column header can never be
  // dragged off-screen (and that drag can't bleed into /feed or the chart).
  useLockBodyScroll(isMobile);
  const isStandalone = useStandaloneMode();

  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState(0);
  const [loadingMessage, setLoadingMessage] = useState("");
  // Remember the panel's open/collapsed state across navigation (shared with the
  // /feed sidebar via localStorage), so clicking Feed keeps whatever it was here.
  const [panelOpen, setPanelOpenState] = useState(() => getSidebarOpen(true));
  const setPanelOpen = (next: boolean) => { setPanelOpenState(next); setSidebarOpen(next); };
  useEffect(() => { setSidebarOpen(panelOpen); }, []); // persist initial so the next page matches
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [isTelegramOpen, setIsTelegramOpen] = useState(false);
  const [isDiscordOpen, setIsDiscordOpen] = useState(false);
  const [isMenuDiscordOpen, setIsMenuDiscordOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [performanceOpen, setPerformanceOpen] = useState(false);

  // Mark trending as the user's last "list" page so Home/Rewards on the dock
  // can bring them back here from /coin or /rewards.
  useEffect(() => {
    if (authenticated) setLastListPage('trending');
  }, [authenticated]);
  const [trendingSort, setTrendingSort] = useState<TrendingSort | null>(null);
  const [trendingListSize, setTrendingListSize] = useState<TrendingListSize>(DEFAULT_TRENDING_LIST_SIZE);

  const {
    telegramDialogOpen,
    setTelegramDialogOpen,
    telegramStep,
    isLinkingUsername,
    selectedBotUsername,
    handleTelegramAuth,
    handleAccountSubmit,
    handleBotSelect,
    handleEditUsername,
    handleInstructionsComplete,
    handleTelegramRemove,
    getTelegramDisplayText,
  } = useTelegramHandlers({ getAccessToken, planData, refetch: refetchPlanData });
  const telegramDisplayText = getTelegramDisplayText();
  const isTelegramLinked = !!telegramDisplayText;
  const telegramBotUsername = selectedBotUsername || planData?.telegramBotUsername || null;
  const telegramBotLink = telegramBotUsername ? `https://t.me/${telegramBotUsername}` : null;

  let hasQueryClient = false;
  let queryClient: ReturnType<typeof useQueryClient> | null = null;
  try {
    queryClient = useQueryClient();
    hasQueryClient = true;
  } catch {
    hasQueryClient = false;
  }

  useEffect(() => {
    if (!queryClient) return;
    queryClient.prefetchQuery({
      queryKey: ['performanceData'],
      queryFn: fetchPerformanceData,
      staleTime: 5 * 60 * 1000,
    });
  }, [queryClient]);

  // Mobile landing dwell tracking — measures if splash improves <30s drop-off.
  useEffect(() => {
    if (!isMobile || authenticated) return;
    const start = Date.now();
    let sent = false;
    const send = (exit_reason: 'pagehide' | 'visibility_hidden' | 'unmount') => {
      if (sent) return;
      sent = true;
      const dwell = Date.now() - start;
      const sawSplash = !!(window as unknown as { __gembotSplashShown?: boolean }).__gembotSplashShown;
      trackMobileLandingDwell({
        dwell_ms: dwell,
        saw_splash: sawSplash,
        bounced_under_30s: dwell < 30_000,
        exit_reason,
      });
    };
    const onPageHide = () => send('pagehide');
    const onVis = () => { if (document.visibilityState === 'hidden') send('visibility_hidden'); };
    window.addEventListener('pagehide', onPageHide);
    document.addEventListener('visibilitychange', onVis);
    return () => {
      window.removeEventListener('pagehide', onPageHide);
      document.removeEventListener('visibilitychange', onVis);
      send('unmount');
    };
  }, [isMobile, authenticated]);

  // PostHog: landing_viewed once + scroll depth thresholds
  useEffect(() => {
    import('@/services/analyticsService').then(({ trackLandingViewed, trackLandingScrollDepth }) => {
      trackLandingViewed({ is_authenticated: !!authenticated });
      const fired = new Set<number>();
      const onScroll = () => {
        const h = document.documentElement;
        const total = h.scrollHeight - h.clientHeight;
        if (total <= 0) return;
        const pct = (h.scrollTop / total) * 100;
        ([25, 50, 75, 100] as const).forEach((t) => {
          if (pct >= t && !fired.has(t)) {
            fired.add(t);
            trackLandingScrollDepth(t);
          }
        });
      };
      window.addEventListener('scroll', onScroll, { passive: true });
      return () => window.removeEventListener('scroll', onScroll);
    });
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Logout completion animation
  useEffect(() => {
    const logoutInProgress = sessionStorage.getItem("gembot-logout-in-progress");
    if (!logoutInProgress) return;
    sessionStorage.removeItem("gembot-logout-in-progress");

    setIsLoggingOut(true);
    setLoadingProgress(50);
    setLoadingMessage("Signing out...");

    const t1 = setTimeout(() => setLoadingProgress(100), 300);
    const t2 = setTimeout(() => {
      setLoadingMessage("Signed out!");
      void logout().finally(() => {
        setTimeout(() => setIsLoggingOut(false), 600);
      });
    }, 500);

    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [logout]);

  // Honor post-login "Get Premium" intent — premium-aware (mirrors Home.tsx):
  // a returning PREMIUM user who used "Get Premium" to sign in lands on the
  // trending list (/), NOT pricing; a FREE user goes to pricing. We wait for
  // plan data to resolve before sending a non-premium-cached user to pricing,
  // so a premium user is never briefly misrouted.
  useEffect(() => {
    if (!ready || !authenticated || isLoggingOut) return;
    const intent = sessionStorage.getItem("gembot-post-login-intent");
    if (intent !== "pricing") return;
    const premium = isPremium || cachedPremium;
    if (premium) {
      sessionStorage.removeItem("gembot-post-login-intent");
      return; // already on / (trending) — stay
    }
    if (planLoading) return; // not premium and still loading — wait to be sure
    sessionStorage.removeItem("gembot-post-login-intent");
    navigate("/pricing", { replace: true });
  }, [ready, authenticated, isLoggingOut, isPremium, cachedPremium, planLoading, navigate]);

  const handleLogin = async () => {
    if (!ready) return;
    try { await login(); } catch (e) { logger.error("page:Landing", "Login error", e); }
  };

  // While trending purchase is paused, the button stays visible everywhere
  // but only allowlisted emails can actually navigate. Non-allowlisted users
  // see the button visually disabled (greyed/struck-through) and clicks are
  // blocked entirely (no popover, no navigation).
  const trendingDisabled = !isTrendingAllowedEmail(user?.email?.address);
  const handleTrendingClick = () => {
    if (trendingDisabled) return;
    navigate("/trending/purchase");
  };

  const handleLoginForPremium = async () => {
    if (!ready) return;
    try {
      sessionStorage.setItem("gembot-post-login-intent", "pricing");
      await login();
    } catch (e) {
      logger.error("page:Landing", "Login error", e);
    }
  };

  const handleLogout = async () => { await logout(); };

  if (isLoggingOut) {
    return <LoadingBar progress={loadingProgress} message={loadingMessage} />;
  }

  // ── Grouped-sidebar helpers (mirror LandingSidePanel) ──
  const asideGroupLabel = (label: string) =>
    panelOpen ? (
      <div className="px-2 pt-5 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-500">{label}</div>
    ) : (
      <div className="my-2 mx-auto w-6 h-px bg-white/[0.08]" aria-hidden="true" />
    );
  // Active state is monochrome — signalled by TONE not hue: a brighter
  // (near-white) label + icon on a faint raised surface with a hairline inner
  // edge. No colour, no left accent bar. Resting items stay muted grey.
  const asideItemCls = (active: boolean) =>
    `group relative w-full flex items-center rounded-md border border-transparent transition-all duration-200 ${active ? "bg-white/[0.055] shadow-[inset_0_0_0_1px_rgba(255,255,255,0.04)]" : "hover:bg-white/[0.06] hover:border-white/[0.08]"} ${panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"}`;
  const asideBoxCls = (active: boolean) =>
    `relative flex items-center justify-center w-5 h-5 rounded-md border flex-shrink-0 ${active ? "bg-white/[0.08] border-white/[0.10]" : "bg-white/[0.05] border-white/[0.07]"}`;
  const asideIconCls = (active: boolean) => `w-3 h-3 ${active ? "text-[#F4F6F8]" : "text-slate-400 group-hover:text-white"}`;
  const asideLabelCls = (active: boolean) => `flex-1 text-left text-[11px] tracking-tight ${active ? "font-bold text-[#F4F6F8]" : "font-semibold text-slate-200 group-hover:text-white"}`;
  // Community icons — match the menu icon boxes above (same w-5 bordered box +
  // slate icon) so the whole panel reads as one consistent set.
  const asideSocialCls = "group flex items-center justify-center w-5 h-5 rounded-md bg-white/[0.05] border border-white/[0.07] hover:bg-white/[0.08] hover:border-white/[0.12] transition-colors";
  const asideAccountHandle = (user?.email?.address as string | undefined) || "Account";
  const asideAccountInitial = asideAccountHandle.charAt(0).toUpperCase();
  const asideTgPath = "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.64 6.8c-.15 1.58-.8 5.42-1.13 7.19-.14.75-.42 1-.68 1.03-.58.05-1.02-.38-1.58-.75-.88-.58-1.38-.94-2.23-1.5-.99-.65-.35-1.01.22-1.59.15-.15 2.71-2.48 2.76-2.69a.2.2 0 0 0-.05-.18c-.06-.05-.14-.03-.21-.02-.09.02-1.49.95-4.22 2.79-.4.27-.76.41-1.08.4-.36-.01-1.04-.2-1.55-.37-.63-.2-1.12-.31-1.08-.66.02-.18.27-.36.74-.55 2.92-1.27 4.86-2.11 5.83-2.51 2.78-1.16 3.35-1.36 3.73-1.36.08 0 .27.02.39.12.1.08.13.19.14.27-.01.06-.01.24-.02.38z";

  return (
    <main className="h-[100dvh] relative flex flex-col md:flex-row overflow-hidden bg-[#05070E]" aria-label="Gem Bot Trending Tokens">
      <OAuthRedirectHandler />

      {isMobile && !authenticated && <MobileLandingSplash />}

      {/* Mobile Header */}
      {isMobile && (
        <>
          <header className="fixed top-0 left-0 right-0 z-50 flex h-[52px] items-center justify-between px-3 pt-2 bg-[#05070E]">
            <Gem className="w-6 h-6 text-emerald-400" />
            <div className="flex items-center gap-1.5 ml-auto">



              {authenticated && isPremium && (
                <button
                  onClick={() => navigate("/feed")}
                  className="group flex items-center gap-1 px-1.5 h-8 rounded-md hover:bg-emerald-500/[0.08] border border-transparent hover:border-emerald-400/40 transition-all"
                >
                  <span className="flex items-center justify-center w-[20px] h-[20px] rounded bg-emerald-500/15 border border-emerald-400/30 flex-shrink-0">
                    <Rss className="w-3.5 h-3.5 text-emerald-300" />
                  </span>
                  <span className="text-[12px] font-semibold text-white group-hover:text-white">Feed</span>
                </button>
              )}

              {/* Filter removed from the mobile header — sorting now lives on the
                  trending table's column headers (COIN ▾ + sortable metrics). */}

              {authenticated && isPremium && (
                <DiscordDropdown
                  open={isDiscordOpen}
                  onOpenChange={setIsDiscordOpen}
                  trigger={
                    <button
                      className="group flex items-center justify-center h-8 w-8 rounded-md bg-white/[0.05] hover:bg-white/[0.08] transition-all"
                      aria-label="Discord"
                    >
                      <svg className="w-3.5 h-3.5 text-white" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z" />
                      </svg>
                    </button>
                  }
                />
              )}

              {authenticated && isPremium && (
                <TelegramDropdown
                  open={isTelegramOpen}
                  onOpenChange={(open) => {
                    if (open && !(isTelegramLinked && telegramBotLink)) {
                      handleTelegramAuth();
                      return;
                    }
                    setIsTelegramOpen(open);
                  }}
                  trigger={
                    <button
                      className="group flex items-center justify-center h-8 w-8 rounded-md bg-white/[0.05] hover:bg-white/[0.08] transition-all"
                      aria-label="Telegram"
                    >
                      <svg className="w-3.5 h-3.5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="m22 2-7 20-4-9-9-4Z"/>
                        <path d="M22 2 11 13"/>
                      </svg>
                    </button>
                  }
                  botLink={telegramBotLink}
                  botUsername={telegramBotUsername}
                  telegramTag={telegramDisplayText}
                  isLinked={isTelegramLinked}
                  onConnect={handleTelegramAuth}
                  onRemove={handleTelegramRemove}
                />
              )}

              {!(authenticated && isPremium) && (
                <GetPremiumPromoCard
                  onNavigate={authenticated ? () => navigate("/pricing") : handleLoginForPremium}
                  side="bottom"
                  triggerMode="click"
                >
                  <button
                    className="group flex items-center gap-1 px-1.5 h-8 rounded-md hover:bg-violet-500/[0.08] border border-transparent hover:border-violet-400/40 transition-all"
                  >
                    <span className="flex items-center justify-center w-[20px] h-[20px] rounded bg-violet-500/15 border border-violet-400/30 flex-shrink-0">
                      <Crown className="w-3.5 h-3.5 text-violet-300 fill-violet-400/40" />
                    </span>
                    <span className="text-[12px] font-semibold text-slate-200 group-hover:text-white">Get Premium</span>
                  </button>
                </GetPremiumPromoCard>
              )}
              {!(authenticated && isPremium) && (
                authenticated && hasQueryClient ? (
                  <LandingPerformanceDialog>
                    <button className="group flex items-center gap-1 px-1.5 h-8 rounded-md hover:bg-sky-500/[0.08] border border-transparent hover:border-sky-400/40 transition-all">
                      <span className="flex items-center justify-center w-[20px] h-[20px] rounded bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                        <BarChart3 className="w-3.5 h-3.5 text-sky-300" />
                      </span>
                      <span className="text-[12px] font-semibold text-slate-200 group-hover:text-white">Performance</span>
                    </button>
                  </LandingPerformanceDialog>
                ) : (
                  <EarlyCallsPromoCard
                    onNavigate={() => navigate("/gembot")}
                    expanded={true}
                    side="bottom"
                    triggerMode="click"
                  >
                    <button
                      className="group flex items-center gap-1 px-1.5 h-8 rounded-md hover:bg-emerald-500/[0.08] border border-transparent hover:border-emerald-400/40 transition-all"
                    >
                      <span className="flex items-center justify-center w-[20px] h-[20px] rounded bg-emerald-500/15 border border-emerald-400/30 flex-shrink-0">
                        <Zap className="w-3.5 h-3.5 text-emerald-300" />
                      </span>
                      <span className="text-[12px] font-semibold text-slate-200 group-hover:text-white">How It Works</span>
                    </button>
                  </EarlyCallsPromoCard>
                )
              )}

              <button
                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                className="group flex items-center gap-1 px-1.5 h-8 rounded-md bg-white/[0.05] hover:bg-white/[0.08] transition-all"
                aria-label={mobileMenuOpen ? "Close menu" : "Open menu"}
              >
                <span className="text-[12px] font-medium text-white group-hover:text-white">More</span>
                {mobileMenuOpen ? <X className="w-3.5 h-3.5 text-white" /> : <Menu className="w-3.5 h-3.5 text-white" />}
              </button>
            </div>
          </header>


          {mobileMenuOpen && (
            <div className="fixed top-[52px] left-0 right-0 z-50 bg-[#05070E] px-3 py-3 flex flex-col gap-1 max-h-[calc(100vh-52px)] overflow-y-auto overscroll-contain">

              {!authenticated && (
                <button
                  onClick={() => { handleLogin(); setMobileMenuOpen(false); }}
                  disabled={!ready}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-cyan-500/[0.08] border border-transparent hover:border-cyan-400/40 transition-all disabled:opacity-50"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-cyan-500/15 border border-cyan-400/30 flex-shrink-0">
                    <LogIn className="w-4 h-4 text-cyan-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">{!ready ? "Loading..." : "Sign In"}</span>
                </button>
              )}

              {authenticated && !isPremium && (
                <button
                  onClick={() => { setMobileMenuOpen(false); navigate("/pricing"); }}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-violet-500/[0.08] border border-transparent hover:border-violet-400/40 transition-all"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-violet-500/15 border border-violet-400/30 flex-shrink-0">
                    <Crown className="w-4 h-4 text-violet-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Get Premium</span>
                </button>
              )}

              {authenticated && isPremium && (
                <button
                  onClick={() => { if (!trendingDisabled) { handleTrendingClick(); setMobileMenuOpen(false); } }}
                  disabled={trendingDisabled}
                  aria-disabled={trendingDisabled}
                  title={trendingDisabled ? "Trending payments are temporarily unavailable" : undefined}
                  className={`group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md border border-transparent transition-all ${
                    trendingDisabled
                      ? "opacity-50 grayscale cursor-not-allowed"
                      : "hover:bg-amber-500/[0.08] hover:border-amber-400/40"
                  }`}
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-amber-500/15 border border-amber-400/30 flex-shrink-0">
                    <Rocket className="w-4 h-4 text-amber-300" />
                  </span>
                  <span className={`text-[13px] font-semibold ${trendingDisabled ? "text-slate-400 line-through" : "text-slate-200 group-hover:text-white"}`}>
                    Get Trending
                  </span>
                </button>
              )}

              {hasQueryClient ? (
                <LandingPerformanceDialog>
                  <button className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-sky-500/[0.08] border border-transparent hover:border-sky-400/40 transition-all">
                    <span className="flex items-center justify-center w-7 h-7 rounded-md bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                      <BarChart3 className="w-4 h-4 text-sky-300" />
                    </span>
                    <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Performance</span>
                  </button>
                </LandingPerformanceDialog>
              ) : (
                <button disabled className="w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md border border-transparent opacity-50">
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                    <BarChart3 className="w-4 h-4 text-sky-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-400">Performance</span>
                </button>
              )}


              {authenticated && isPremium && (
                <button
                  onClick={() => { setMobileMenuOpen(false); handleTelegramAuth(); }}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-sky-500/[0.08] border border-transparent hover:border-sky-400/40 transition-all"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                    <svg className="w-4 h-4 text-sky-300" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.64 6.8c-.15 1.58-.8 5.42-1.13 7.19-.14.75-.42 1-.68 1.03-.58.05-1.02-.38-1.58-.75-.88-.58-1.38-.94-2.23-1.5-.99-.65-.35-1.01.22-1.59.15-.15 2.71-2.48 2.76-2.69a.2.2 0 0 0-.05-.18c-.06-.05-.14-.03-.21-.02-.09.02-1.49.95-4.22 2.79-.4.27-.76.41-1.08.4-.36-.01-1.04-.2-1.55-.37-.63-.2-1.12-.31-1.08-.66.02-.18.27-.36.74-.55 2.92-1.27 4.86-2.11 5.83-2.51 2.78-1.16 3.35-1.36 3.73-1.36.08 0 .27.02.39.12.1.08.13.19.14.27-.01.06-.01.24-.02.38z"/>
                    </svg>
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Telegram</span>
                </button>
              )}

              {authenticated && !isPremium && (
                <button
                  onClick={() => { navigate("/gembot"); setMobileMenuOpen(false); }}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-emerald-500/[0.08] border border-transparent hover:border-emerald-400/40 transition-all"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-emerald-500/15 border border-emerald-400/30 flex-shrink-0">
                    <Zap className="w-4 h-4 text-emerald-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">How It Works</span>
                </button>
              )}

              <button
                onClick={() => { navigate("/support"); setMobileMenuOpen(false); }}
                className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-teal-500/[0.08] border border-transparent hover:border-teal-400/40 transition-all"
              >
                <span className="flex items-center justify-center w-7 h-7 rounded-md bg-teal-500/15 border border-teal-400/30 flex-shrink-0">
                  <MessageCircle className="w-4 h-4 text-teal-300" />
                </span>
                <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Support</span>
              </button>

              {authenticated && isPremium && (
                <button
                  onClick={() => { setMobileMenuOpen(false); window.dispatchEvent(new CustomEvent('feed:open-trading-guide')); }}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-amber-500/[0.08] border border-transparent hover:border-amber-400/40 transition-all"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-amber-500/15 border border-amber-400/30 flex-shrink-0">
                    <BookOpen className="w-4 h-4 text-amber-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Trading Guide</span>
                </button>
              )}

              {authenticated && (
                <button
                  onClick={() => {
                    setMobileMenuOpen(false);
                    trackSidePanelItemClicked({ item: 'settings', location: 'mobile_menu', is_premium: !!isPremium });
                    trackSettingsOpened('mobile_menu');
                    window.dispatchEvent(new CustomEvent('feed:open-settings'));
                  }}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-slate-500/[0.12] border border-transparent hover:border-slate-400/40 transition-all"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-slate-500/15 border border-slate-400/30 flex-shrink-0">
                    <Settings className="w-4 h-4 text-slate-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Settings</span>
                </button>
              )}

              {authenticated && isPremium && (
                <DiscordDropdown
                  open={isMenuDiscordOpen}
                  onOpenChange={setIsMenuDiscordOpen}
                  trigger={
                    <button
                      className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-indigo-500/[0.08] border border-transparent hover:border-indigo-400/40 transition-all"
                    >
                      <span className="flex items-center justify-center w-7 h-7 rounded-md bg-indigo-500/15 border border-indigo-400/30 flex-shrink-0">
                        <DiscordIcon className="w-4 h-4 text-indigo-300" />
                      </span>
                      <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Discord</span>
                    </button>
                  }
                />
              )}

            {authenticated && isPremium && (
              <button
                onClick={() => { navigate("/rewards"); setMobileMenuOpen(false); }}
                className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-pink-500/[0.08] border border-transparent hover:border-pink-400/40 transition-all"
              >
                <span className="flex items-center justify-center w-7 h-7 rounded-md bg-pink-500/15 border border-pink-400/30 flex-shrink-0">
                  <Gift className="w-4 h-4 text-pink-300" />
                </span>
                <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Rewards</span>
              </button>
            )}


              {authenticated && ready && (
                <button
                  onClick={() => { handleLogout(); setMobileMenuOpen(false); }}
                  className="group w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-md hover:bg-rose-500/[0.08] border border-transparent hover:border-rose-400/30 transition-all mt-1"
                >
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-rose-500/15 border border-rose-400/30 flex-shrink-0">
                    <LogOut className="w-4 h-4 text-rose-300" />
                  </span>
                  <span className="text-[13px] font-semibold text-slate-200 group-hover:text-white">Sign Out</span>
                </button>
              )}

              <div className="flex flex-col gap-2 pt-3 mt-2 border-t border-white/[0.06]">
                <a
                  href="https://x.com/gembotio"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-between gap-3 px-2.5 py-2 rounded-md bg-slate-500/10 border border-slate-400/20 text-slate-200 hover:bg-slate-500/20 hover:border-slate-300/40 hover:text-white transition-all"
                  aria-label="Follow us on X"
                >
                  <span className="text-[13px] font-semibold">Follow us</span>
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-slate-500/15 border border-slate-400/30">
                    <XIcon className="w-4 h-4" />
                  </span>
                </a>
                <a
                  href="https://t.me/gembotio"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-between gap-3 px-2.5 py-2 rounded-md bg-sky-500/10 border border-sky-400/20 text-slate-200 hover:bg-sky-500/20 hover:border-sky-300/40 hover:text-white transition-all"
                  aria-label="Join the free chat on Telegram"
                >
                  <span className="text-[13px] font-semibold">Join the #1 free memecoin chat in the world</span>
                  <span className="flex items-center justify-center w-7 h-7 rounded-md bg-sky-500/15 border border-sky-400/30 text-sky-300">
                    <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.64 6.8c-.15 1.58-.8 5.42-1.13 7.19-.14.75-.42 1-.68 1.03-.58.05-1.02-.38-1.58-.75-.88-.58-1.38-.94-2.23-1.5-.99-.65-.35-1.01.22-1.59.15-.15 2.71-2.48 2.76-2.69a.2.2 0 0 0-.05-.18c-.06-.05-.14-.03-.21-.02-.09.02-1.49.95-4.22 2.79-.4.27-.76.41-1.08.4-.36-.01-1.04-.2-1.55-.37-.63-.2-1.12-.31-1.08-.66.02-.18.27-.36.74-.55 2.92-1.27 4.86-2.11 5.83-2.51 2.78-1.16 3.35-1.36 3.73-1.36.08 0 .27.02.39.12.1.08.13.19.14.27-.01.06-.01.24-.02.38z" />
                    </svg>
                  </span>
                </a>
              </div>
            </div>
          )}
        </>
      )}

      {/* Desktop Side Panel */}
      {!isMobile && (
        <aside
          className={`fixed top-0 left-0 h-full z-50 flex flex-col overflow-y-auto overflow-x-hidden transition-all duration-300 ease-in-out ${
            panelOpen ? "w-36" : "w-12"
          } bg-[#05070E] border-r border-white/[0.06]`}
        >
          {/* Header — expanded: brand lifted to sit on the same line as the
              content column headers (COIN / MARKET CAP / …); collapse toggle
              pinned top-right above it. Collapsed: gem on top, toggle beneath. */}
          {panelOpen ? (
            <div className="flex items-center justify-between gap-2 px-2 pt-2 pb-4">
              <button onClick={() => navigate("/")} className="flex items-center gap-1.5 min-w-0" aria-label="Home">
                <Gem className="w-6 h-6 text-emerald-400 flex-shrink-0" />
                <span className="text-base font-bold text-white whitespace-nowrap tracking-tight">Gem Bot</span>
              </button>
              <button
                onClick={() => setPanelOpen(!panelOpen)}
                className="flex items-center justify-center w-5 h-5 rounded-md bg-white/[0.05] border border-white/[0.07] text-slate-400 hover:text-white hover:bg-white/[0.08] transition-colors flex-shrink-0"
                aria-label="Collapse panel"
                title="Collapse"
              >
                <PanelLeftClose className="w-3 h-3" />
              </button>
            </div>
          ) : (
            <div className="flex flex-col items-center gap-3 py-4">
              <button onClick={() => navigate("/")} className="flex items-center justify-center min-w-0" aria-label="Home">
                <Gem className="w-6 h-6 text-emerald-400 flex-shrink-0" />
              </button>
              <button
                onClick={() => setPanelOpen(!panelOpen)}
                className="flex items-center justify-center w-5 h-5 rounded-md bg-white/[0.05] border border-white/[0.07] text-slate-400 hover:text-white hover:bg-white/[0.08] transition-colors"
                aria-label="Expand panel"
                title="Expand"
              >
                <PanelLeftOpen className="w-3 h-3" />
              </button>
            </div>
          )}

          {/* ───── MENU ───── */}
          <section className="px-2 flex flex-col gap-1">
            {asideGroupLabel("Menu")}

            {!(authenticated && isPremium) && (
              <GetPremiumPromoCard
                onNavigate={authenticated ? () => navigate("/pricing") : handleLoginForPremium}
                expanded={panelOpen}
                side="right"
                triggerMode="hover-and-click"
              >
                <button
                  className={`group relative w-full flex items-center rounded-md bg-transparent hover:bg-violet-500/[0.16] border border-transparent hover:border-violet-400/30 transition-all duration-200 ${panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"}`}
                  title={!panelOpen ? "Get Premium" : undefined}
                >
                  <span className="flex items-center justify-center w-5 h-5 rounded-md bg-violet-500/20 border border-violet-400/40 flex-shrink-0">
                    <Crown className="w-3 h-3 text-violet-300 fill-violet-400/40" />
                  </span>
                  {panelOpen && <span className="flex-1 text-left text-[11px] font-semibold tracking-tight text-slate-200 group-hover:text-violet-100 transition-colors">Get Premium</span>}
                </button>
              </GetPremiumPromoCard>
            )}

            {/* Filter removed from the desktop sidebar — its sorting job moved to
                the "Sort by" dropdown above the trending table. (Mobile keeps the
                Filter control.) */}

            {authenticated && ready && isPremium && (
              <button onClick={() => navigate("/feed")} className={asideItemCls(false)} title={!panelOpen ? "Feed" : undefined}>
                <span className={asideBoxCls(false)}><Rss className={asideIconCls(false)} /></span>
                {panelOpen && <span className={asideLabelCls(false)}>Feed</span>}
              </button>
            )}

            {/* Trending — the current page, so always shown active, in the same
                monochrome (tone-not-hue) active treatment as every other item. */}
            {authenticated && ready && isPremium && (
              <button
                onClick={() => navigate("/")}
                aria-current="page"
                className={asideItemCls(true)}
                title={!panelOpen ? "Trending" : undefined}
              >
                <span className={asideBoxCls(true)}><Flame className={asideIconCls(true)} /></span>
                {panelOpen && <span className={asideLabelCls(true)}>Trending</span>}
              </button>
            )}

            {hasQueryClient && (
              <LandingPerformanceDialog>
                <button className={asideItemCls(false)} title={!panelOpen ? "Performance" : undefined}>
                  <span className={asideBoxCls(false)}><BarChart3 className={asideIconCls(false)} /></span>
                  {panelOpen && <span className={asideLabelCls(false)}>Performance</span>}
                </button>
              </LandingPerformanceDialog>
            )}
          </section>

          {/* ───── RESOURCES ───── */}
          <section className="px-2 flex flex-col gap-1">
            {asideGroupLabel("Resources")}

            {authenticated && isPremium ? (
              <button onClick={() => window.dispatchEvent(new CustomEvent('feed:open-trading-guide'))} className={asideItemCls(false)} title={!panelOpen ? "Trading Guide" : undefined}>
                <span className={asideBoxCls(false)}><BookOpen className={asideIconCls(false)} /></span>
                {panelOpen && <span className={asideLabelCls(false)}>Trading Guide</span>}
              </button>
            ) : (
              <button onClick={() => navigate("/gembot")} className={asideItemCls(false)} title={!panelOpen ? "How It Works" : undefined}>
                <span className={asideBoxCls(false)}><BookOpen className={asideIconCls(false)} /></span>
                {panelOpen && <span className={asideLabelCls(false)}>How It Works</span>}
              </button>
            )}

            <Popover>
              <PopoverTrigger asChild>
                <button className={asideItemCls(false)} title={!panelOpen ? "Support" : undefined}>
                  <span className={asideBoxCls(false)}><MessageCircle className={asideIconCls(false)} /></span>
                  {panelOpen && <span className={asideLabelCls(false)}>Support</span>}
                </button>
              </PopoverTrigger>
              <PopoverContent side="right" align="start" className="w-48 p-2 bg-slate-900 border-white/[0.08]">
                <div className="space-y-1">
                  <button onClick={() => window.open('https://t.me/x100xgemfinder', '_blank', 'noopener,noreferrer')} className="w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm text-slate-200 hover:bg-slate-800 transition-colors">
                    <svg className="w-3.5 h-3.5 text-slate-400" viewBox="0 0 24 24" fill="currentColor"><path d={asideTgPath} /></svg>
                    <span>Support 1</span>
                  </button>
                  <button onClick={() => window.open('https://t.me/pinmachine1', '_blank', 'noopener,noreferrer')} className="w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm text-slate-200 hover:bg-slate-800 transition-colors">
                    <svg className="w-3.5 h-3.5 text-slate-400" viewBox="0 0 24 24" fill="currentColor"><path d={asideTgPath} /></svg>
                    <span>Support 2</span>
                  </button>
                </div>
              </PopoverContent>
            </Popover>
          </section>

          {/* ───── COMMUNITY ───── */}
          <section className="px-2">
            {asideGroupLabel("Community")}
            <div className={panelOpen ? "flex items-center gap-1.5 px-2 py-1" : "flex flex-col items-center gap-1.5"}>
              <a href="https://x.com/gembotio" target="_blank" rel="noopener noreferrer" className={asideSocialCls} aria-label="X (Twitter)" title="X">
                <XIcon className="w-3 h-3 text-slate-400 group-hover:text-white" />
              </a>
              {authenticated && isPremium ? (
                <DiscordDropdown open={isDiscordOpen} onOpenChange={setIsDiscordOpen} trigger={
                  <button className={asideSocialCls} aria-label="Discord" title="Discord"><DiscordIcon className="w-3 h-3 text-slate-400 group-hover:text-white" /></button>
                } />
              ) : null}
              {authenticated && isPremium ? (
                <TelegramDropdown open={isTelegramOpen} onOpenChange={setIsTelegramOpen} botLink={telegramBotLink} botUsername={telegramBotUsername} telegramTag={telegramDisplayText} isLinked={isTelegramLinked} onConnect={handleTelegramAuth} onRemove={handleTelegramRemove} trigger={
                  <button className={asideSocialCls} aria-label="Telegram" title="Telegram"><svg className="w-3 h-3 text-slate-400 group-hover:text-white" viewBox="0 0 24 24" fill="currentColor"><path d={asideTgPath} /></svg></button>
                } />
              ) : (
                <a href="https://t.me/gembotio" target="_blank" rel="noopener noreferrer" className={asideSocialCls} aria-label="Telegram" title="Telegram">
                  <svg className="w-3 h-3 text-slate-400 group-hover:text-white" viewBox="0 0 24 24" fill="currentColor"><path d={asideTgPath} /></svg>
                </a>
              )}
            </div>
          </section>

          {/* Updates — the one live element, so it sits with the top "app" block
              directly under Community (capped at 3; reuses the trending socket;
              shown for everyone; self-hides when collapsed/empty). */}
          <LiveStatusPanel expanded={panelOpen} />

          {/* spacer — all the slack collects here, between the live content above
              and the pinned Rewards + Account sections below. */}
          <div className="flex-1 min-h-4" />

          {/* Upgrades (Earn Rewards unlock tiers, monochrome) + the themed
              "Invite friends" CTA — shown for non-premium (incl. signed out). */}
          <UnlockFeaturesStrip expanded={panelOpen} authenticated={!!authenticated} isPremium={!!isPremium} />

          {/* ───── REWARDS ───── (premium; non-premium get Invite friends above)
              Its own section so the label reads like Menu / Resources / Community,
              with the gift icon + a plain white "Refer & Earn" label below it. */}
          {authenticated && isPremium && (
            <section className="px-2 flex flex-col gap-1">
              {/* Label only when expanded — no collapsed separator above Rewards. */}
              {panelOpen && asideGroupLabel("Rewards")}
              {panelOpen ? (
                <button onClick={() => navigate("/rewards")} className={asideItemCls(false)} title="Refer & Earn">
                  <span className={asideBoxCls(false)}><Gift className={asideIconCls(false)} /></span>
                  <span className={`${asideLabelCls(false)} min-w-0 whitespace-nowrap overflow-hidden text-ellipsis`}>Refer &amp; Earn</span>
                </button>
              ) : (
                <button onClick={() => navigate("/rewards")} className={asideItemCls(false)} aria-label="Refer & Earn" title="Refer & Earn">
                  <span className={asideBoxCls(false)}><Gift className={asideIconCls(false)} /></span>
                </button>
              )}
            </section>
          )}

          {/* ───── ACCOUNT ───── */}
          <section className="px-2 pb-4 flex flex-col gap-1">
            {asideGroupLabel("Account")}

            {authenticated && (
              <button
                onClick={() => {
                  const loc = panelOpen ? 'side_panel_expanded' : 'side_panel_collapsed';
                  trackSidePanelItemClicked({ item: 'settings', location: loc, is_premium: !!isPremium });
                  trackSettingsOpened(loc);
                  window.dispatchEvent(new CustomEvent('feed:open-settings'));
                }}
                className={asideItemCls(false)}
                title={!panelOpen ? "Settings" : undefined}
              >
                <span className={asideBoxCls(false)}><Settings className={asideIconCls(false)} /></span>
                {panelOpen && <span className={asideLabelCls(false)}>Settings</span>}
              </button>
            )}

            {!(authenticated && ready) ? (
              <button onClick={handleLogin} disabled={!ready} className={`${asideItemCls(false)} disabled:opacity-50`} title={!panelOpen ? "Sign In" : undefined}>
                <span className={asideBoxCls(false)}><LogIn className={asideIconCls(false)} /></span>
                {panelOpen && <span className={asideLabelCls(false)}>{!ready ? "Loading..." : "Sign In"}</span>}
              </button>
            ) : panelOpen ? (
              <div className="flex items-center gap-2 px-2 py-1.5">
                <span className="flex items-center justify-center w-5 h-5 rounded-full bg-white/[0.08] text-slate-200 text-[9px] font-bold flex-shrink-0">{asideAccountInitial}</span>
                <span className="flex-1 min-w-0">
                  <span className="block text-[11px] font-semibold text-slate-200 truncate">{asideAccountHandle}</span>
                </span>
                <button onClick={handleLogout} className="flex items-center justify-center w-5 h-5 text-slate-400 hover:text-white transition-colors flex-shrink-0" aria-label="Sign out" title="Sign out"><LogOut className="w-3.5 h-3.5" /></button>
              </div>
            ) : (
              <button onClick={handleLogout} className={asideItemCls(false)} aria-label="Sign out" title="Sign out">
                {/* Monochrome account avatar — a circle on the same raised surface
                    as the rail icon boxes (circle = identity vs the rounded-square
                    nav icons), bright initial, no colour. */}
                <span className="flex items-center justify-center w-5 h-5 rounded-full bg-white/[0.05] shadow-[inset_0_0_0_1px_rgba(255,255,255,0.05)] text-[#F4F6F8] text-[9px] font-semibold flex-shrink-0">{asideAccountInitial}</span>
              </button>
            )}
          </section>
        </aside>
      )}

      {/* Main content */}
      <div
        className={`relative z-10 flex-1 min-h-0 h-[calc(100dvh-52px)] md:h-screen overscroll-y-none transition-all duration-300 ease-in-out flex flex-col ${
          isMobile
            ? "overflow-hidden pb-[env(safe-area-inset-bottom)]"
            : "overflow-y-auto pb-[env(safe-area-inset-bottom)]"
        } ${
          isMobile ? "mt-[52px] ml-0" : panelOpen ? "ml-36" : "ml-12"
        }`}
      >
          <TrendingTable
            isPremium={!!(authenticated && isPremium)}
            sort={trendingSort}
            onSortChange={setTrendingSort}
            onUpgrade={authenticated ? () => navigate("/pricing") : handleLoginForPremium}
            listSize={authenticated && isPremium ? trendingListSize : undefined}
            bottomBar={!!authenticated && isMobile}
          />
      </div>

      {/* Mobile bottom nav dock — shown to every signed-in user on trending for
          parity with /feed. Search is locked for free users until charting
          opens up to them. Performance/Search toggle via controlled state so a
          second tap closes them. */}
      {isMobile && authenticated && (
        <>
          <MobileNavDock
            currentPage="trending"
            searchOpen={searchOpen}
            onSearchOpenChange={setSearchOpen}
            searchEnabled={!!isPremium}
            performanceOpen={performanceOpen}
            onPerformanceOpenChange={setPerformanceOpen}
          />
          {isPremium && (
            <HistoricalCallsSearchDialog
              open={searchOpen}
              onOpenChange={setSearchOpen}
              isPremium={!!isPremium}
              onUpsell={() => { setSearchOpen(false); navigate('/pricing'); }}
            />
          )}
        </>
      )}

      <Dialog open={telegramDialogOpen} onOpenChange={setTelegramDialogOpen}>
        {telegramStep === 'username' && (
          <TelegramUsernameForm
            onAccountSubmit={handleAccountSubmit}
            isLoading={isLinkingUsername}
          />
        )}
        {telegramStep === 'bot-select' && telegramDisplayText && (
          <TelegramBotSelector
            currentBotUsername={planData?.telegramBotUsername || undefined}
            telegramTag={telegramDisplayText}
            onBotSelect={handleBotSelect}
            onEditUsername={handleEditUsername}
          />
        )}
        {telegramStep === 'instructions' && selectedBotUsername && telegramDisplayText && (
          <TelegramBotInstructions
            botUsername={selectedBotUsername}
            telegramTag={telegramDisplayText}
            onComplete={handleInstructionsComplete}
          />
        )}
      </Dialog>
    </main>
  );
};

export default Landing;
