import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Gem, LogOut, Zap, Rocket, BarChart3, LogIn, MessageCircle, PanelLeftClose, Menu, X, Rss, Crown, Gift } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useAuth } from "@/hooks/useAuth";
import { useIsMobile } from "@/hooks/use-mobile";
import { usePlanData } from "@/hooks/usePlanData";
import { LoadingBar } from "@/components/routing/LoadingBar";
import { OAuthRedirectHandler } from "@/components/auth/OAuthRedirectHandler";
import { TrendingTable } from "@/components/trending/TrendingTable";
import {
  TrendingFiltersPopover,
  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 TrendingPromoCard from "@/components/landing/TrendingPromoCard";
import { isTrendingAllowedEmail } from "@/config/trendingAllowlist";
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 { DiscordAccess } from "@/components/discord/DiscordAccess";
import { TelegramDropdown } from "@/components/feed/TelegramDropdown";
import { TelegramUsernameForm } from "@/components/telegram/TelegramUsernameForm";
import { TelegramBotSelector } from "@/components/telegram/TelegramBotSelector";
import { TelegramBotInstructions } from "@/components/telegram/TelegramBotInstructions";
import { useTelegramHandlers } from "@/hooks/useTelegramHandlers";

import { logger } from "@/services/logger";
import { trackMobileLandingDwell } 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, planData, refetch: refetchPlanData } = usePlanData();
  const isMobile = useIsMobile();

  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState(0);
  const [loadingMessage, setLoadingMessage] = useState("");
  const [panelOpen, setPanelOpen] = useState(true);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [isTelegramOpen, setIsTelegramOpen] = useState(false);
  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
  useEffect(() => {
    if (!ready || !authenticated || isLoggingOut) return;
    const intent = sessionStorage.getItem("gembot-post-login-intent");
    if (intent === "pricing") {
      sessionStorage.removeItem("gembot-post-login-intent");
      navigate("/pricing", { replace: true });
    }
  }, [ready, authenticated, isLoggingOut, 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} />;
  }

  return (
    <main className="h-screen 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 items-center justify-between px-3 py-1.5 bg-[#05070E] border-b border-white/[0.06]">
            <div className="flex items-center">
              <Gem className="w-5 h-5 text-emerald-400" />
            </div>
            <div className="flex items-center gap-1.5">
              {authenticated && isPremium ? (
                <button
                  onClick={() => navigate("/feed")}
                  className="group flex items-center gap-1 px-1.5 h-6 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-4 h-4 rounded bg-emerald-500/15 border border-emerald-400/30 flex-shrink-0">
                    <Rss className="w-2.5 h-2.5 text-emerald-300" />
                  </span>
                  <span className="text-[10px] font-semibold text-slate-200 group-hover:text-white">Early Calls</span>
                </button>
              ) : (
                <GetPremiumPromoCard
                  onNavigate={authenticated ? () => navigate("/pricing") : handleLoginForPremium}
                  side="bottom"
                  triggerMode="click"
                >
                  <button
                    className="group flex items-center gap-1 px-1.5 h-6 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-4 h-4 rounded bg-violet-500/15 border border-violet-400/30 flex-shrink-0">
                      <Crown className="w-2.5 h-2.5 text-violet-300 fill-violet-400/40" />
                    </span>
                    <span className="text-[10px] font-semibold text-slate-200 group-hover:text-white">Get Premium</span>
                  </button>
                </GetPremiumPromoCard>
              )}
              {authenticated && isPremium && (
                <TrendingFiltersPopover
                  expanded={true}
                  sort={trendingSort}
                  onChange={setTrendingSort}
                  listSize={trendingListSize}
                  onListSizeChange={setTrendingListSize}
                  mobile={true}
                />
              )}
              {!(authenticated && isPremium) && (
                authenticated && hasQueryClient ? (
                  <LandingPerformanceDialog>
                    <button className="group flex items-center gap-1 px-1.5 h-6 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-4 h-4 rounded bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                        <BarChart3 className="w-2.5 h-2.5 text-sky-300" />
                      </span>
                      <span className="text-[10px] 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-6 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-4 h-4 rounded bg-emerald-500/15 border border-emerald-400/30 flex-shrink-0">
                        <Zap className="w-2.5 h-2.5 text-emerald-300" />
                      </span>
                      <span className="text-[10px] 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-6 rounded-md bg-slate-500/15 border border-slate-400/30 hover:bg-slate-500/25 hover:border-slate-300/50 transition-all"
                aria-label={mobileMenuOpen ? "Close menu" : "Open menu"}
              >
                <span className="text-[10px] font-semibold text-slate-100">More</span>
                {mobileMenuOpen ? <X className="w-3 h-3 text-slate-100" /> : <Menu className="w-3 h-3 text-slate-100" />}
              </button>
            </div>
          </header>

          {mobileMenuOpen && (
            <div className="fixed top-[46px] left-0 right-0 z-50 bg-[#05070E] border-b border-white/[0.06] px-3 py-3 flex flex-col gap-1 max-h-[calc(100vh-46px)] 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 && (
                <Dialog>
                  <DialogTrigger asChild>
                    <button
                      onClick={() => setMobileMenuOpen(false)}
                      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">Premium Discord</span>
                    </button>
                  </DialogTrigger>
                  <DialogContent className="max-w-md">
                    <DialogHeader>
                      <DialogTitle className="text-white">Discord Access</DialogTitle>
                    </DialogHeader>
                    <DiscordAccess />
                  </DialogContent>
                </Dialog>
            )}

            {authenticated && isPremium && (
              <button
                onClick={() => navigate("/rewards")}
                className={`group w-full flex items-center rounded-md hover:bg-pink-500/[0.08] border border-transparent hover:border-pink-400/40 transition-all duration-200 ${
                  panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                }`}
              >
                <span className="flex items-center justify-center w-5 h-5 rounded-md bg-pink-500/15 border border-pink-400/30 flex-shrink-0">
                  <Gift className="w-3 h-3 text-pink-300" />
                </span>
                {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">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 transition-all duration-300 ease-in-out ${
            panelOpen ? "w-36" : "w-12"
          } bg-[#05070E] border-r border-white/[0.06]`}
        >
          <div className={`flex ${panelOpen ? "items-center px-3 py-6 gap-2" : "flex-col items-center py-5"}`}>
            <Gem className="w-7 h-7 text-emerald-400 flex-shrink-0" />
            {panelOpen && <span className="text-lg font-bold text-white whitespace-nowrap tracking-tight">Gem Bot</span>}
          </div>

          <nav className="flex flex-col gap-1 px-2">
            {!(authenticated && ready) && (
              <button
                onClick={handleLogin}
                disabled={!ready}
                className={`group w-full flex items-center rounded-md hover:bg-cyan-500/[0.08] border border-transparent hover:border-cyan-400/40 transition-all duration-200 disabled:opacity-50 ${
                  panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                }`}
              >
                <span className="flex items-center justify-center w-5 h-5 rounded-md bg-cyan-500/15 border border-cyan-400/30 flex-shrink-0">
                  <LogIn className="w-3 h-3 text-cyan-300" />
                </span>
                {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">{!ready ? "Loading..." : "Sign In"}</span>}
              </button>
            )}

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

            {authenticated && isPremium && (
              <TrendingFiltersPopover
                expanded={panelOpen}
                sort={trendingSort}
                onChange={setTrendingSort}
                listSize={trendingListSize}
                onListSizeChange={setTrendingListSize}
              />
            )}

            {authenticated && ready && isPremium && (
              <button
                onClick={() => navigate("/feed")}
                className={`group w-full flex items-center rounded-md hover:bg-emerald-500/[0.08] border border-transparent hover:border-emerald-400/40 transition-all duration-200 ${
                  panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                }`}
              >
                <span className="flex items-center justify-center w-5 h-5 rounded-md bg-emerald-500/15 border border-emerald-400/30 flex-shrink-0">
                  <Rss className="w-3 h-3 text-emerald-300" />
                </span>
                {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">Early Calls</span>}
              </button>
            )}

            {authenticated && isPremium && hasQueryClient && (
              <LandingPerformanceDialog>
                <button
                  className={`group w-full flex items-center rounded-md hover:bg-sky-500/[0.08] border border-transparent hover:border-sky-400/40 transition-all duration-200 ${
                    panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                  }`}
                >
                  <span className="flex items-center justify-center w-5 h-5 rounded-md bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                    <BarChart3 className="w-3 h-3 text-sky-300" />
                  </span>
                  {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">Performance</span>}
                </button>
              </LandingPerformanceDialog>
            )}

            {authenticated && isPremium && (
              <Dialog>
                <DialogTrigger asChild>
                  <button
                    className={`group w-full flex items-center rounded-md hover:bg-indigo-500/[0.08] border border-transparent hover:border-indigo-400/40 transition-all duration-200 ${
                      panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                    }`}
                  >
                    <span className="flex items-center justify-center w-5 h-5 rounded-md bg-indigo-500/15 border border-indigo-400/30 flex-shrink-0">
                      <DiscordIcon className="w-3 h-3 text-indigo-300" />
                    </span>
                    {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">Discord</span>}
                  </button>
                </DialogTrigger>
                <DialogContent className="max-w-md">
                  <DialogHeader>
                    <DialogTitle className="text-white">Discord Access</DialogTitle>
                  </DialogHeader>
                  <DiscordAccess />
                </DialogContent>
              </Dialog>
            )}

            {authenticated && isPremium && (
              <TelegramDropdown
                open={isTelegramOpen}
                onOpenChange={setIsTelegramOpen}
                botLink={telegramBotLink}
                botUsername={telegramBotUsername}
                telegramTag={telegramDisplayText}
                isLinked={isTelegramLinked}
                onConnect={handleTelegramAuth}
                onRemove={handleTelegramRemove}
                trigger={
                  <button
                    className={`group w-full flex items-center rounded-md hover:bg-sky-500/[0.08] border border-transparent hover:border-sky-400/40 transition-all duration-200 ${
                      panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                    }`}
                  >
                    <span className="flex items-center justify-center w-5 h-5 rounded-md bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                      <svg className="w-3 h-3 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>
                    {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">Telegram</span>}
                  </button>
                }
              />
            )}


            {!(authenticated && isPremium) && (
              <EarlyCallsPromoCard
                onNavigate={() => navigate("/gembot")}
                expanded={panelOpen}
              />
            )}

            {!(authenticated && isPremium) && hasQueryClient && (
              <LandingPerformanceDialog>
                <button
                  className={`group w-full flex items-center rounded-md hover:bg-sky-500/[0.08] border border-transparent hover:border-sky-400/40 transition-all duration-200 ${
                    panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                  }`}
                >
                  <span className="flex items-center justify-center w-5 h-5 rounded-md bg-sky-500/15 border border-sky-400/30 flex-shrink-0">
                    <BarChart3 className="w-3 h-3 text-sky-300" />
                  </span>
                  {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">Performance</span>}
                </button>
              </LandingPerformanceDialog>
            )}

            <Popover>
              <PopoverTrigger asChild>
                <button
                  className={`group w-full flex items-center rounded-md hover:bg-slate-500/[0.12] border border-transparent hover:border-slate-400/40 transition-all duration-200 ${
                    panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                  }`}
                >
                  <span className="flex items-center justify-center w-5 h-5 rounded-md bg-teal-500/15 border border-teal-400/30 flex-shrink-0">
                    <MessageCircle className="w-3 h-3 text-teal-300" />
                  </span>
                  {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">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-sky-400" 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>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-sky-400" 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>Support 2</span>
                  </button>
                </div>
              </PopoverContent>
            </Popover>

            {authenticated && isPremium && (
              <TrendingPromoCard
                onNavigate={handleTrendingClick}
                expanded={panelOpen}
                disabled={trendingDisabled}
              />
            )}

            {authenticated && ready && (
              <button
                onClick={handleLogout}
                className={`group w-full flex items-center rounded-md hover:bg-rose-500/[0.08] border border-transparent hover:border-rose-400/30 transition-all duration-200 mt-1 ${
                  panelOpen ? "gap-2 px-2 py-1.5" : "justify-center py-1.5"
                }`}
              >
                <span className="flex items-center justify-center w-5 h-5 rounded-md bg-rose-500/15 border border-rose-400/30 flex-shrink-0">
                  <LogOut className="w-3 h-3 text-rose-300" />
                </span>
                {panelOpen && <span className="text-[11px] font-semibold text-slate-200 group-hover:text-white tracking-tight">Sign Out</span>}
              </button>
            )}
          </nav>

          <UnlockFeaturesStrip expanded={panelOpen} authenticated={!!authenticated} isPremium={!!isPremium} />

          <div className="flex-1 min-h-4" />
          <PremiumRewardsStrip expanded={panelOpen} authenticated={!!authenticated} isPremium={!!isPremium} />
          <div className="flex-1 min-h-4" />

          <LiveStatusPanel expanded={panelOpen} withTopBorder={!!(authenticated && isPremium)} />

          <div className={`flex items-center ${panelOpen ? "justify-center gap-3" : "flex-col gap-2 items-center"} px-2 pb-4 pt-2`}>
            <button
              onClick={() => setPanelOpen(!panelOpen)}
              className="text-slate-300 hover:text-white transition-colors"
              aria-label={panelOpen ? "Collapse panel" : "Expand panel"}
            >
              <PanelLeftClose className={`w-4 h-4 ${!panelOpen ? "rotate-180" : ""}`} />
            </button>
            <a href="https://x.com/gembotio" target="_blank" rel="noopener noreferrer" className="text-slate-300 hover:text-white transition-colors" aria-label="Follow us on X">
              <XIcon className="w-4 h-4" />
            </a>
            <a href="https://t.me/gembotio" target="_blank" rel="noopener noreferrer" className="text-slate-300 hover:text-white transition-colors" aria-label="Join us on Telegram">
              <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>
            </a>
          </div>
        </aside>
      )}

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