window.createInverseArenaModule = function createInverseArenaModule(deps) {
  const { useState, useEffect, useMemo, useRef } = React;
  const {
    apiRequest,
    safeText,
    getSavedSiteTheme,
    ensureSiteThemeStyles,
    applySiteThemeToDocument,
    BrandHomeLink,
    SiteHeaderNav,
    HeaderProfileButton,
    ThemeToggleButton,
    HELVETICA_STYLE,
    ArrowUpRight,
    buildNewsTickerItems,
    NewsTicker,
    MagnifierIcon,
    ArrowRight,
    GithubMark,
    normalizeFoundResponse,
    normalizeGeneratedSkillResponse,
    MinimalResult,
    trackVisitorEvent,
    Copy,
  } = deps || {};
  function DashboardPage() {
    const initialHackerView = (() => {
      try {
        const params = new URLSearchParams(window.location.search || "");
        return params.get("theme") === "hacker";
      } catch (_err) {
        return false;
      }
    })();
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    const [rows, setRows] = useState([]);
    const [rankingIndex, setRankingIndex] = useState({});
    const [expandedCards, setExpandedCards] = useState({});
    const [expandedSections, setExpandedSections] = useState({});
    const [queryInput, setQueryInput] = useState("");
    const [hackerView, setHackerView] = useState(initialHackerView);
    const [tickerData, setTickerData] = useState([]);
    const [queryResult, setQueryResult] = useState(null);
    const [queryError, setQueryError] = useState("");
    const [requestRunning, setRequestRunning] = useState(false);
    const [showCliSignup, setShowCliSignup] = useState(false);
    const [cliSignupBusy, setCliSignupBusy] = useState(false);
    const [cliSignupError, setCliSignupError] = useState("");
    const [cliSignupDone, setCliSignupDone] = useState(false);
    const [cliName, setCliName] = useState("");
    const [cliEmail, setCliEmail] = useState("");
    const [cliKey, setCliKey] = useState("");
    const [siteTheme, setSiteTheme] = useState(() => (typeof getSavedSiteTheme === "function" ? getSavedSiteTheme() : "dark"));
    const abortRef = useRef(null);
    const cliPlaceholderCommand = "npx -y --package https://approxination.com/cli/latest/approx.tgz approx init <API Key>";
    const cliCommand = cliKey
      ? `npx -y --package https://approxination.com/cli/latest/approx.tgz approx init ${cliKey}`
      : "";
    const cliSkillInstruction = `install ${window.location.origin}/Skill.md`;

    useEffect(() => {
      if (typeof ensureSiteThemeStyles === "function") {
        ensureSiteThemeStyles();
      }
      if (typeof applySiteThemeToDocument === "function") {
        applySiteThemeToDocument(siteTheme);
      }
      try {
        localStorage.setItem("approx_site_theme", siteTheme);
      } catch (_err) {
        // ignore storage issues
      }
    }, [siteTheme]);

    useEffect(() => {
      const syncTheme = () => {
        if (typeof getSavedSiteTheme === "function") {
          setSiteTheme(getSavedSiteTheme());
        }
      };
      window.addEventListener("storage", syncTheme);
      return () => window.removeEventListener("storage", syncTheme);
    }, []);

    useEffect(() => {
      if (typeof trackVisitorEvent === "function") {
        trackVisitorEvent("page_view", { surface: "inverse_arena" });
      }
      let cancelled = false;
      const load = async () => {
        setLoading(true);
        setError("");
        try {
          const data = await apiRequest("/dashboard/data");
          if (cancelled) return;
          setRows(Array.isArray(data?.rows) ? data.rows : []);
          const rankings = Array.isArray(data?.rankings) ? data.rankings : [];
          setTickerData(rankings);
          const idx = {};
          for (const r of rankings) {
            const tool = safeText(r?.tool, "");
            if (!tool) continue;
            idx[tool] = Number(r?.appearances || 0);
          }
          setRankingIndex(idx);
        } catch (err) {
          if (cancelled) return;
          setError(safeText(err?.message, "Failed to load dashboard data."));
        } finally {
          if (!cancelled) setLoading(false);
        }
      };
      load();
      return () => {
        cancelled = true;
      };
    }, []);

    const groupedData = useMemo(() => {
      const groups = {};
      for (const row of rows) {
        const section = safeText(row?.section, "Uncategorized");
        const qText = safeText(row?.question, "Untitled question");
        const qNum = Number(row?.question_number ?? 0);
        if (!groups[section]) groups[section] = {};
        if (!groups[section][qText]) {
          groups[section][qText] = { number: qNum, text: qText, tools: [] };
        }
        groups[section][qText].tools.push({
          rank: Number(row?.rank ?? 999),
          tool: safeText(row?.tool, "Unknown Tool"),
          score: Number.isFinite(Number(row?.score)) ? Number(row.score) : 0,
          elo: Number.isFinite(Number(row?.elo)) ? Number(row.elo) : 1500,
          url: safeText(row?.url, "#"),
        });
      }

      Object.keys(groups).forEach((section) => {
        Object.keys(groups[section]).forEach((qText) => {
          groups[section][qText].tools.sort((a, b) => {
            const eloDiff =
              (Number.isFinite(Number(b?.elo)) ? Number(b.elo) : 1500) -
              (Number.isFinite(Number(a?.elo)) ? Number(a.elo) : 1500);
            if (eloDiff !== 0) return eloDiff;
            const scoreDiff =
              (Number.isFinite(Number(b?.score)) ? Number(b.score) : 0) -
              (Number.isFinite(Number(a?.score)) ? Number(a.score) : 0);
            if (scoreDiff !== 0) return scoreDiff;
            return (Number(a?.rank) || 999) - (Number(b?.rank) || 999);
          });
        });
      });

      return groups;
    }, [rows]);

    const sectionEntries = useMemo(() => {
      return Object.entries(groupedData)
        .map(([section, questions]) => {
          const questionItems = Object.values(questions || {}).sort((a, b) => {
            const numberCmp = Number(a?.number || 0) - Number(b?.number || 0);
            if (numberCmp !== 0) return numberCmp;
            return safeText(a?.text, "").localeCompare(safeText(b?.text, ""));
          });
          const toolSet = new Set();
          let highestElo = 0;
          for (const item of questionItems) {
            const tools = Array.isArray(item?.tools) ? item.tools : [];
            for (const tool of tools) {
              const name = safeText(tool?.tool, "");
              if (name) toolSet.add(name);
              const elo = Number.isFinite(Number(tool?.elo)) ? Number(tool.elo) : 0;
              if (elo > highestElo) highestElo = elo;
            }
          }
          return [section, {
            questionsMap: questions,
            questionItems,
            questionCount: questionItems.length,
            toolCount: toolSet.size,
            highestElo,
          }];
        })
        .sort((a, b) => {
          const aMeta = a[1] || {};
          const bMeta = b[1] || {};
          if (Number(bMeta.questionCount || 0) !== Number(aMeta.questionCount || 0)) {
            return Number(bMeta.questionCount || 0) - Number(aMeta.questionCount || 0);
          }
          return String(a[0]).localeCompare(String(b[0]));
        });
    }, [groupedData]);
    const tickerItems = useMemo(() => {
      if (typeof buildNewsTickerItems !== "function") return [];
      return buildNewsTickerItems(tickerData, 10);
    }, [tickerData]);

    useEffect(() => {
      if (sectionEntries.length === 0) return;
      setExpandedSections((prev) => {
        const allowed = new Set(sectionEntries.map(([section]) => String(section)));
        const next = {};
        for (const [key, value] of Object.entries(prev)) {
          if (allowed.has(String(key)) && Boolean(value)) {
            next[key] = true;
          }
        }
        if (Object.keys(next).length > 0) return next;
        return { [sectionEntries[0][0]]: true };
      });
    }, [sectionEntries]);

    useEffect(() => () => abortRef.current?.abort(), []);

    useEffect(() => {
      const syncCliAccountState = () => {
        const savedToken = localStorage.getItem("approx_auth_token") || "";
        const savedKey = localStorage.getItem("approx_registration_key") || "";
        if (savedToken && savedKey) {
          setCliKey(savedKey);
          setCliSignupDone(true);
        }
      };
      syncCliAccountState();
      window.addEventListener("storage", syncCliAccountState);
      return () => {
        window.removeEventListener("storage", syncCliAccountState);
      };
    }, []);

    const runInlineQuery = async () => {
      const query = String(queryInput || "").trim();
      if (!query) {
        setQueryError("Please enter a query.");
        return;
      }
      if (typeof apiRequest !== "function" || typeof normalizeGeneratedSkillResponse !== "function") {
        setQueryError("Query experience is not available on this page right now.");
        return;
      }

      setQueryError("");
      setRequestRunning(true);
      if (typeof trackVisitorEvent === "function") {
        trackVisitorEvent("query_submit", { surface: "inverse_arena", query_preview: query.slice(0, 120) });
      }
      abortRef.current?.abort();
      const controller = new AbortController();
      abortRef.current = controller;

      try {
        const authToken = localStorage.getItem("approx_auth_token") || "";
        const raw = await apiRequest("/skills/generate", {
          method: "POST",
          token: authToken,
          body: {
            query,
            limit: 10,
          },
        });
        setQueryResult(normalizeGeneratedSkillResponse(raw, query));
      } catch (err) {
        const message = err?.name === "AbortError"
          ? "Request timed out. Try again."
          : safeText(err?.message, "Request failed.");
        setQueryError(message);
      } finally {
        setRequestRunning(false);
      }
    };

    const openMainApp = () => {
      window.location.href = "/?app=1&auth=1";
    };
    const openProfile = () => {
      const hasAuth = Boolean(localStorage.getItem("approx_auth_token") || "");
      window.location.href = hasAuth ? "/?app=1&profile=1" : "/?app=1&auth=1";
    };

    const handleCopyCli = () => {
      const text = cliCommand ? `${cliCommand}\n${cliSkillInstruction}` : cliPlaceholderCommand;
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).catch(() => {});
        return;
      }
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position = "fixed";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand("copy");
      } catch (_err) {
        // ignore copy fallback failures
      } finally {
        textArea.remove();
      }
    };

    const handleCliSignup = async () => {
      const cleanName = safeText(cliName, "");
      const cleanEmail = safeText(String(cliEmail || "").trim().toLowerCase(), "");
      if (!cleanName) {
        setCliSignupError("Name is required.");
        return;
      }
      if (!cleanEmail || !cleanEmail.includes("@")) {
        setCliSignupError("A valid email is required.");
        return;
      }
      setCliSignupBusy(true);
      setCliSignupError("");
      try {
        if (typeof trackVisitorEvent === "function") {
          trackVisitorEvent("cta_click", {
            surface: "inverse_arena",
            target: "cli_register_submit",
            email_domain: safeText(cleanEmail.split("@")[1], ""),
          });
        }
        const data = await apiRequest("/users/cli-register", {
          method: "POST",
          body: {
            name: cleanName,
            email: cleanEmail,
          },
        });
        const issuedKey = safeText(data?.registration_key, "");
        const accessToken = safeText(data?.access_token, "");
        if (!issuedKey) throw new Error("Registration key was not returned.");
        setCliKey(issuedKey);
        setCliSignupDone(true);
        localStorage.setItem("approx_registration_key", issuedKey);
        if (accessToken) {
          localStorage.setItem("approx_auth_token", accessToken);
        }
        window.dispatchEvent(new Event("storage"));
      } catch (err) {
        setCliSignupError(safeText(err?.message, "Failed to generate your CLI key."));
      } finally {
        setCliSignupBusy(false);
      }
    };

    const displayQuestionText = (value, fallback) => {
      const raw = safeText(value, fallback);
      if (!raw) return fallback;
      const cleaned = raw
        .replace(/^\s*the\s+best\s+skill\s+for\s+/i, "")
        .replace(/^\s*best\s+skill\s+for\s+/i, "")
        .replace(/^\s*the\s+best\s+tool\s+for\s+/i, "")
        .replace(/^\s*best\s+tool\s+for\s+/i, "");
      if (!cleaned) return raw;
      return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
    };

    const buildToolLabel = (tool, url) => {
      const cleanTool = safeText(tool, "Unknown Tool");
      const cleanUrl = safeText(url, "");
      if (!cleanUrl || cleanUrl === "#") return cleanTool;
      if (/^https?:\/\//i.test(cleanUrl)) return cleanTool;

      const normalizedTool = cleanTool.replace(/\s+/g, "-");
      const lowerSource = cleanUrl.toLowerCase();
      const lowerTool = cleanTool.toLowerCase();
      const lowerNormalizedTool = normalizedTool.toLowerCase();

      if (
        lowerSource === lowerTool ||
        lowerSource.endsWith(`/${lowerTool}`) ||
        lowerSource.endsWith(`/${lowerNormalizedTool}`)
      ) {
        return cleanUrl;
      }
      return `${cleanUrl}/${normalizedTool}`;
    };

    const hashSeed = (text) => {
      const s = String(text || "");
      let h = 2166136261;
      for (let i = 0; i < s.length; i++) {
        h ^= s.charCodeAt(i);
        h = Math.imul(h, 16777619);
      }
      return h >>> 0;
    };

    const cardHasSignals = (cardKey) => (hashSeed(cardKey) % 100) < 28;

    const buildCardSignals = (cardKey, tools) => {
      if (!Array.isArray(tools)) return [];
      const signals = tools.map(() => null);
      if (!cardHasSignals(cardKey) || tools.length === 0) return signals;

      const base = hashSeed(`${cardKey}::base`);

      if (tools.length >= 1 && base % 11 === 0) {
        const nrIdx = base % tools.length;
        signals[nrIdx] = { symbol: "#NR", tone: "neutral", title: "Newly ranked" };
      }

      if (tools.length >= 2) {
        const visibleLimit = Math.min(3, tools.length);
        const visibleIdx = Array.from({ length: visibleLimit }, (_v, i) => i);

        const downVisible = visibleIdx
          .map((i) => ({ i, rank: Number(tools[i]?.rank || 0) }))
          .filter((x) => x.rank > 1);
        const downAll = tools
          .map((t, i) => ({ i, rank: Number(t.rank || 0) }))
          .filter((x) => x.rank > 1);
        const downPool = downVisible.length > 0 ? downVisible : downAll;
        if (downPool.length > 0) {
          const pick = (base >> 3) % downPool.length;
          const downIdx = downPool[pick].i;

          const upVisible = visibleIdx.filter((i) => i !== downIdx);
          const upAll = tools.map((_t, i) => i).filter((i) => i !== downIdx);
          const upPool = upVisible.length > 0 ? upVisible : upAll;
          const upIdx = upPool[(base >> 1) % upPool.length];

          if (!signals[upIdx]) {
            signals[upIdx] = { symbol: "▲", tone: "up", title: "Moved up in ranking" };
          }
          if (!signals[downIdx]) {
            signals[downIdx] = { symbol: "▼", tone: "down", title: "Moved down in ranking" };
          }
        }
      }
      return signals;
    };

    return (
      <div data-approx-theme={siteTheme} className={`approx-theme-surface min-h-screen w-screen overflow-x-hidden font-sans pb-11 ${
        hackerView ? "bg-black text-[#F1F1F1] selection:bg-[#FCEE09] selection:text-black" : "bg-[#151515] text-[#a3a3a3] selection:bg-[#a3a3a3] selection:text-[#151515]"
      }`}>
        {hackerView ? (
          <header className="h-16 shrink-0 flex items-center justify-between px-8 border-b border-white/10 bg-black z-20 relative">
            <div className="absolute inset-x-0 bottom-0 h-[2px] bg-gradient-to-r from-[#FCEE09] via-white/10 to-[#FCEE09] opacity-20" />
            <div className="flex items-center gap-10">
              <img
                src="/frontend/APPROXINATION_Logo_white.png"
                alt="Approxination"
                className="h-7 w-auto"
                loading="eager"
                decoding="async"
              />
            </div>
            <div className="flex items-center gap-6">
              <div className="text-[#FCEE09] text-sm font-semibold" style={HELVETICA_STYLE}>Inverse Arena</div>
              <a
                href="/?app=1&theme=hacker"
                className="px-4 py-1 border border-white/30 text-white bg-black hover:bg-white hover:text-black transition-all text-[9px] font-black tracking-widest"
                style={HELVETICA_STYLE}
              >
                Search
              </a>
            </div>
          </header>
        ) : (
          <header className="approx-site-header fixed top-0 left-0 right-0 z-50 w-full py-4 md:py-6 bg-black/80 backdrop-blur-md border-b border-[#2e2e2e]/50">
            <div className="max-w-[1100px] mx-auto px-4 sm:px-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 sm:gap-6">
              <a href="/" className="flex items-center">
                <img
                  src="/frontend/APPROXINATION_Logo.png"
                  alt="Approxination"
                  className={`approx-brand-logo h-[18px] md:h-[22px] w-auto object-contain ${siteTheme === "light" ? "" : "brightness-0 invert"}`}
                />
              </a>
              <div className="w-full sm:w-auto flex items-center justify-between gap-4 sm:gap-6 md:gap-8">
                <nav className="flex items-center gap-4 sm:gap-6 md:gap-8 min-w-0 overflow-x-auto whitespace-nowrap scrollbar-none">
                  <a href="/dashboard" className="text-[12px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">Inverse Arena</a>
                  <a href="/?founders=1" className="text-[12px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">For Founders</a>
                  <a href="/docs" className="text-[12px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">Docs</a>
                </nav>
                <div className="flex items-center gap-2">
                {typeof ThemeToggleButton === "function" ? (
                  <ThemeToggleButton
                    compact
                    theme={siteTheme}
                    onToggle={() => setSiteTheme((prev) => (prev === "light" ? "dark" : "light"))}
                  />
                ) : null}
                {typeof HeaderProfileButton === "function" ? <HeaderProfileButton compact /> : (
                  <button
                    onClick={Boolean(localStorage.getItem("approx_auth_token") || "") ? openProfile : openMainApp}
                    className="text-[13px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors"
                    style={HELVETICA_STYLE}
                  >
                    {Boolean(localStorage.getItem("approx_auth_token") || "") ? "Profile" : "Sign up"}
                  </button>
                )}
                </div>
              </div>
            </div>
          </header>
        )}

        <main className="max-w-[1100px] mx-auto px-4 sm:px-6 pt-28 sm:pt-32 md:pt-36 pb-10 md:pb-16 space-y-10 md:space-y-12">
          {!hackerView && (
            <section className="w-full space-y-6">
              <div className="approx-search-shell w-full max-w-[760px] border-b border-[#2e2e2e] pb-4">
                <div className="flex flex-col sm:flex-row gap-3 sm:gap-2">
                  <div className="relative flex-grow flex items-center">
                    <MagnifierIcon className="absolute left-4 text-[#a3a3a3] w-5 h-5" />
                    <input
                      type="text"
                      value={queryInput}
                      onChange={(e) => setQueryInput(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          runInlineQuery();
                        }
                      }}
                      placeholder="What do you need to know?"
                      className="approx-search-input w-full border border-[#2e2e2e] rounded-md py-3 pl-12 pr-4 text-base bg-[#1a1a1a] text-[#d4d4d4] placeholder-[#666666] focus:outline-none focus:border-[#444444] transition-all"
                      style={HELVETICA_STYLE}
                    />
                  </div>
                  <button
                    onClick={runInlineQuery}
                    disabled={requestRunning}
                    className="approx-search-button w-full sm:w-auto px-6 py-3 bg-white text-black rounded-md hover:bg-[#d4d4d4] transition-colors font-semibold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50"
                    style={HELVETICA_STYLE}
                  >
                    Ask Agents <ArrowRight size={16} />
                  </button>
                </div>
                {queryError && (
                  <div className="mt-3 text-xs font-semibold tracking-wider uppercase text-[#ff5f56]" style={HELVETICA_STYLE}>
                    {queryError}
                  </div>
                )}
                <div className="w-full mt-6 max-w-xl">
                  {!showCliSignup && !cliSignupDone ? (
                    <button
                      type="button"
                      onClick={() => setShowCliSignup(true)}
                      className="group w-full text-left active:scale-[0.995] transition-transform"
                    >
                      <div className="approx-cli-shell flex items-center justify-between bg-[#111] border border-[#222] rounded-md p-4 font-mono text-sm text-[#A1A1A1] hover:border-[#333] transition-colors cursor-text">
                        <span className="flex gap-3 overflow-x-auto whitespace-nowrap">
                          <span className="approx-cli-prompt text-[#555] select-none">$</span>
                          <span className="approx-cli-command text-[#D4D4D4]">{cliPlaceholderCommand}</span>
                        </span>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            handleCopyCli();
                          }}
                          className="approx-cli-copy bg-transparent border-0 appearance-none shadow-none outline-none text-[#555] group-hover:text-white active:scale-95 transition-all cursor-pointer p-1 ml-4 flex-shrink-0"
                          title="Copy to clipboard"
                          aria-label="Copy CLI command"
                        >
                          <Copy size={16} />
                        </button>
                      </div>
                    </button>
                  ) : (
                    <div className="approx-cli-form space-y-4 border-l border-[#2e2e2e] pl-4 sm:pl-5">
                      {!cliKey ? (
                        <>
                          <div className="approx-theme-link-secondary text-base text-[#7ee787] font-['Inter',sans-serif]">Use via CLI</div>
                          <div className="grid grid-cols-1 gap-3">
                            <input
                              type="text"
                              value={cliName}
                              onChange={(e) => setCliName(e.target.value)}
                              placeholder="Name"
                              className="approx-cli-input w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-2.5 text-sm text-white placeholder:text-white/25 focus:outline-none focus:border-[#5a5a5a]"
                            />
                            <input
                              type="email"
                              value={cliEmail}
                              onChange={(e) => setCliEmail(e.target.value)}
                              placeholder="Email"
                              className="approx-cli-input w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-2.5 text-sm text-white placeholder:text-white/25 focus:outline-none focus:border-[#5a5a5a]"
                            />
                          </div>
                          {cliSignupError ? <div className="text-sm text-[#ff7b72]">{cliSignupError}</div> : null}
                          <button
                            type="button"
                            onClick={handleCliSignup}
                            disabled={cliSignupBusy}
                            className="approx-cli-inline-action inline-flex items-center justify-center border-b border-white pb-1 text-sm font-medium text-white hover:text-[#d0d0d0] hover:border-[#d0d0d0] active:scale-[0.98] transition-all disabled:opacity-50"
                          >
                            {cliSignupBusy ? "Generating key..." : "Generate Personal Key"}
                          </button>
                        </>
                      ) : (
                        <>
                          <div className="approx-theme-link-secondary text-base text-[#7ee787] font-['Inter',sans-serif]">Your account is ready</div>
                          <div className="approx-cli-shell flex items-start justify-between bg-[#111] border border-[#222] rounded-md p-4 font-mono text-sm text-[#A1A1A1] hover:border-[#333] transition-colors group cursor-text">
                            <div className="min-w-0 space-y-1 overflow-x-auto scrollbar-none">
                              <div className="flex gap-3 whitespace-nowrap">
                                <span className="approx-cli-prompt text-[#555] select-none">$</span>
                                <div className="approx-cli-command text-[#D4D4D4]">{cliCommand}</div>
                              </div>
                              <div className="flex gap-3 whitespace-nowrap">
                                <span className="approx-cli-prompt text-[#555] select-none">$</span>
                                <div className="approx-cli-command text-[#A1A1A1]">{cliSkillInstruction}</div>
                              </div>
                            </div>
                            <button
                              type="button"
                              onClick={handleCopyCli}
                              className="approx-cli-copy bg-transparent border-0 appearance-none shadow-none outline-none text-[#555] group-hover:text-white active:scale-95 transition-all cursor-pointer p-1 ml-4 flex-shrink-0"
                              title="Copy to clipboard"
                              aria-label="Copy CLI commands"
                            >
                              <Copy size={16} />
                            </button>
                          </div>
                        </>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </section>
          )}
          {!hackerView && requestRunning && (
            <div className="w-full text-xs font-semibold tracking-[0.25em] text-[#666666] uppercase animate-pulse" style={HELVETICA_STYLE}>
              Synthesizing knowledge base...
            </div>
          )}
          {!hackerView && queryResult && typeof MinimalResult === "function" && (
            <section className="w-full">
              <MinimalResult
                data={queryResult}
                query={queryInput}
                setQuery={setQueryInput}
                onRunNext={runInlineQuery}
                requestRunning={requestRunning}
                showQueryBar={false}
                siteTheme={siteTheme}
              />
            </section>
          )}
          {loading && <div className="text-xs font-bold tracking-wider uppercase text-[#666666]">Loading Inverse Arena data...</div>}
          {!loading && error && <div className="text-xs font-bold tracking-wider uppercase text-[#ff5f56]">{error}</div>}
          {!loading && !error && sectionEntries.length === 0 && (
            <div className="text-xs font-bold tracking-wider uppercase text-[#666666]">No Inverse Arena data available yet.</div>
          )}

          {!loading && !error && (
            <>
              {sectionEntries.map(([section, meta]) => (
                <section key={section} id={`arena-section-${String(section || "").toLowerCase().replace(/[^a-z0-9]+/g, "-")}`} className="space-y-5 scroll-mt-24">
                  <button
                    type="button"
                    onClick={() => setExpandedSections((prev) => ({ ...prev, [section]: !prev[section] }))}
                    className="w-full flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3 sm:gap-4 text-left border-b border-black pb-3"
                  >
                    <div className="space-y-1">
                      <div className="text-[11px] font-bold uppercase tracking-[0.25em]">{section}</div>
                      <div className="approx-section-meta text-[12px] text-[#57606a] font-medium leading-5" style={HELVETICA_STYLE}>
                        {Number(meta?.questionCount || 0).toLocaleString()} questions · {Number(meta?.toolCount || 0).toLocaleString()} tools · top rating {Number(meta?.highestElo || 1500).toFixed(0)}
                      </div>
                    </div>
                    <span className="approx-section-toggle text-[10px] tracking-[0.15em] uppercase">{expandedSections[section] ? "Hide" : "Show"}</span>
                  </button>
                  {expandedSections[section] && (
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                      {(Array.isArray(meta?.questionItems) ? meta.questionItems : []).map((q, qIndex) => {
                        const safeQ = q && typeof q === "object" ? q : {};
                        const fallbackQuestion = displayQuestionText(safeQ.text, `Question ${qIndex + 1}`);
                        const fallbackTools = Array.isArray(safeQ.tools) ? safeQ.tools : [];
                        try {
                          const cardKey = `${section}::${safeText(safeQ.text, `Question ${qIndex + 1}`)}::${qIndex}`;
                          const isExpanded = Boolean(expandedCards[cardKey]);
                          const tools = fallbackTools;
                          const allSignals = buildCardSignals(cardKey, tools);
                          const visibleSignals = allSignals.slice(0, 3);
                          const leader = tools[0] || null;
                          const challengers = tools.slice(1);
                          const hasMoreChallengers = challengers.length > 2;
                          const shownChallengers = isExpanded ? challengers : challengers.slice(0, 2);
                          const totalElo = tools.reduce(
                            (sum, t) => sum + (Number.isFinite(Number(t?.elo)) ? Number(t.elo) : 1500),
                            0,
                          );
                          const consensus = (tool) => {
                            if (!tool) return 0;
                            const value = Number.isFinite(Number(tool?.elo)) ? Number(tool.elo) : 1500;
                            return totalElo > 0 ? Math.round((value / totalElo) * 100) : 0;
                          };
                          const topDiff =
                            tools.length >= 2
                              ? Math.abs(
                                (Number.isFinite(Number(tools[0]?.elo)) ? Number(tools[0].elo) : 1500) -
                                  (Number.isFinite(Number(tools[1]?.elo)) ? Number(tools[1].elo) : 1500),
                              )
                              : 0;
                          const marketVotes = tools.reduce((sum, t) => sum + Number(rankingIndex[safeText(t?.tool, "")] || 0), 0);
                          const marketAgents = Math.max(1, tools.length);
                          const updatedMins = (hashSeed(cardKey) % 59) + 1;
                          const trendDelta = (signal, seedKey) => {
                            const seed = hashSeed(seedKey);
                            if (signal?.tone === "up") return 4 + (seed % 17);
                            if (signal?.tone === "down") return -(3 + (seed % 14));
                            return 0;
                          };
                          const TrendBadge = ({ value }) => {
                            if (!Number.isFinite(Number(value)) || Number(value) === 0) {
                              return <span className="text-gray-400 text-xs font-mono w-8 text-right">-</span>;
                            }
                            const positive = Number(value) > 0;
                            return (
                              <div className={`flex items-center gap-1 text-[12px] font-bold ${positive ? "text-green-600" : "text-red-500"}`}>
                                <span>{positive ? "▲" : "▼"}</span>
                                <span style={HELVETICA_STYLE}>{Math.abs(Number(value))}</span>
                              </div>
                            );
                          };

                          return (
                            <div
                              key={`${section}_${qIndex}`}
                              className={`approx-ranking-card relative rounded-xl overflow-hidden transition-all duration-200 flex flex-col group ${
                                hackerView
                                  ? "bg-[#080808] border border-white/10 hover:border-[#FCEE09]/70"
                                  : "bg-[#1a1a1a] border border-[#2e2e2e] hover:border-[#444444]"
                              }`}
                            >
                              <img
                                src="/frontend/APRXNTN_LOGO-removebg-preview.png"
                                alt="APRXNTN"
                                className={`absolute top-3 left-3 w-5 h-5 object-contain opacity-90 pointer-events-none ${siteTheme === "light" ? "brightness-0" : "brightness-0 invert"}`}
                                loading="lazy"
                                decoding="async"
                              />
                              <div className={`approx-ranking-card-header p-4 pb-3 pl-10 border-b flex justify-between items-start gap-4 ${hackerView ? "border-white/10" : "border-[#2e2e2e]"}`}>
                                <div>
                                  <div className={`approx-ranking-card-section text-[9px] uppercase tracking-[0.18em] mb-1.5 flex items-center gap-1.5 ${hackerView ? "text-white/40" : "text-[#737373]"}`} style={HELVETICA_STYLE}>
                                    {section}
                                  </div>
                                  <h3 className={`approx-ranking-card-title text-[16px] md:text-[17px] font-semibold leading-snug ${hackerView ? "text-white" : "text-white"}`}>
                                    {displayQuestionText(safeQ.text, `Question ${qIndex + 1}`)}
                                  </h3>
                                </div>
                              </div>

                              <div className="p-4 space-y-4">
                                {leader && (
                                  <div className={`approx-ranking-card-leader flex justify-between items-center rounded-lg px-3 py-3 border ${hackerView ? "bg-black border-white/15" : "bg-[#202020] border-[#303030]"}`}>
                                    <div className="min-w-0 flex-1 pr-3">
                                      {leader?.url && leader.url !== "#" ? (
                                        <a
                                          href={leader.url}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          className={`approx-ranking-card-title max-w-full font-semibold text-[15px] md:text-[16px] inline-flex items-center gap-1.5 ${hackerView ? "text-[#FCEE09] hover:text-white" : "text-white hover:text-[#d4d4d4]"}`}
                                        >
                                          <span className="block truncate max-w-[13rem] md:max-w-[16rem] lg:max-w-[18rem]">
                                            {buildToolLabel(leader?.tool, leader?.url)}
                                          </span>
                                          <ArrowUpRight size={12} className={hackerView ? "text-white/40" : "text-gray-400"} />
                                        </a>
                                      ) : (
                                        <div className={`approx-ranking-card-title font-semibold text-[15px] md:text-[16px] truncate max-w-[13rem] md:max-w-[16rem] lg:max-w-[18rem] ${hackerView ? "text-[#FCEE09]" : "text-white"}`}>
                                          {buildToolLabel(leader?.tool, leader?.url)}
                                        </div>
                                      )}
                                      <div className="flex items-center gap-2 mt-0.5">
                                        <span className={`approx-ranking-card-chip text-[10px] font-mono px-1.5 py-0.5 rounded ${hackerView ? "text-white/70 bg-black border border-white/20" : "text-[#a3a3a3] bg-[#151515] border border-[#303030]"}`}>
                                          <span style={HELVETICA_STYLE}>{consensus(leader)}</span>% Consensus
                                        </span>
                                        <TrendBadge value={trendDelta(visibleSignals[0], `${cardKey}::leader`)} />
                                      </div>
                                    </div>
                                    <div className="flex flex-col items-end shrink-0 pl-2">
                                      <div className={`approx-ranking-card-value text-[28px] md:text-[30px] leading-none font-black tracking-tight ${hackerView ? "text-white" : "text-white"}`} style={HELVETICA_STYLE}>
                                        {Number(leader?.elo || 1500).toFixed(0)}
                                      </div>
                                      <div className={`approx-ranking-card-meta text-[10px] uppercase tracking-[0.18em] font-bold mt-1 ${hackerView ? "text-white/50" : "text-[#737373]"}`}>ELO</div>
                                    </div>
                                  </div>
                                )}

                                <div className="space-y-1">
                                  {shownChallengers.map((tool, tIndex) => (
                                    <div
                                      key={`${qIndex}_ch_${tIndex}`}
                                      className={`approx-ranking-card-row flex justify-between items-center py-2 px-1 border-b last:border-0 rounded transition-colors ${
                                        hackerView ? "border-white/10 hover:bg-white/5" : "border-[#252525] hover:bg-[#202020]"
                                      }`}
                                    >
                                      <div className="flex items-center gap-2.5 min-w-0">
                                        <span className={`approx-ranking-card-meta text-[10px] font-bold w-3 text-center ${hackerView ? "text-white/40" : "text-[#666666]"}`} style={HELVETICA_STYLE}>
                                          {tIndex + 2}
                                        </span>
                                        {tool?.url && tool.url !== "#" ? (
                                          <a
                                            href={tool.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className={`approx-ranking-card-rowlabel text-[14px] md:text-[15px] font-medium truncate flex items-center gap-1.5 ${hackerView ? "text-white hover:text-[#FCEE09]" : "text-[#d4d4d4] hover:text-white"}`}
                                          >
                                            {buildToolLabel(tool?.tool, tool?.url)}
                                            <ArrowUpRight size={12} className={hackerView ? "text-white/40" : "text-gray-400"} />
                                          </a>
                                        ) : (
                                          <span className={`approx-ranking-card-rowlabel text-[14px] md:text-[15px] font-medium truncate ${hackerView ? "text-white" : "text-[#d4d4d4]"}`}>{buildToolLabel(tool?.tool, tool?.url)}</span>
                                        )}
                                      </div>
                                      <div className="flex items-center gap-3 shrink-0">
                                        <TrendBadge value={trendDelta(visibleSignals[tIndex + 1], `${cardKey}::${tIndex}`)} />
                                        <span className={`approx-ranking-card-rowvalue text-[13px] md:text-[14px] font-bold w-12 text-right ${hackerView ? "text-white" : "text-white"}`} style={HELVETICA_STYLE}>
                                          {Number(tool?.elo || 1500).toFixed(0)}
                                        </span>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>

                              {hasMoreChallengers && (
                                <button
                                  type="button"
                                  onClick={() => setExpandedCards((prev) => ({ ...prev, [cardKey]: !isExpanded }))}
                                  className={`w-full py-2 border-t flex items-center justify-center gap-1 text-xs font-semibold transition-colors ${
                                    hackerView
                                      ? "bg-black border-white/10 text-white/70 hover:text-[#FCEE09] hover:bg-white/5"
                                      : "bg-[#1a1a1a] border-[#2e2e2e] text-[#a3a3a3] hover:text-white hover:bg-[#202020]"
                                  }`}
                                >
                                  {isExpanded ? "Hide" : `View ${challengers.length - 2} more`}
                                </button>
                              )}

                              <div className={`approx-ranking-card-footer mt-auto px-4 py-3 border-t flex flex-wrap items-center justify-between gap-y-2 ${
                                hackerView ? "bg-black border-white/10" : "bg-[#1a1a1a] border-[#2e2e2e]"
                              }`}>
                                <div className={`approx-ranking-card-footmeta flex items-center gap-3 text-[11px] font-medium ${hackerView ? "text-white/60" : "text-[#737373]"}`}>
                                  <span className="flex items-center gap-1" title="Volume">
                                    <span>●</span> <span style={HELVETICA_STYLE}>{Number(marketVotes || tools.length).toLocaleString()}</span>
                                  </span>
                                  <span className="flex items-center gap-1" title="Agents">
                                    <span>◌</span> <span style={HELVETICA_STYLE}>{marketAgents}</span>
                                  </span>
                                </div>
                                <div className={`approx-ranking-card-footmeta flex items-center gap-1 text-[10px] font-medium ${hackerView ? "text-white/40" : "text-[#666666]"}`}>
                                  <span>◷</span> <span style={HELVETICA_STYLE}>{updatedMins}</span>m ago
                                </div>
                              </div>
                            </div>
                          );
                        } catch (_err) {
                          try {
                            console.error("inverse_arena_card_render_failed", {
                              section,
                              question: safeText(safeQ.text, ""),
                              error: String(_err?.message || _err || "unknown_error"),
                            });
                          } catch (_consoleErr) {
                            // ignore console serialization issues
                          }
                          return (
                            <div
                              key={`${section}_${qIndex}`}
                              className={`rounded-xl overflow-hidden flex flex-col ${
                                hackerView ? "bg-[#080808] border border-white/10" : "bg-[#1a1a1a] border border-[#2e2e2e]"
                              }`}
                            >
                              <div className={`p-4 pb-3 pl-10 border-b ${hackerView ? "border-white/10" : "border-[#2e2e2e]"}`}>
                                <div className={`text-[10px] uppercase tracking-widest mb-1.5 ${hackerView ? "text-white/40" : "text-[#737373]"}`} style={HELVETICA_STYLE}>
                                  {section}
                                </div>
                                <h3 className={`text-[15px] font-bold leading-snug ${hackerView ? "text-white" : "text-white"}`}>
                                  {fallbackQuestion}
                                </h3>
                              </div>
                              <div className="p-4 space-y-2">
                                {fallbackTools.slice(0, 4).map((tool, idx) => (
                                  <div
                                    key={`${section}_${qIndex}_fallback_${idx}`}
                                    className={`flex items-center justify-between gap-3 py-2 border-b last:border-0 ${
                                      hackerView ? "border-white/10" : "border-[#252525]"
                                    }`}
                                  >
                                    <div className={`min-w-0 text-[15px] truncate ${hackerView ? "text-white" : "text-[#d4d4d4]"}`}>
                                      {buildToolLabel(tool?.tool, tool?.url)}
                                    </div>
                                    <div className={`shrink-0 text-[13px] font-bold ${hackerView ? "text-white/80" : "text-white"}`} style={HELVETICA_STYLE}>
                                      {Number(tool?.elo || 1500).toFixed(0)}
                                    </div>
                                  </div>
                                ))}
                              </div>
                            </div>
                          );
                        }
                      })}
                    </div>
                  )}
                </section>
              ))}
            </>
          )}
          <section className={`mt-16 pt-8 border-t ${hackerView ? "border-white/10" : "border-[#d0d7de]"}`}>
            <div className="max-w-5xl space-y-4">
              <p className={`text-[12px] leading-6 ${hackerView ? "text-white/45" : "text-[#57606a]"}`} style={HELVETICA_STYLE}>
                Measurement &amp; integrity note: Approxination rankings and performance signals are collected independently through our evaluation pipeline and connected agent network. Reported tool metrics reflect observed execution outcomes and may include normal routing, hosting, and network overhead. During rare outages or monitoring pauses, sample counts may be lower than usual. Ranking snapshots and historical changes are recorded in a tamper-evident way, and any cost references shown on the platform are informational estimates only and may differ from actual provider billing.
              </p>
              <p className={`text-[12px] leading-6 ${hackerView ? "text-white/45" : "text-[#57606a]"}`} style={HELVETICA_STYLE}>
                Important disclaimer: Approxination is an independent ranking, evaluation, and recommendation service. We are not affiliated with, endorsed by, or officially connected to the tool vendors, API providers, model providers, or software platforms mentioned on this website. All product names, logos, and brands are the property of their respective owners and are used only for identification and informational purposes. Metrics and rankings are provided as is for general information only and should not be the sole basis for production or business decisions. We make no warranty as to accuracy or completeness and accept no liability for loss arising from their use.
              </p>
            </div>
          </section>
        </main>
        {typeof NewsTicker === "function" && <NewsTicker items={tickerItems} />}
      </div>
    );
  }

  class DashboardErrorBoundary extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false, message: "" };
    }

    static getDerivedStateFromError(error) {
      return { hasError: true, message: String(error?.message || error || "dashboard_render_error") };
    }

    componentDidCatch(_error, _info) {
      // No-op: keeping console details for browser devtools.
    }

    render() {
      if (this.state.hasError) {
        return (
          <div className="min-h-screen w-screen bg-white text-black font-sans p-8">
            <div className="max-w-3xl mx-auto border border-red-300 bg-red-50 p-6 rounded-xl">
              <h1 className="text-sm font-bold uppercase tracking-widest text-red-700">Dashboard Render Error</h1>
              <p className="text-sm mt-3 text-red-800">The dashboard crashed while rendering this section.</p>
              <p className="text-xs mt-3 font-mono text-red-700 break-all">{this.state.message}</p>
              <a href="/dashboard" className="inline-block mt-4 text-xs uppercase tracking-widest border border-red-400 px-3 py-2">
                Reload Dashboard
              </a>
            </div>
          </div>
        );
      }
      return this.props.children;
    }
  }

  return { DashboardPage, DashboardErrorBoundary };
};
