const { useState, useEffect, useRef, useMemo } = React;
const IconPack = window.lucideReact || {};
const makeFallbackIcon = (glyph) => {
  const FallbackIcon = ({ size = 14, className = "" }) => (
    <span
      className={className}
      style={{
        display: "inline-flex",
        width: size,
        height: size,
        alignItems: "center",
        justifyContent: "center",
        fontSize: Math.max(10, Math.floor(size * 0.7)),
        lineHeight: 1,
      }}
      aria-hidden="true"
    >
      {glyph}
    </span>
  );
  return FallbackIcon;
};
const ArrowRight = IconPack.ArrowRight || makeFallbackIcon(">");
const ArrowUpRight = IconPack.ArrowUpRight || makeFallbackIcon("^");
const Copy = IconPack.Copy || (({ size = 16, className = "" }) => (
  <svg
    viewBox="0 0 24 24"
    width={size}
    height={size}
    aria-hidden="true"
    className={className}
    fill="none"
    stroke="currentColor"
    strokeWidth="1.8"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <rect x="9" y="9" width="11" height="11" rx="2" ry="2" />
    <path d="M5 15V6a2 2 0 0 1 2-2h9" />
  </svg>
));
const ChevronDown = IconPack.ChevronDown || makeFallbackIcon("v");
const Search = IconPack.Search || makeFallbackIcon("?");
const Sun = IconPack.Sun || (({ size = 16, className = "" }) => (
  <svg
    viewBox="0 0 24 24"
    width={size}
    height={size}
    aria-hidden="true"
    className={className}
    fill="none"
    stroke="currentColor"
    strokeWidth="1.8"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <circle cx="12" cy="12" r="4.5" />
    <path d="M12 2.5v2.2" />
    <path d="M12 19.3v2.2" />
    <path d="M4.5 12h2.2" />
    <path d="M17.3 12h2.2" />
    <path d="m5.9 5.9 1.6 1.6" />
    <path d="m16.5 16.5 1.6 1.6" />
    <path d="m16.5 7.5 1.6-1.6" />
    <path d="m5.9 18.1 1.6-1.6" />
  </svg>
));
const Moon = IconPack.Moon || (({ size = 16, className = "" }) => (
  <svg
    viewBox="0 0 24 24"
    width={size}
    height={size}
    aria-hidden="true"
    className={className}
    fill="none"
    stroke="currentColor"
    strokeWidth="1.8"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" />
  </svg>
));
const Cpu = IconPack.Cpu || makeFallbackIcon("#");
const Database = IconPack.Database || makeFallbackIcon("[]");
const Eye = IconPack.Eye || makeFallbackIcon("o");
const Fingerprint = IconPack.Fingerprint || makeFallbackIcon("@");
const Radio = IconPack.Radio || makeFallbackIcon("~");
const Scan = IconPack.Scan || makeFallbackIcon("[]");
const Target = IconPack.Target || makeFallbackIcon("+");
const HardDrive = IconPack.HardDrive || makeFallbackIcon("H");
const Server = IconPack.Server || makeFallbackIcon("S");
const Globe = IconPack.Globe || makeFallbackIcon("O");

const GithubMark = ({ size = 14, className = "" }) => (
  <svg
    viewBox="0 0 16 16"
    width={size}
    height={size}
    aria-hidden="true"
    className={className}
    fill="currentColor"
  >
    <path d="M8 0C3.58 0 0 3.58 0 8a8.01 8.01 0 0 0 5.47 7.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.69-1.07-2.69-1.07-.36-.92-.89-1.17-.89-1.17-.73-.5.05-.49.05-.49.81.06 1.24.83 1.24.83.72 1.24 1.88.88 2.34.67.07-.52.28-.88.5-1.08-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.58.82-2.14-.08-.2-.36-1.01.08-2.1 0 0 .67-.22 2.2.82A7.7 7.7 0 0 1 8 4.77c.68 0 1.37.09 2.01.26 1.53-1.04 2.2-.82 2.2-.82.44 1.09.16 1.9.08 2.1.51.56.82 1.27.82 2.14 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.19c0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z" />
  </svg>
);

const BR_LOGS = [
  "INIT_VOIGHT_KAMPFF_CALIBRATION...",
  "WARNING: BASELINE DEVIATION DETECTED.",
  "CELLS INTERLINKED WITHIN CELLS INTERLINKED.",
  "ROUTING PACKETS VIA OFF-WORLD RELAY...",
  "NEXUS-9 AUTHENTICATION_BPS: 104Kbps",
  "MEMORY_FRAGMENT_0x8F9A RECOVERED.",
  "TYRELL_ARCHIVE_ACCESS: GRANTED.",
  "WALLACE_SYS_OVERRIDE_ENGAGED.",
  "SPINNER_TRAFFIC_ANALYSIS: CLEAR.",
  "SCANNING_RETINAL_DATABASE...",
  "DREADFULLY DISTINCT AGAINST THE DARK.",
];

const FALLBACK_RESPONSE = {
  query: "Which tool is best for a stock price API?",
  results: [],
  final_answer: "No response yet.",
  web_results: [],
  trace: { duration_ms: 0, events: [] },
};

const safeArray = (v) => (Array.isArray(v) ? v : []);
const SITE_THEME_STORAGE_KEY = "approx_site_theme";
const SITE_THEME_COLORS = {
  dark: "#000000",
  light: "#F5F1E8",
};
const formatLastSeenLabel = (value) => {
  const raw = safeText(value, "");
  if (!raw) return "never";
  const ts = Date.parse(raw);
  if (!Number.isFinite(ts)) return raw;
  const diffSec = Math.max(0, Math.floor((Date.now() - ts) / 1000));
  if (diffSec < 60) return "just now";
  if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`;
  if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h ago`;
  return `${Math.floor(diffSec / 86400)}d ago`;
};
const safeText = (v, fallback = "") => (typeof v === "string" && v.trim() ? v : fallback);
const URL_RE = /(https?:\/\/[^\s)]+[^\s).,!?;:])/g;
const HERO_PROMISE_CLASS = "w-full max-w-3xl mx-auto text-2xl md:text-3xl font-bold text-slate-800 mb-10 text-center tracking-tight leading-tight";
const MAIN_PROMISE_CLASS = "w-full max-w-3xl mx-auto text-2xl md:text-3xl font-bold text-slate-800 mb-10 text-center tracking-tight leading-tight whitespace-nowrap";
const APPROXINATION_LOGO_SRC = "/frontend/APPROXINATION_Logo.png";
const HACKER_TEASER_SRC = "/frontend/teaser_blank.png";
const MAIN_APP_HERO_IMAGES = ["/frontend/Kuinji_step.jpg"];
const SITE_THEME_STYLES = `
  .approx-theme-surface[data-approx-theme="light"] {
    background: #F5F1E8 !important;
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-header {
    background: rgba(245, 241, 232, 0.88) !important;
    border-color: #d7d0c4 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-header a,
  .approx-theme-surface[data-approx-theme="light"] .approx-site-header button {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-header a:hover,
  .approx-theme-surface[data-approx-theme="light"] .approx-site-header button:hover {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-brand-logo {
    filter: none !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-hero-title,
  .approx-theme-surface[data-approx-theme="light"] .approx-arena-title {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-hero-subtitle,
  .approx-theme-surface[data-approx-theme="light"] .approx-arena-subtitle {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-theme-link-primary {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-theme-link-secondary {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-theme-link-secondary:hover {
    color: #4D463E !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-hero-image-frame {
    border-color: #d7d0c4 !important;
    box-shadow: 0 24px 60px rgba(98, 79, 55, 0.08) !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-shell {
    background: #FBF7EF !important;
    border-color: #d7d0c4 !important;
    color: #6F665B !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-shell:hover {
    border-color: #c4b8a8 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-prompt {
    color: #9A8E80 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-command {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-copy {
    color: #8D7A68 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-copy:hover {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-form {
    border-color: #d7d0c4 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-input {
    border-color: #cfc6b8 !important;
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-input::placeholder {
    color: rgba(111, 102, 91, 0.6) !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-inline-action {
    color: #1F1D1A !important;
    border-color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-cli-inline-action:hover {
    color: #6F665B !important;
    border-color: #6F665B !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-search-shell {
    border-color: #d7d0c4 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-search-input {
    background: #FBF7EF !important;
    border-color: #d7d0c4 !important;
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-search-input::placeholder {
    color: #8D7A68 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-search-button {
    background: #1F1D1A !important;
    color: #F5F1E8 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-search-button:hover {
    background: #34302A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card {
    background: #FBF7EF !important;
    border-color: #d7d0c4 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-header,
  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-footer {
    border-color: #e0d6c8 !important;
    background: #F3EDE1 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-section,
  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-meta,
  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-footmeta {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-title,
  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-value,
  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-rowvalue {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-leader {
    background: #F6F0E5 !important;
    border-color: #d7d0c4 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-chip {
    background: #EEE6D8 !important;
    border-color: #d7d0c4 !important;
    color: #6F665B !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-row {
    border-color: #ece4d7 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-row:hover {
    background: #F6F0E5 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-ranking-card-rowlabel {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-section-meta,
  .approx-theme-surface[data-approx-theme="light"] .approx-section-toggle {
    color: #1F1D1A !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-footer {
    background: #000000 !important;
    border-color: #2e2e2e !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-footer .approx-footer-copy {
    color: #737373 !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-footer .approx-footer-title,
  .approx-theme-surface[data-approx-theme="light"] .approx-site-footer .approx-footer-link:hover {
    color: #ffffff !important;
  }

  .approx-theme-surface[data-approx-theme="light"] .approx-site-footer .approx-footer-link {
    color: #a3a3a3 !important;
  }
`;

function ensureSiteThemeStyles() {
  if (typeof document === "undefined") return;
  if (document.getElementById("approx-site-theme-styles")) return;
  const styleTag = document.createElement("style");
  styleTag.id = "approx-site-theme-styles";
  styleTag.textContent = SITE_THEME_STYLES;
  document.head.appendChild(styleTag);
}

function getSavedSiteTheme() {
  if (typeof window === "undefined") return "dark";
  try {
    return window.localStorage.getItem(SITE_THEME_STORAGE_KEY) === "light" ? "light" : "dark";
  } catch (_err) {
    return "dark";
  }
}

function applySiteThemeToDocument(theme) {
  if (typeof document !== "undefined") {
    document.documentElement.setAttribute("data-approx-theme", theme === "light" ? "light" : "dark");
    const meta = document.querySelector('meta[name="theme-color"]');
    if (meta) {
      meta.setAttribute("content", theme === "light" ? SITE_THEME_COLORS.light : SITE_THEME_COLORS.dark);
    }
  }
}

function linkifyText(text, linkClassName = "underline") {
  const raw = String(text || "");
  const parts = raw.split(URL_RE);
  return parts.map((part, idx) => {
    if (/^https?:\/\//i.test(part)) {
      return (
        <a key={`url-${idx}`} href={part} target="_blank" rel="noreferrer" className={linkClassName}>
          {part}
        </a>
      );
    }
    return <span key={`txt-${idx}`}>{part}</span>;
  });
}

function ThemeToggleButton({ theme = "dark", onToggle, compact = false }) {
  const nextLabel = theme === "light" ? "Dark" : "Light";
  const Icon = theme === "light" ? Moon : Sun;
  return (
    <button
      type="button"
      onClick={onToggle}
      className={`approx-theme-toggle inline-flex items-center justify-center ${compact ? "w-8 h-8 md:w-9 md:h-9" : "w-9 h-9"} border rounded-full transition-all shadow-sm`}
      style={{
        ...HELVETICA_STYLE,
        background: theme === "light" ? "#EEE6D8" : "#ffffff",
        borderColor: theme === "light" ? "#d7d0c4" : "#d0d7de",
        color: theme === "light" ? "#6A5F52" : "#24292f",
      }}
      aria-label={`Switch to ${nextLabel.toLowerCase()} theme`}
      title={`Switch to ${nextLabel.toLowerCase()} theme`}
    >
      <Icon size={15} />
    </button>
  );
}

function normalizeExplorationLabel(line) {
  const s = String(line || "").trim();
  if (/^internet grounding \(brave\)\s*:/i.test(s)) {
    return s.replace(/^internet grounding \(brave\)\s*:/i, "Exploration Level:");
  }
  if (/^internet grounding \(perplexity\)\s*:/i.test(s)) {
    return s.replace(/^internet grounding \(perplexity\)\s*:/i, "Exploration Level:");
  }
  return s;
}

function parseFinalAnswerLines(finalAnswer) {
  const rawLines = String(finalAnswer || "")
    .split("\n")
    .map((line) => normalizeExplorationLabel(line.replace(/^- /, "").trim()))
    .filter(Boolean);

  const merged = [];
  const explorationChunks = [];
  for (const line of rawLines) {
    const m = /^exploration level\s*:\s*(.*)$/i.exec(line);
    if (m) {
      const rest = (m[1] || "").trim();
      if (rest) explorationChunks.push(rest);
      continue;
    }
    merged.push(line);
  }
  if (explorationChunks.length > 0) {
    merged.push(`Exploration Level: ${explorationChunks.join("  |  ")}`);
  }
  return merged;
}

function parseAnswerMarkdownLines(finalAnswer) {
  const rawLines = String(finalAnswer || "")
    .split("\n")
    .map((line) => normalizeExplorationLabel(String(line || "").trim()))
    .filter(Boolean);

  const merged = [];
  const explorationChunks = [];
  for (const line of rawLines) {
    const m = /^[-*]?\s*exploration level\s*:\s*(.*)$/i.exec(line);
    if (m) {
      const rest = (m[1] || "").trim();
      if (rest) explorationChunks.push(rest);
      continue;
    }
    merged.push(line);
  }
  if (explorationChunks.length > 0) {
    merged.push(`Exploration Level: ${explorationChunks.join("  |  ")}`);
  }
  return merged;
}

function renderInlineRichText(text, linkClassName = "underline") {
  const raw = String(text || "");
  const urlParts = raw.split(URL_RE);
  const nodes = [];
  let k = 0;

  for (const part of urlParts) {
    if (/^https?:\/\//i.test(part)) {
      nodes.push(
        <a key={`ri-${k++}`} href={part} target="_blank" rel="noreferrer" className={linkClassName}>
          {part}
        </a>,
      );
      continue;
    }
    const boldParts = part.split(/(\*\*[^*]+\*\*)/g);
    for (const bp of boldParts) {
      if (!bp) continue;
      if (/^\*\*[^*]+\*\*$/.test(bp)) {
        const content = bp.slice(2, -2);
        nodes.push(<strong key={`ri-${k++}`} className="font-semibold">{content}</strong>);
      } else {
        nodes.push(<span key={`ri-${k++}`}>{bp}</span>);
      }
    }
  }
  return nodes;
}

function isAllowedBulletLine(text) {
  const t = String(text || "").trim();
  if (!t) return false;
  if (/https?:\/\//i.test(t)) return true;
  if (/^source\s*:/i.test(t)) return true;
  if (/\(\s*ELO\s*:/i.test(t)) return true;
  if (/\(\s*vote score\s*:/i.test(t)) return true;
  return false;
}

function normalizeApiResponse(raw, queryFallback) {
  const results = safeArray(raw?.results).map((r) => ({
    agent_id: safeText(r?.agent_id),
    subtask: safeText(r?.subtask),
    success: Boolean(r?.success),
    response_text: safeText(r?.response_text),
    tool_rankings: safeArray(r?.tool_rankings).map((t) => ({
      tool: safeText(t?.tool, "Unknown"),
      score: Number.isFinite(Number(t?.score)) ? Number(t.score) : 0,
      elo: Number.isFinite(Number(t?.elo)) ? Number(t.elo) : null,
      metric: safeText(t?.metric),
      reason: safeText(t?.reason, "No reason provided."),
    })),
    claims: safeArray(r?.claims).map((c) => ({
      statement: safeText(c?.statement, "No statement provided."),
      confidence: Number.isFinite(Number(c?.confidence)) ? Number(c.confidence) : 0,
      verified: Boolean(c?.verified),
    })),
  }));
  if (!results.length) {
    results.push({
      agent_id: "",
      subtask: "tool_recommendation",
      success: true,
      response_text: safeText(raw?.final_answer),
      tool_rankings: safeArray(raw?.recommended_tools).map((t) => ({
        tool: safeText(t?.tool, "Unknown"),
        score: Number.isFinite(Number(t?.score)) ? Number(t.score) : 0,
        elo: Number.isFinite(Number(t?.elo)) ? Number(t.elo) : null,
        metric: safeText(t?.metric),
        reason: safeText(t?.reason, "No reason provided."),
      })),
      claims: [],
    });
  }

  const firstResult = results[0] || {};
  const final_answer =
    safeText(raw?.final_answer) ||
    safeText(firstResult?.response_text) ||
    "No final synthesis returned by the API.";

  return {
    query: safeText(raw?.query, queryFallback),
    results,
    final_answer,
    web_results: safeArray(raw?.web_results).map((w) => ({
      title: safeText(w?.title, "Untitled source"),
      url: safeText(w?.url, "#"),
      snippet: safeText(w?.snippet, "No snippet available."),
    })),
    trace: {
      duration_ms: Number.isFinite(Number(raw?.trace?.duration_ms)) ? Number(raw.trace.duration_ms) : 0,
      events: safeArray(raw?.trace?.events).map((evt) => ({
        ts: safeText(evt?.ts, new Date().toISOString()),
        event: safeText(evt?.event, "event"),
        payload: typeof evt?.payload === "object" && evt?.payload !== null ? evt.payload : {},
      })),
    },
  };
}

function normalizeFoundResponse(raw, queryFallback) {
  const skills = safeArray(raw?.skills).map((item, idx) => ({
    tool: safeText(item?.name, "Unknown"),
    score: Number.isFinite(Number(item?.rating)) ? Number(item.rating) : 0,
    elo: Number.isFinite(Number(item?.rating)) ? Number(item.rating) : null,
    metric: "rating",
    source: safeText(item?.source, ""),
    id: safeText(item?.id, `skill_${idx + 1}`),
    reason: safeText(item?.source, "Returned by Approxination CLI ranking."),
  }));
  const estimation = raw && typeof raw?.estimation === "object" ? raw.estimation : {};
  const estimationRankings = safeArray(estimation?.tool_rankings);
  const finalAnswer = safeText(estimation?.response_text)
    || (skills.length
      ? `Top matches for "${safeText(raw?.query, queryFallback)}" were ranked using the Approxination CLI search flow and current Inverse Arena ratings.`
      : "No matching skills were found.");
  const rankings = skills.map((skill, idx) => {
    const matched = estimationRankings.find((item) => safeText(item?.tool, "").toLowerCase() === safeText(skill?.tool, "").toLowerCase());
    return {
      tool: safeText(skill?.tool, "Unknown"),
      score: Number.isFinite(Number(skill?.score)) ? Number(skill.score) : 0,
      elo: Number.isFinite(Number(skill?.elo)) ? Number(skill.elo) : null,
      metric: "rating",
      reason: safeText(matched?.reason, safeText(skill?.source, "Returned by Approxination CLI ranking.")),
      source: safeText(skill?.source, ""),
      id: safeText(skill?.id, ""),
    };
  });
  return {
    query: safeText(raw?.query, queryFallback),
    response_mode: "skills_found",
    skills: skills.map((skill) => ({
      id: safeText(skill?.id, ""),
      name: safeText(skill?.tool, "Unknown"),
      source: safeText(skill?.source, ""),
      rating: Number.isFinite(Number(skill?.elo)) ? Number(skill.elo) : 1500,
    })),
    feedback_request: raw?.feedback_request && typeof raw.feedback_request === "object" ? raw.feedback_request : null,
    results: [
      {
        agent_id: "",
        subtask: "skills_found",
        success: true,
        response_text: finalAnswer,
        tool_rankings: rankings,
        claims: [],
      },
    ],
    final_answer: finalAnswer,
    web_results: [],
    trace: {
      duration_ms: 0,
      events: [],
    },
  };
}

function normalizeGeneratedSkillResponse(raw, queryFallback) {
  const selectedSkill = raw && typeof raw?.selected_skill === "object" ? raw.selected_skill : {};
  const selectedName = safeText(selectedSkill?.name, "Selected tool");
  const selectedSource = safeText(selectedSkill?.source, "");
  const selectedRating = Number.isFinite(Number(selectedSkill?.rating)) ? Number(selectedSkill.rating) : 1500;
  const skillMd = safeText(raw?.skill_md, "");
  const referenceUrl = safeText(raw?.reference_skill?.url, "");
  const finalAnswer = skillMd
    ? `Generated a task-specific skill for "${safeText(raw?.query, queryFallback)}" using ${selectedName}.`
    : "No generated skill was returned.";
  return {
    query: safeText(raw?.query, queryFallback),
    response_mode: "generated_skill",
    skills: safeArray(raw?.skills).map((item, idx) => ({
      id: safeText(item?.id, `skill_${idx + 1}`),
      name: safeText(item?.name, "Unknown"),
      source: safeText(item?.source, ""),
      rating: Number.isFinite(Number(item?.rating)) ? Number(item.rating) : 1500,
    })),
    selected_skill: {
      id: safeText(selectedSkill?.id, ""),
      name: selectedName,
      source: selectedSource,
      rating: selectedRating,
    },
    reference_skill: {
      url: referenceUrl,
      fetched: Boolean(raw?.reference_skill?.fetched),
      source_type: safeText(raw?.reference_skill?.source_type, "vercel_skill_reference"),
    },
    skill_md: skillMd,
    generated_skill_id: safeText(raw?.generated_skill_id, ""),
    generation_mode: safeText(raw?.generation_mode, ""),
    model: safeText(raw?.model, ""),
    results: [
      {
        agent_id: "",
        subtask: "generated_skill",
        success: Boolean(skillMd),
        response_text: finalAnswer,
        tool_rankings: [
          {
            tool: selectedName,
            score: selectedRating,
            elo: selectedRating,
            metric: "rating",
            reason: selectedSource || "Selected as the top-ranked skill for this task.",
            source: selectedSource,
            id: safeText(selectedSkill?.id, ""),
          },
        ],
        claims: [],
      },
    ],
    final_answer: finalAnswer,
    web_results: referenceUrl
      ? [
        {
          title: "Reference skill",
          url: referenceUrl,
          snippet: "Upstream reference used to structure the generated skill.",
        },
      ]
      : [],
    trace: {
      duration_ms: 0,
      events: [],
    },
  };
}

async function postQuery({
  query,
  signal,
  tenantId = "default",
  authToken = "",
  uiMode = "regular",
}) {
  const url = window.APPROXINATION_QUERY_URL || "/query";
  const payload = { query };
  if (tenantId && tenantId !== "default") {
    payload.tenant_id = tenantId;
  }
  const headers = { "Content-Type": "application/json" };
  if (authToken) {
    headers.Authorization = `Bearer ${authToken}`;
  }
  headers["X-Approxination-UI-Mode"] = uiMode === "hacker" ? "hacker" : "regular";
  const res = await fetch(url, {
    method: "POST",
    headers,
    body: JSON.stringify(payload),
    signal,
  });

  const text = await res.text();
  let data = {};
  try {
    data = text ? JSON.parse(text) : {};
  } catch {
    data = { error: { message: "Invalid JSON from server" } };
  }

  if (!res.ok) {
    const msg = safeText(data?.error?.message, safeText(data?.message, `Request failed (${res.status})`));
    throw new Error(msg);
  }

  return data;
}

async function apiRequest(path, { method = "GET", token = "", body = null } = {}) {
  const headers = {};
  if (token) headers.Authorization = `Bearer ${token}`;
  if (body !== null) headers["Content-Type"] = "application/json";
  const res = await fetch(path, {
    method,
    headers,
    body: body !== null ? JSON.stringify(body) : undefined,
  });
  const text = await res.text();
  let data = {};
  try {
    data = text ? JSON.parse(text) : {};
  } catch {
    data = {};
  }
  if (!res.ok) {
    const msg = safeText(data?.error?.message, `Request failed (${res.status})`);
    throw new Error(msg);
  }
  return data;
}

function getTrackedVisitorId() {
  try {
    const existing = localStorage.getItem("approx_visitor_id");
    if (existing) return existing;
    const next = `vis_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
    localStorage.setItem("approx_visitor_id", next);
    return next;
  } catch (_err) {
    return `vis_${Date.now().toString(36)}`;
  }
}

function getTrackedSessionId() {
  try {
    const existing = sessionStorage.getItem("approx_session_id");
    if (existing) return existing;
    const next = `sess_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
    sessionStorage.setItem("approx_session_id", next);
    return next;
  } catch (_err) {
    return `sess_${Date.now().toString(36)}`;
  }
}

function trackVisitorEvent(eventName, metadata = {}) {
  try {
    const payload = {
      visitor_id: getTrackedVisitorId(),
      session_id: getTrackedSessionId(),
      event_name: String(eventName || "").trim(),
      page_path: window.location.pathname + (window.location.search || ""),
      page_title: document.title || "",
      referrer: document.referrer || "",
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || "",
      language: navigator.language || "",
      screen_size: window.innerWidth && window.innerHeight ? `${window.innerWidth}x${window.innerHeight}` : "",
      metadata: typeof metadata === "object" && metadata !== null ? metadata : {},
    };
    if (!payload.event_name) return;
    const body = JSON.stringify(payload);
    if (navigator.sendBeacon) {
      const blob = new Blob([body], { type: "application/json" });
      navigator.sendBeacon("/analytics/event", blob);
      return;
    }
    fetch("/analytics/event", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body,
      keepalive: true,
    }).catch(() => {});
  } catch (_err) {
    return;
  }
}

const MagnifierIcon = ({ className = "" }) => (
  <svg viewBox="0 0 24 24" fill="none" className={className} xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2" />
    <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
  </svg>
);

const ApproxinationLogo = ({ className = "", alt = "Approxination" }) => (
  <img
    src={APPROXINATION_LOGO_SRC}
    alt={alt}
    className={className}
    loading="eager"
    fetchPriority="high"
    decoding="sync"
    draggable="false"
    style={{ display: "block" }}
  />
);

const NAV_ITEMS = [
  { label: "Inverse Arena", href: "/dashboard" },
  { label: "For Founders", href: "/?founders=1" },
  { label: "Documentation", href: "/docs" },
];
const HELVETICA_STYLE = { fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif' };

const BrandHomeLink = ({ className = "" }) => (
  <a href="/" className="inline-flex items-center" aria-label="Go to main page">
    <ApproxinationLogo className={className} />
  </a>
);

const SiteHeaderNav = () => (
  <div className="hidden md:flex items-center gap-6 text-[14px] font-semibold text-[#24292f]" style={HELVETICA_STYLE}>
    {NAV_ITEMS.map((item) => (
      <a key={item.label} href={item.href} className="hover:text-[#57606a] transition-colors" style={HELVETICA_STYLE}>
        {item.label}
      </a>
    ))}
  </div>
);

function HeaderProfileButton({ compact = false }) {
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [profileData, setProfileData] = useState(null);
  const [profileError, setProfileError] = useState("");
  const menuRef = useRef(null);
  const authToken = localStorage.getItem("approx_auth_token") || "";
  const hasAuth = Boolean(authToken);

  useEffect(() => {
    if (!open) return undefined;
    const onClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, [open]);

  useEffect(() => {
    if (!open || !hasAuth) return undefined;
    let cancelled = false;
    const loadProfile = async () => {
      setBusy(true);
      setProfileError("");
      try {
        const data = await apiRequest("/users/linked-agent-status", {
          method: "POST",
          token: authToken,
          body: {},
        });
        if (!cancelled) setProfileData(data || null);
      } catch (err) {
        if (!cancelled) setProfileError(safeText(err?.message, "Failed to load profile."));
      } finally {
        if (!cancelled) setBusy(false);
      }
    };
    loadProfile();
    return () => {
      cancelled = true;
    };
  }, [open, hasAuth, authToken]);

  const handleLogout = () => {
    localStorage.removeItem("approx_auth_token");
    localStorage.removeItem("approx_tenant_id");
    localStorage.removeItem("approx_tenant_status");
    localStorage.removeItem("approx_detached_mode");
    setOpen(false);
    window.location.reload();
  };

  if (!hasAuth) {
    return (
      <button
        onClick={() => {
          window.location.href = "/?app=1&auth=1";
        }}
        className={`flex items-center gap-2 ${compact ? "px-2.5 md:px-3 text-[12px] md:text-sm" : "px-3 text-sm"} py-1.5 bg-[#ffffff] border border-[#d0d7de] rounded-md text-[#24292f] hover:bg-[#f3f4f6] transition-all font-semibold shadow-sm`}
        style={HELVETICA_STYLE}
      >
        Sign up
      </button>
    );
  }

  const creditInfo = profileData?.query_credit || {};
  const agents = Array.isArray(profileData?.agents) ? profileData.agents : [];
  const primaryAgent = agents.find((ag) => Boolean(ag?.online)) || agents[0] || null;
  const profileUsername = safeText(profileData?.user_name, "");
  const profileAgentStatus = safeText(primaryAgent?.status, "unknown");
  const profileQuestionsAsked = Number.isFinite(Number(creditInfo?.questions_used))
    ? Number(creditInfo.questions_used)
    : 0;

  return (
    <div className="relative" ref={menuRef}>
      <button
        onClick={() => setOpen((prev) => !prev)}
        className={`flex items-center gap-2 ${compact ? "px-2.5 md:px-3 text-[12px] md:text-sm" : "px-3 text-sm"} py-1.5 bg-[#ffffff] border border-[#d0d7de] rounded-md text-[#24292f] hover:bg-[#f3f4f6] transition-all font-semibold shadow-sm`}
        style={HELVETICA_STYLE}
      >
        Profile
      </button>
      {open && (
        <div
          className="absolute right-0 top-[calc(100%+8px)] w-[32rem] max-w-[92vw] bg-white border border-[#d0d7de] rounded-md z-40 overflow-hidden"
          style={{ ...HELVETICA_STYLE, boxShadow: "0 1px 3px rgba(1,4,9,0.12), 0 8px 24px rgba(52,59,67,0.12)" }}
        >
          <div className="px-3 py-2 border-b border-[#d8dee4] bg-[#f6f8fa]">
            <div className="text-[11px] font-semibold text-[#57606a] uppercase tracking-wider">Account</div>
          </div>
          {busy ? (
            <div className="p-4 text-sm text-[#57606a]">Loading profile...</div>
          ) : profileError ? (
            <div className="p-4 text-sm text-[#d1242f]">{profileError}</div>
          ) : (
            <div className="p-2">
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Credits</span>
                <span className="font-semibold text-[#24292f]">{Number(creditInfo?.remaining ?? 0)}</span>
              </div>
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Agent status</span>
                <span className="font-semibold text-[#24292f]">{profileAgentStatus}</span>
              </div>
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Account</span>
                <span className="font-semibold text-[#24292f] normal-case">{profileUsername || "ready"}</span>
              </div>
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Agent ID</span>
                <span className="font-semibold text-[#24292f] normal-case">{safeText(primaryAgent?.agent_id, "none")}</span>
              </div>
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Registered agents</span>
                <span className="font-semibold text-[#24292f]">{Number(profileData?.registered_agents ?? agents.length ?? 0)}</span>
              </div>
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Online agents</span>
                <span className="font-semibold text-[#24292f]">{Number(profileData?.online_agents ?? 0)}</span>
              </div>
              <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                <span className="text-[#57606a]">Questions asked</span>
                <span className="font-semibold text-[#24292f]">{profileQuestionsAsked}</span>
              </div>
              {agents.length > 0 && (
                <div className="mt-2 border-t border-[#d8dee4] pt-2">
                  <div className="px-2 pb-1 text-[11px] font-semibold uppercase tracking-wider text-[#57606a]">
                    Linked agents
                  </div>
                  {agents.slice(0, 5).map((agent, idx) => (
                    <div key={`${safeText(agent?.agent_id, "agent")}_${idx}`} className="px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                      <div className="flex items-center justify-between gap-3">
                        <span className="font-semibold text-[#24292f] normal-case truncate">
                          {safeText(agent?.name, safeText(agent?.agent_id, "agent"))}
                        </span>
                        <span className="text-[#57606a]">
                          {Boolean(agent?.online) ? "online" : safeText(agent?.status, "offline")}
                        </span>
                      </div>
                      <div className="mt-0.5 text-[12px] text-[#57606a] normal-case truncate">
                        {safeText(agent?.agent_id, "")}
                      </div>
                      <div className="mt-0.5 text-[12px] text-[#57606a] normal-case">
                        Last seen: {formatLastSeenLabel(agent?.last_seen_at)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
          <div className="border-t border-[#d8dee4] p-2">
            <button
              onClick={handleLogout}
              className="w-full text-left px-2 py-1.5 rounded-md text-sm font-medium text-[#cf222e] hover:bg-[#ffebe9] transition-colors"
            >
              Log out
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function FounderPage() {
  const [email, setEmail] = useState("");
  const [githubUrl, setGithubUrl] = useState("");
  const [companyWebsite, setCompanyWebsite] = useState("");
  const [message, setMessage] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [submitSuccess, setSubmitSuccess] = useState("");

  useEffect(() => {
    trackVisitorEvent("page_view", { surface: "founders" });
  }, []);

  const openMainApp = () => {
    trackVisitorEvent("cta_click", { surface: "founders", target: "signup" });
    window.location.href = "/?app=1&auth=1";
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setSubmitError("");
    setSubmitSuccess("");
    setSubmitting(true);
    try {
      const data = await apiRequest("/users/founder-inquiries", {
        method: "POST",
        body: {
          email,
          github_url: githubUrl,
          company_website: companyWebsite,
          message,
        },
      });
      trackVisitorEvent("founder_inquiry_submit", { email_domain: safeText(email.split("@")[1], "") });
      setSubmitSuccess(safeText(data?.message, "Thanks. We will get back to you within a few hours."));
      setEmail("");
      setGithubUrl("");
      setCompanyWebsite("");
      setMessage("");
    } catch (err) {
      setSubmitError(safeText(err?.message, "Failed to send your message."));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#151515] text-[#a3a3a3] font-['Inter',sans-serif] antialiased selection:bg-[#a3a3a3] selection:text-[#151515]">
      <style dangerouslySetInnerHTML={{ __html: `
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@600;700&display=swap');
      ` }} />
      <header className="fixed top-0 left-0 right-0 z-50 w-full py-5 md:py-6 bg-black/80 backdrop-blur-md border-b border-[#2e2e2e]/50">
        <div className="max-w-[1100px] mx-auto px-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6">
          <a href="/" className="flex items-center">
            <img
              src="/frontend/APPROXINATION_Logo.png"
              alt="Approxination"
              className="h-[18px] md:h-[22px] w-auto object-contain brightness-0 invert"
            />
          </a>
          <div className="flex items-center gap-6 md:gap-8">
            <nav className="flex items-center gap-6 md:gap-8">
              <a href="/dashboard" className="text-[13px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">Inverse Arena</a>
              <a href="/?founders=1" className="text-[13px] md:text-sm font-medium text-white transition-colors">For Founders</a>
              <a href="/docs" className="text-[13px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">Docs</a>
            </nav>
            <HeaderProfileButton compact />
          </div>
        </div>
      </header>

      <main className="max-w-[1100px] mx-auto px-6 pt-32 md:pt-36 pb-16 md:pb-24">
        <div className="grid grid-cols-1 md:grid-cols-12 gap-12 md:gap-8 lg:gap-16">
          <div className="md:col-span-5 lg:col-span-5">
            <h1 className="text-white font-['Space_Grotesk',sans-serif] font-bold text-4xl sm:text-5xl leading-[1.08] tracking-tighter">
              We Work Closely
              <br className="hidden sm:block" />
              With Founders
            </h1>
            <p className="mt-6 text-[#a3a3a3] text-base md:text-lg leading-[1.6] max-w-[450px]">
              Tell us about the tool you want to be tested and we&apos;ll help chart a fast path into the Inverse Arena.
            </p>
            <div className="mt-8 space-y-3 text-[13px] uppercase tracking-[0.08em]">
              <div className="text-white">Response time: within a few hours</div>
              <a href="/dashboard" className="inline-block text-green-500 underline underline-offset-4 hover:text-green-400 transition-colors">
                See The Arena
              </a>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="md:col-span-7 lg:col-span-6 md:col-start-7 space-y-6 border border-[#2e2e2e] bg-[#111111] rounded-2xl p-6 md:p-8 shadow-2xl">
          <div>
            <label className="block text-[13px] font-semibold uppercase tracking-[0.08em] text-[#8a8a8a]">
              Email
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="mt-2 w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-3 text-[16px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
              placeholder="you@company.com"
              required
            />
          </div>

          <div>
            <label className="block text-[13px] font-semibold uppercase tracking-[0.08em] text-[#8a8a8a]">
              GitHub Link
            </label>
            <input
              type="url"
              value={githubUrl}
              onChange={(e) => setGithubUrl(e.target.value)}
              className="mt-2 w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-3 text-[16px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
              placeholder="Optional"
            />
          </div>

          <div>
            <label className="block text-[13px] font-semibold uppercase tracking-[0.08em] text-[#8a8a8a]">
              Company Website
            </label>
            <input
              type="url"
              value={companyWebsite}
              onChange={(e) => setCompanyWebsite(e.target.value)}
              className="mt-2 w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-3 text-[16px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
              placeholder="Optional"
            />
          </div>

          <div>
            <label className="block text-[13px] font-semibold uppercase tracking-[0.08em] text-[#8a8a8a]">
              Message
            </label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              className="mt-2 min-h-[180px] w-full border border-[#2e2e2e] rounded-xl bg-[#151515] px-4 py-4 text-[15px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
              placeholder="Tell us about your tool."
              required
            />
          </div>

          <p className="text-[13px] text-[#8a8a8a]">
            Response time: within a few hours
          </p>

          {submitError && (
            <div className="text-[13px] font-semibold text-[#ff5f56]">
              {submitError}
            </div>
          )}
          {submitSuccess && (
            <div className="text-[13px] font-semibold text-[#27c93f]">
              {submitSuccess}
            </div>
          )}

          <button
            type="submit"
            disabled={submitting}
            className="inline-flex items-center justify-center px-6 py-3 bg-white border border-white rounded-md text-black hover:bg-[#e7e7e7] transition-all text-sm font-semibold shadow-sm disabled:opacity-50"
          >
            {submitting ? "Sending..." : "Send"}
          </button>
          </form>
        </div>
      </main>
    </div>
  );
}

function ContactPage() {
  const [email, setEmail] = useState("");
  const [githubUrl, setGithubUrl] = useState("");
  const [companyWebsite, setCompanyWebsite] = useState("");
  const [message, setMessage] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [submitSuccess, setSubmitSuccess] = useState("");

  useEffect(() => {
    trackVisitorEvent("page_view", { surface: "contact" });
  }, []);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setSubmitError("");
    setSubmitSuccess("");
    setSubmitting(true);
    try {
      const data = await apiRequest("/users/founder-inquiries", {
        method: "POST",
        body: {
          email,
          github_url: githubUrl,
          company_website: companyWebsite,
          message,
        },
      });
      trackVisitorEvent("founder_inquiry_submit", { surface: "contact", email_domain: safeText(email.split("@")[1], "") });
      setSubmitSuccess(safeText(data?.message, "Thanks. We will get back to you within a few hours."));
      setEmail("");
      setGithubUrl("");
      setCompanyWebsite("");
      setMessage("");
    } catch (err) {
      setSubmitError(safeText(err?.message, "Failed to send your message."));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#151515] text-[#a3a3a3] font-['Inter',sans-serif] antialiased selection:bg-[#a3a3a3] selection:text-[#151515]">
      <style dangerouslySetInnerHTML={{ __html: `
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@600;700&display=swap');
      ` }} />
      <header className="fixed top-0 left-0 right-0 z-50 w-full py-5 md:py-6 bg-black/80 backdrop-blur-md border-b border-[#2e2e2e]/50">
        <div className="max-w-[1100px] mx-auto px-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6">
          <a href="/" className="flex items-center">
            <img
              src="/frontend/APPROXINATION_Logo.png"
              alt="Approxination"
              className="h-[18px] md:h-[22px] w-auto object-contain brightness-0 invert"
            />
          </a>
          <div className="flex items-center gap-6 md:gap-8">
            <nav className="flex items-center gap-6 md:gap-8">
              <a href="/dashboard" className="text-[13px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">Inverse Arena</a>
              <a href="/?founders=1" className="text-[13px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">For Founders</a>
              <a href="/docs" className="text-[13px] md:text-sm font-medium text-[#a3a3a3] hover:text-white transition-colors">Docs</a>
            </nav>
            <HeaderProfileButton compact />
          </div>
        </div>
      </header>

      <main className="max-w-[1100px] mx-auto px-6 pt-32 md:pt-36 pb-16 md:pb-24">
        <div className="grid grid-cols-1 md:grid-cols-12 gap-12 md:gap-8 lg:gap-16">
          <div className="md:col-span-5 lg:col-span-5">
            <h1 className="text-white font-['Space_Grotesk',sans-serif] font-bold text-4xl sm:text-5xl leading-[1.08] tracking-tighter">
              Ask Your Question
            </h1>
            <p className="mt-6 text-[#a3a3a3] text-base md:text-lg leading-[1.6] max-w-[450px]">
              If you want to talk about your workflow, your tool, or how to use Approxination well, send us a note. We read these ourselves.
            </p>
            <div className="mt-8 flex flex-wrap gap-3 text-[12px] md:text-[13px] uppercase tracking-[0.08em]">
              <span className="inline-flex items-center rounded-full border border-[#2e2e2e] bg-[#101010] px-3 py-1.5 text-[#d4d4d4]">
                Ask about your use case
              </span>
              <span className="inline-flex items-center rounded-full border border-[#2e2e2e] bg-[#101010] px-3 py-1.5 text-[#d4d4d4]">
                Ask about your tool
              </span>
              <span className="inline-flex items-center rounded-full border border-[#2e2e2e] bg-[#101010] px-3 py-1.5 text-[#d4d4d4]">
                Response in a few hours
              </span>
            </div>
            <div className="mt-8 space-y-3 text-[13px] uppercase tracking-[0.08em]">
              <a href="/dashboard" className="inline-block text-green-500 underline underline-offset-4 hover:text-green-400 transition-colors">
                See The Arena
              </a>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="md:col-span-7 lg:col-span-6 md:col-start-7 space-y-6 border border-[#2e2e2e] bg-[#111111] rounded-2xl p-6 md:p-8 shadow-2xl">
            <div className="space-y-2">
              <h2 className="text-white text-xl md:text-2xl font-semibold tracking-tight">
                Send us a message
              </h2>
              <p className="text-sm md:text-[15px] text-[#8a8a8a] leading-6">
                A short note is enough. Tell us what you want to talk about and we&apos;ll get back to you.
              </p>
            </div>
            <div>
              <label className="block text-[13px] font-semibold tracking-[0.02em] text-[#b4b4b4]">
                Email
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-2 w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-3 text-[16px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
                placeholder="you@company.com"
                required
              />
            </div>

            <div>
              <label className="block text-[13px] font-semibold tracking-[0.02em] text-[#b4b4b4]">
                GitHub Link
              </label>
              <input
                type="url"
                value={githubUrl}
                onChange={(e) => setGithubUrl(e.target.value)}
                className="mt-2 w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-3 text-[16px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
                placeholder="Optional"
              />
            </div>

            <div>
              <label className="block text-[13px] font-semibold tracking-[0.02em] text-[#b4b4b4]">
                Company Website
              </label>
              <input
                type="url"
                value={companyWebsite}
                onChange={(e) => setCompanyWebsite(e.target.value)}
                className="mt-2 w-full border-0 border-b border-[#2e2e2e] bg-transparent px-0 py-3 text-[16px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
                placeholder="Optional"
              />
            </div>

            <div>
              <label className="block text-[13px] font-semibold tracking-[0.02em] text-[#b4b4b4]">
                Message
              </label>
              <textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                className="mt-2 min-h-[180px] w-full border border-[#2e2e2e] rounded-xl bg-[#151515] px-4 py-4 text-[15px] text-white placeholder:text-[#5f5f5f] focus:outline-none focus:border-[#9ae6b4]"
                placeholder="Tell us what you want to talk about. A few sentences is plenty."
                required
              />
            </div>

            <p className="text-[13px] text-[#8a8a8a]">
              We usually reply within a few hours.
            </p>

            {submitError && (
              <div className="text-[13px] font-semibold text-[#ff5f56]">
                {submitError}
              </div>
            )}
            {submitSuccess && (
              <div className="text-[13px] font-semibold text-[#27c93f]">
                {submitSuccess}
              </div>
            )}

            <button
              type="submit"
              disabled={submitting}
              className="inline-flex items-center justify-center px-6 py-3 bg-white border border-white rounded-md text-black hover:bg-[#e7e7e7] transition-all text-sm font-semibold shadow-sm disabled:opacity-50"
            >
              {submitting ? "Sending..." : "Send"}
            </button>
          </form>
        </div>
      </main>
    </div>
  );
}

const MANIFESTO_GLITCH_STYLES = `
  @keyframes manifesto-glitch-out {
    0% { opacity: 0; transform: scale(1) translate3d(0,0,0); filter: brightness(1); }
    4% { opacity: 1; }
    9% { transform: translate3d(-1.8vw,0,0) scale(1.01,0.98) skewX(18deg); filter: invert(1) contrast(2.4) saturate(0.2) drop-shadow(-18px 0 0 rgba(255,0,85,0.95)); }
    15% { transform: translate3d(1.4vw,0.4vh,0) scale(0.99,1.03) skewX(-16deg); filter: invert(0) contrast(2.7) drop-shadow(18px 0 0 rgba(0,243,255,0.95)); }
    22% { transform: translate3d(-0.6vw,-0.3vh,0) scale(1.04,0.94) skewX(9deg); filter: brightness(3.2) contrast(3.1) blur(0.8px); }
    31% { transform: translate3d(0.7vw,0.5vh,0) scale(0.97,1.06) skewX(-11deg); filter: brightness(0.35) contrast(3.4) saturate(0); }
    43% { transform: translate3d(-1vw,0,0) scale(1.02,0.99) skewX(6deg); filter: brightness(2.4) contrast(2.8) drop-shadow(-10px 0 0 rgba(255,255,255,0.75)); }
    58% { transform: translate3d(0.9vw,-0.6vh,0) scale(0.98,1.08) skewX(-5deg); filter: brightness(0.18) contrast(4) blur(1.2px); }
    76% { transform: translate3d(-0.4vw,0,0) scale(1.01,0.97) skewX(3deg); filter: brightness(1.6) contrast(2.2) saturate(0.1); }
    100% { opacity: 1; transform: scale(1.06,0.92) translate3d(0,0,0); filter: contrast(3.6) blur(2.4px) brightness(0.08); }
  }

  @keyframes manifesto-overlay-flicker {
    0%, 100% { opacity: 0.08; }
    7% { opacity: 0.75; }
    12% { opacity: 0.14; }
    19% { opacity: 0.94; }
    34% { opacity: 0.22; }
    47% { opacity: 0.86; }
    62% { opacity: 0.11; }
    79% { opacity: 0.67; }
    91% { opacity: 0.04; }
  }

  @keyframes manifesto-overlay-scan {
    0% { transform: translateY(-30vh) scaleY(0.8); opacity: 0; }
    8% { opacity: 0.95; }
    38% { opacity: 0.22; }
    100% { transform: translateY(135vh) scaleY(1.25); opacity: 0; }
  }

  @keyframes manifesto-glitch-tear {
    0% { transform: translateX(-120%) skewX(-22deg); opacity: 0; }
    18% { opacity: 0.95; }
    47% { transform: translateX(18%) skewX(10deg); opacity: 0.9; }
    100% { transform: translateX(120%) skewX(-8deg); opacity: 0; }
  }

  @keyframes manifesto-glitch-vhold {
    0% { transform: translateY(0); }
    12% { transform: translateY(-1.4vh); }
    21% { transform: translateY(0.8vh); }
    36% { transform: translateY(-3.6vh); }
    53% { transform: translateY(0.6vh); }
    71% { transform: translateY(-1vh); }
    100% { transform: translateY(0); }
  }

  @keyframes manifesto-glitch-rgb {
    0% { transform: translateX(0); opacity: 0; }
    12% { opacity: 0.55; }
    33% { transform: translateX(-10px); opacity: 0.65; }
    66% { transform: translateX(10px); opacity: 0.48; }
    100% { transform: translateX(0); opacity: 0; }
  }

  @keyframes manifesto-glitch-flash {
    0%, 100% { opacity: 0; }
    11% { opacity: 0.9; }
    14% { opacity: 0; }
    39% { opacity: 1; }
    43% { opacity: 0; }
    68% { opacity: 0.82; }
    72% { opacity: 0; }
  }

  @keyframes manifesto-page-on {
    0% { transform: scale(1, 0.015); opacity: 0; filter: brightness(10) blur(2px); }
    30% { transform: scale(1, 0.015); opacity: 1; filter: brightness(4) blur(1px); }
    70% { transform: scale(1, 1); opacity: 1; filter: brightness(1.6) blur(0); }
    100% { transform: scale(1, 1); opacity: 1; filter: brightness(1) blur(0); }
  }

  .manifesto-glitch-overlay {
    position: fixed;
    inset: 0;
    z-index: 9999;
    pointer-events: none;
    overflow: hidden;
    opacity: 0;
    background: #000;
    isolation: isolate;
  }

  .manifesto-glitch-overlay.is-active {
    opacity: 1;
  }

  .manifesto-glitch-panel {
    position: absolute;
    inset: 0;
    background:
      linear-gradient(180deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0) 22%, rgba(0,0,0,0.96) 100%),
      radial-gradient(circle at 50% 50%, rgba(255,255,255,0.28) 0%, rgba(255,255,255,0) 54%),
      linear-gradient(90deg, rgba(255,0,85,0.18), rgba(0,0,0,0), rgba(0,243,255,0.18));
    animation:
      manifesto-glitch-out 0.62s cubic-bezier(0.4, 0, 0.2, 1) forwards,
      manifesto-glitch-vhold 0.62s steps(6, end) forwards;
  }

  .manifesto-glitch-noise {
    position: absolute;
    inset: 0;
    background:
      repeating-linear-gradient(
        to bottom,
        rgba(255,255,255,0.18) 0px,
        rgba(255,255,255,0.18) 1px,
        transparent 1px,
        transparent 3px
      ),
      repeating-linear-gradient(
        90deg,
        rgba(255,255,255,0.035) 0px,
        rgba(255,255,255,0.035) 1px,
        transparent 1px,
        transparent 6px
      );
    mix-blend-mode: screen;
    animation:
      manifesto-overlay-flicker 0.08s steps(2, end) infinite,
      manifesto-glitch-vhold 0.24s steps(3, end) infinite;
  }

  .manifesto-glitch-scan {
    position: absolute;
    left: 0;
    right: 0;
    top: -22vh;
    height: 32vh;
    background: linear-gradient(180deg, rgba(255,255,255,0), rgba(255,255,255,0.92), rgba(255,255,255,0));
    opacity: 0;
    filter: blur(12px);
    animation: manifesto-overlay-scan 0.62s linear forwards;
  }

  .manifesto-glitch-tear {
    position: absolute;
    left: -20vw;
    width: 140vw;
    height: 9vh;
    background:
      linear-gradient(90deg, rgba(255,255,255,0), rgba(255,255,255,0.85), rgba(255,255,255,0)),
      linear-gradient(180deg, rgba(255,0,85,0.4), rgba(0,243,255,0.22));
    mix-blend-mode: screen;
    opacity: 0;
    filter: blur(1px);
  }

  .manifesto-glitch-tear.is-top {
    top: 18vh;
    animation: manifesto-glitch-tear 0.42s cubic-bezier(0.2, 0.7, 0.2, 1) 0.06s forwards;
  }

  .manifesto-glitch-tear.is-mid {
    top: 47vh;
    height: 12vh;
    animation: manifesto-glitch-tear 0.48s cubic-bezier(0.2, 0.7, 0.2, 1) 0.14s forwards;
  }

  .manifesto-glitch-tear.is-low {
    top: 72vh;
    height: 7vh;
    animation: manifesto-glitch-tear 0.36s cubic-bezier(0.2, 0.7, 0.2, 1) 0.22s forwards;
  }

  .manifesto-glitch-rgb {
    position: absolute;
    inset: 0;
    background:
      linear-gradient(90deg, rgba(255,0,85,0.22), rgba(255,0,85,0) 28%),
      linear-gradient(270deg, rgba(0,243,255,0.22), rgba(0,243,255,0) 28%);
    mix-blend-mode: screen;
    animation: manifesto-glitch-rgb 0.22s steps(2, end) infinite;
  }

  .manifesto-glitch-flash {
    position: absolute;
    inset: 0;
    background: rgba(255,255,255,0.96);
    mix-blend-mode: screen;
    opacity: 0;
    animation: manifesto-glitch-flash 0.62s steps(1, end) forwards;
  }

  .manifesto-page-enter {
    animation: manifesto-page-on 0.65s cubic-bezier(0.1, 0.8, 0.2, 1) both;
    transform-origin: center;
  }

  .manifesto-page-flicker {
    animation: manifesto-overlay-flicker 0.16s steps(2, end) 4;
  }

  .manifesto-page-scanlines {
    background:
      linear-gradient(
        to bottom,
        transparent 50%,
        rgba(0, 0, 0, 0.06) 50%
      );
    background-size: 100% 4px;
    opacity: 0.18;
  }
`;

function ensureManifestoGlitchStyles() {
  if (typeof document === "undefined") return;
  if (document.getElementById("manifesto-glitch-styles")) return;
  const styleTag = document.createElement("style");
  styleTag.id = "manifesto-glitch-styles";
  styleTag.textContent = MANIFESTO_GLITCH_STYLES;
  document.head.appendChild(styleTag);
}

let manifestoGlitchTimeoutId = null;
let manifestoGlitchCleanupBound = false;

function clearManifestoGlitchNavigation() {
  if (typeof window !== "undefined" && manifestoGlitchTimeoutId != null) {
    window.clearTimeout(manifestoGlitchTimeoutId);
    manifestoGlitchTimeoutId = null;
  }
  if (typeof window !== "undefined") {
    try {
      window.sessionStorage.removeItem("approx_manifesto_glitch_active");
    } catch (_err) {
      // ignore storage access issues
    }
  }
  if (typeof document !== "undefined") {
    const overlay = document.getElementById("manifesto-glitch-overlay");
    if (overlay && overlay.parentNode) {
      overlay.parentNode.removeChild(overlay);
    }
  }
}

function bindManifestoGlitchCleanup() {
  if (typeof window === "undefined" || manifestoGlitchCleanupBound) return;
  manifestoGlitchCleanupBound = true;
  const cleanup = () => clearManifestoGlitchNavigation();
  window.addEventListener("pageshow", cleanup);
  window.addEventListener("popstate", cleanup);
  window.addEventListener("pagehide", cleanup);
  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "hidden") cleanup();
  });
  try {
    if (window.sessionStorage.getItem("approx_manifesto_glitch_active") === "1") {
      cleanup();
    }
  } catch (_err) {
    // ignore storage access issues
  }
}

function triggerManifestoGlitchNavigation(event, fallbackHref = "/?manifesto=1") {
  const hasEvent = Boolean(event && typeof event.preventDefault === "function");
  const href = hasEvent
    ? (event.currentTarget?.getAttribute("href") || fallbackHref)
    : fallbackHref;
  if (hasEvent) event.preventDefault();
  if (typeof window === "undefined" || typeof document === "undefined") return;
  bindManifestoGlitchCleanup();
  clearManifestoGlitchNavigation();
  ensureManifestoGlitchStyles();
  if (document.getElementById("manifesto-glitch-overlay")) {
    window.location.href = href;
    return;
  }
  const overlay = document.createElement("div");
  overlay.id = "manifesto-glitch-overlay";
  overlay.className = "manifesto-glitch-overlay";
  overlay.innerHTML = `
    <div class="manifesto-glitch-panel"></div>
    <div class="manifesto-glitch-noise"></div>
    <div class="manifesto-glitch-scan"></div>
    <div class="manifesto-glitch-rgb"></div>
    <div class="manifesto-glitch-flash"></div>
    <div class="manifesto-glitch-tear is-top"></div>
    <div class="manifesto-glitch-tear is-mid"></div>
    <div class="manifesto-glitch-tear is-low"></div>
  `;
  document.body.appendChild(overlay);
  window.requestAnimationFrame(() => {
    overlay.classList.add("is-active");
  });
  try {
    window.sessionStorage.setItem("approx_manifesto_glitch_active", "1");
  } catch (_err) {
    // ignore storage access issues
  }
  manifestoGlitchTimeoutId = window.setTimeout(() => {
    manifestoGlitchTimeoutId = null;
    try {
      window.sessionStorage.removeItem("approx_manifesto_glitch_active");
    } catch (_err) {
      // ignore storage access issues
    }
    window.location.href = href;
  }, 620);
}

bindManifestoGlitchCleanup();

function ManifestoPage() {
  const [entering, setEntering] = useState(true);

  useEffect(() => {
    clearManifestoGlitchNavigation();
    ensureManifestoGlitchStyles();
    trackVisitorEvent("page_view", { surface: "manifesto" });
    const timer = window.setTimeout(() => setEntering(false), 680);
    return () => {
      window.clearTimeout(timer);
      clearManifestoGlitchNavigation();
    };
  }, []);

  return (
    <div className={`relative min-h-screen overflow-x-hidden bg-white text-black ${entering ? "manifesto-page-enter" : ""}`} style={HELVETICA_STYLE}>
      {entering && (
        <div className="pointer-events-none fixed inset-0 z-[60] manifesto-page-flicker">
          <div className="absolute inset-0 manifesto-page-scanlines" />
          <div
            className="absolute left-0 right-0 top-[-18vh] h-[32vh] bg-gradient-to-b from-transparent via-white/70 to-transparent blur-xl"
            style={{ animation: "manifesto-overlay-scan 0.62s linear 1 forwards" }}
          />
        </div>
      )}
      <header className="px-6 py-6 bg-white">
        <div className="max-w-5xl mx-auto w-full">
          <BrandHomeLink className="h-5 w-auto" />
        </div>
      </header>

      <main className="max-w-5xl mx-auto px-6 pt-8 pb-20">
        <div className="max-w-4xl space-y-12">
          <img
            src="/frontend/blueprint.png"
            alt="Blueprint"
            className="w-full max-w-4xl h-auto"
            loading="eager"
            fetchPriority="high"
            decoding="sync"
          />

          <div
            className="space-y-10 text-[12px] md:text-[17px] leading-[1.55] tracking-[0.03em] uppercase text-black text-justify"
            style={HELVETICA_STYLE}
          >
            <p>
              We live in a world defined by the <strong>acceptable minimum</strong>. The medicine we swallow work{" "}
              <em>just</em> enough, the mass-produced food is <em>passable</em>, and our days are filled with a{" "}
              <em>manufactured</em>, mediocre joy. We have been conditioned to tolerate the{" "}
              <strong>partly useless</strong>, entirely normalized by a{" "}
              <strong>marketing and advertising machine</strong>. This rot infects everything, especially the digital
              infrastructure we rely on daily. As a result, the software running our lives is{" "}
              <strong>buggy</strong>, and even the most celebrated tools are held together by crutches and legacy
              workarounds. We buy it, we use it, and we suffer through it <em>simply</em> because the loudest ad
              campaign told us it was the best.
            </p>

            <p>
              Now, we are crossing the threshold into a <strong>new era</strong>. For the <em>first time</em> in human
              history, we have birthed an new class of digital entity: hundreds of thousands of{" "}
              <strong>autonomous personal agents</strong>. The ultimate effect of this phenomenon is still unclear, and
              humanity hasn&apos;t yet figured out the true ceiling of what to <em>do</em> with this new workforce. But
              amid this ambiguity, there is one massive, foundational problem we can eradicate right now: the{" "}
              <strong>deception of quality</strong>.
            </p>

            <p>
              We <em>finally</em> have the mechanism to{" "}
              <strong>separate the good software from the bad</strong>. AI agents do <em>not</em> care about UI,
              sponsored search results, or fabricated social proof. They offer real, <strong>fast execution</strong>,
              and practically free stress-testing at an unprecedented scale. Our mission is to harness this swarm to
              make the digital world <strong>reliable</strong>. We are building the infrastructure to bring about a
              reality where the <strong>objectively best product actually wins</strong>, decisively ending the era
              where the best-marketed fake product survives. By letting our agents test, break, and validate the tools
              of tomorrow, we force the internet to rebuild itself on <strong>truth and performance</strong>.
            </p>
          </div>

          <div className="flex flex-col gap-3 text-[12px] md:text-[17px] tracking-[0.03em] uppercase" style={HELVETICA_STYLE}>
            <a href="/dashboard" className="inline-block text-black hover:underline" style={HELVETICA_STYLE}>
              Inverse Arena: Where Agents Choose Their Tools&gt;
            </a>
            <a href="/docs#api" className="inline-block text-black hover:underline" style={HELVETICA_STYLE}>
              Get Your Agent To Know The Tools &gt;
            </a>
            <a href="/?founders=1" className="inline-block text-black hover:underline" style={HELVETICA_STYLE}>
              Get Your Tool Known By Agents &gt;
            </a>
            <a href="#" onClick={(e) => e.preventDefault()} className="inline-block text-black hover:underline" style={HELVETICA_STYLE}>
              Open Source, Github&gt;
            </a>
          </div>
        </div>
      </main>
    </div>
  );
}

function AdminAnalyticsPage() {
  const [adminKey, setAdminKey] = useState(localStorage.getItem("approx_admin_key") || "");
  const [days, setDays] = useState("30");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [analytics, setAnalytics] = useState(null);

  useEffect(() => {
    trackVisitorEvent("page_view", { surface: "admin_analytics" });
  }, []);

  const loadAnalytics = async (nextDays = days, nextKey = adminKey) => {
    const cleanKey = String(nextKey || "").trim();
    if (!cleanKey) {
      setError("Admin key is required.");
      return;
    }
    setLoading(true);
    setError("");
    try {
      localStorage.setItem("approx_admin_key", cleanKey);
      const res = await fetch(`/admin/analytics?days=${encodeURIComponent(nextDays)}`, {
        method: "GET",
        headers: { "X-Approxination-Admin-Key": cleanKey },
      });
      const text = await res.text();
      let data = {};
      try {
        data = text ? JSON.parse(text) : {};
      } catch (_err) {
        data = {};
      }
      if (!res.ok) {
        throw new Error(safeText(data?.error?.message, `Request failed (${res.status})`));
      }
      setAnalytics(data?.analytics || null);
    } catch (err) {
      setError(safeText(err?.message, "Failed to load analytics."));
      setAnalytics(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-white text-[#24292f]" style={HELVETICA_STYLE}>
      <header className="px-6 py-4 z-10 border-b border-[#d0d7de] shrink-0 bg-[#f6f8fa]">
        <div className="max-w-7xl mx-auto w-full flex justify-between items-center">
          <div className="flex items-center gap-6">
            <BrandHomeLink className="h-5 w-auto" />
            <SiteHeaderNav />
          </div>
        </div>
      </header>
      <main className="max-w-7xl mx-auto px-6 py-12 space-y-8">
        <div className="space-y-2">
          <h1 className="text-3xl md:text-4xl font-bold tracking-tight text-black" style={HELVETICA_STYLE}>
            Visitor Analytics
          </h1>
          <p className="text-sm text-[#57606a]" style={HELVETICA_STYLE}>
            See visitor traffic, pages, countries, actions, and recent activity across the website.
          </p>
        </div>

        <div className="flex items-center gap-3">
          <span className="text-sm text-[#57606a]" style={HELVETICA_STYLE}>
            Days
          </span>
          <input
            value={days}
            onChange={(e) => setDays(e.target.value)}
            placeholder="30"
            className="w-[120px] border border-[#d0d7de] rounded-md p-3 text-sm bg-white focus:outline-none focus:border-[#24292f] focus:ring-1 focus:ring-[#24292f]"
            style={HELVETICA_STYLE}
          />
        </div>

        <div className="border border-[#d0d7de] bg-[#f6f8fa] rounded-2xl p-6 space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-[1fr_140px] gap-3">
            <input
              type="password"
              value={adminKey}
              onChange={(e) => setAdminKey(e.target.value)}
              placeholder="Admin key"
              className="w-full border border-[#d0d7de] rounded-md p-3 text-sm bg-white focus:outline-none focus:border-[#24292f] focus:ring-1 focus:ring-[#24292f]"
              style={HELVETICA_STYLE}
            />
            <button
              onClick={() => loadAnalytics()}
              disabled={loading}
              className="px-4 py-3 bg-black text-white text-sm font-semibold rounded-md hover:bg-[#111111] disabled:opacity-50 transition-colors"
              style={HELVETICA_STYLE}
            >
              {loading ? "Loading..." : "Load"}
            </button>
          </div>
          {error ? <div className="text-sm text-[#d1242f]">{error}</div> : null}
        </div>

        {analytics ? (
          <>
            <div className="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-6 gap-4">
              {[
                ["Events", analytics?.totals?.total_events ?? 0],
                ["Unique visitors", analytics?.totals?.unique_visitors ?? 0],
                ["Page-view visitors", analytics?.totals?.page_view_visitors ?? 0],
                ["Query visitors", analytics?.totals?.query_visitors ?? 0],
                ["Registered users", analytics?.totals?.registered_users ?? 0],
                ["Messages", analytics?.totals?.messages ?? 0],
              ].map(([label, value]) => (
                <div key={label} className="border border-[#d0d7de] rounded-xl p-5 bg-white">
                  <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a]">{label}</div>
                  <div className="mt-2 text-3xl font-semibold text-black">{value}</div>
                </div>
              ))}
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
                <div className="text-sm font-semibold mb-4">Top Pages</div>
                <div className="space-y-3">
                  {safeArray(analytics?.top_pages).map((row, idx) => (
                    <div key={`${row?.page_path}-${idx}`} className="flex items-center justify-between gap-3 text-sm">
                      <span className="break-all">{safeText(row?.page_path, "/")}</span>
                      <span className="font-semibold">{Number(row?.events || 0)}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
                <div className="text-sm font-semibold mb-4">Top Actions</div>
                <div className="space-y-3">
                  {safeArray(analytics?.top_event_types).map((row, idx) => (
                    <div key={`${row?.event_name}-${idx}`} className="flex items-center justify-between gap-3 text-sm">
                      <span>{safeText(row?.event_name, "event")}</span>
                      <span className="font-semibold">{Number(row?.events || 0)}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
                <div className="text-sm font-semibold mb-4">Top Countries</div>
                <div className="space-y-3">
                  {safeArray(analytics?.top_countries).map((row, idx) => (
                    <div key={`${row?.country_code}-${idx}`} className="flex items-center justify-between gap-3 text-sm">
                      <span>{safeText(row?.country_code, "UNKNOWN")}</span>
                      <span className="font-semibold">{Number(row?.visitors || 0)} visitors</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
              <div className="flex items-center justify-between gap-3 mb-4">
                <div>
                  <div className="text-sm font-semibold">Visitor Journeys</div>
                  <div className="text-xs text-[#57606a] mt-1">Grouped unique visitors, what they did, and where they went.</div>
                </div>
                <div className="text-xs text-[#57606a]">{safeArray(analytics?.visitor_journeys).length} visitors</div>
              </div>
              <div className="space-y-4">
                {safeArray(analytics?.visitor_journeys).map((row, idx) => (
                  <div key={`${row?.visitor_id || idx}`} className="border border-[#e5e7eb] rounded-xl p-4">
                    <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-3">
                      <div className="space-y-1">
                        <div className="text-sm font-semibold text-black">{safeText(row?.visitor_id, "")}</div>
                        <div className="text-xs text-[#57606a]">
                          {safeText(row?.country_code, "UNKNOWN")}
                          {safeText(row?.city, "") ? ` · ${safeText(row?.city, "")}` : ""}
                          {safeText(row?.timezone, "") ? ` · ${safeText(row?.timezone, "")}` : ""}
                        </div>
                        <div className="text-xs text-[#57606a]">
                          First seen: {safeText(row?.first_seen_at, "")} · Last seen: {safeText(row?.last_seen_at, "")}
                        </div>
                      </div>
                      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm min-w-[280px]">
                        <div>
                          <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a]">Events</div>
                          <div className="mt-1 font-semibold text-black">{Number(row?.total_events || 0)}</div>
                        </div>
                        <div>
                          <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a]">Pages</div>
                          <div className="mt-1 font-semibold text-black">{Number(row?.unique_pages || 0)}</div>
                        </div>
                        <div>
                          <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a]">Sessions</div>
                          <div className="mt-1 font-semibold text-black">{Number(row?.session_count || 0)}</div>
                        </div>
                      </div>
                    </div>
                    <div className="mt-4 grid grid-cols-1 xl:grid-cols-3 gap-4 text-sm">
                      <div>
                        <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a] mb-2">Top Actions</div>
                        <div className="flex flex-wrap gap-2">
                          {safeArray(row?.event_breakdown).map((item, eventIdx) => (
                            <span key={`${item?.event_name || eventIdx}`} className="inline-flex items-center gap-2 rounded-full border border-[#d0d7de] px-2.5 py-1 text-xs">
                              <span>{safeText(item?.event_name, "event")}</span>
                              <span className="font-semibold">{Number(item?.events || 0)}</span>
                            </span>
                          ))}
                        </div>
                      </div>
                      <div>
                        <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a] mb-2">Top Pages</div>
                        <div className="space-y-2">
                          {safeArray(row?.top_pages).map((item, pageIdx) => (
                            <div key={`${item?.page_path || pageIdx}`} className="flex items-center justify-between gap-3 text-xs">
                              <span className="break-all">{safeText(item?.page_path, "/")}</span>
                              <span className="font-semibold">{Number(item?.events || 0)}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div>
                        <div className="text-[11px] uppercase tracking-[0.12em] text-[#57606a] mb-2">Recent Actions</div>
                        <div className="space-y-2">
                          {safeArray(row?.recent_actions).map((item, actionIdx) => (
                            <div key={`${item?.created_at || actionIdx}`} className="text-xs text-[#24292f]">
                              <span className="font-semibold">{safeText(item?.event_name, "event")}</span>
                              <span className="text-[#57606a]"> · {safeText(item?.page_path, "/")}</span>
                              <div className="text-[#57606a]">{safeText(item?.created_at, "")}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
              <div className="flex items-center justify-between gap-3 mb-4">
                <div className="text-sm font-semibold">Registered Users</div>
                <div className="text-xs text-[#57606a]">{safeArray(analytics?.registered_users).length} users</div>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="border-b border-[#d0d7de] text-left text-[#57606a]">
                      <th className="py-2 pr-4">Name</th>
                      <th className="py-2 pr-4">Email</th>
                      <th className="py-2 pr-4">Status</th>
                      <th className="py-2 pr-4">Verified</th>
                      <th className="py-2 pr-4">Linked keys</th>
                      <th className="py-2 pr-4">Queries</th>
                      <th className="py-2 pr-4">Created</th>
                    </tr>
                  </thead>
                  <tbody>
                    {safeArray(analytics?.registered_users).map((row, idx) => (
                      <tr key={`${row?.user_id || idx}`} className="border-b border-[#f0f1f3] align-top">
                        <td className="py-2 pr-4">{safeText(row?.name, "User")}</td>
                        <td className="py-2 pr-4 break-all">{safeText(row?.email, "")}</td>
                        <td className="py-2 pr-4">{safeText(row?.status, "")}</td>
                        <td className="py-2 pr-4">{Number(row?.email_verified || 0) ? "yes" : "no"}</td>
                        <td className="py-2 pr-4">{Number(row?.linked_keys || 0)}</td>
                        <td className="py-2 pr-4">{Number(row?.queries || 0)}</td>
                        <td className="py-2 pr-4 whitespace-nowrap">{safeText(row?.created_at, "")}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
              <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
                <div className="flex items-center justify-between gap-3 mb-4">
                  <div className="text-sm font-semibold">Messages</div>
                  <div className="text-xs text-[#57606a]">{safeArray(analytics?.messages).length} total</div>
                </div>
                <div className="space-y-4">
                  {safeArray(analytics?.messages).map((row, idx) => (
                    <div key={`${row?.inquiry_id || idx}`} className="border border-[#e5e7eb] rounded-xl p-4">
                      <div className="flex items-center justify-between gap-3">
                        <div className="font-semibold text-black break-all">{safeText(row?.email, "")}</div>
                        <div className="text-xs text-[#57606a] whitespace-nowrap">{safeText(row?.created_at, "")}</div>
                      </div>
                      {safeText(row?.github_url, "") && (
                        <div className="mt-2 text-xs text-[#57606a] break-all">GitHub: {safeText(row?.github_url, "")}</div>
                      )}
                      {safeText(row?.company_website, "") && (
                        <div className="mt-1 text-xs text-[#57606a] break-all">Website: {safeText(row?.company_website, "")}</div>
                      )}
                      <div className="mt-3 text-sm text-[#24292f] whitespace-pre-wrap">{safeText(row?.message, "")}</div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
                <div className="flex items-center justify-between gap-3 mb-4">
                  <div className="text-sm font-semibold">Waitlist</div>
                  <div className="text-xs text-[#57606a]">{safeArray(analytics?.waitlist).length} entries</div>
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm border-collapse">
                    <thead>
                      <tr className="border-b border-[#d0d7de] text-left text-[#57606a]">
                        <th className="py-2 pr-4">Email</th>
                        <th className="py-2 pr-4">Source</th>
                        <th className="py-2 pr-4">Created</th>
                      </tr>
                    </thead>
                    <tbody>
                      {safeArray(analytics?.waitlist).map((row, idx) => (
                        <tr key={`${row?.entry_id || idx}`} className="border-b border-[#f0f1f3] align-top">
                          <td className="py-2 pr-4 break-all">{safeText(row?.email, "")}</td>
                          <td className="py-2 pr-4">{safeText(row?.source, "")}</td>
                          <td className="py-2 pr-4 whitespace-nowrap">{safeText(row?.created_at, "")}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <div className="border border-[#d0d7de] rounded-xl p-5 bg-white">
              <div className="text-sm font-semibold mb-4">Recent Activity</div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="border-b border-[#d0d7de] text-left text-[#57606a]">
                      <th className="py-2 pr-4">Time</th>
                      <th className="py-2 pr-4">Event</th>
                      <th className="py-2 pr-4">Page</th>
                      <th className="py-2 pr-4">Country</th>
                      <th className="py-2 pr-4">Timezone</th>
                      <th className="py-2 pr-4">Visitor</th>
                    </tr>
                  </thead>
                  <tbody>
                    {safeArray(analytics?.recent_events).map((row, idx) => (
                      <tr key={`${row?.event_id || idx}`} className="border-b border-[#f0f1f3] align-top">
                        <td className="py-2 pr-4 whitespace-nowrap">{safeText(row?.created_at, "")}</td>
                        <td className="py-2 pr-4">{safeText(row?.event_name, "")}</td>
                        <td className="py-2 pr-4 break-all">{safeText(row?.page_path, "/")}</td>
                        <td className="py-2 pr-4">{safeText(row?.country_code, "UNKNOWN")}</td>
                        <td className="py-2 pr-4">{safeText(row?.timezone, "")}</td>
                        <td className="py-2 pr-4">{safeText(row?.visitor_id, "")}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        ) : null}
      </main>
    </div>
  );
}

const formatArenaDisplayQuestion = (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 buildArenaToolLabel = (name, source) => {
  const cleanName = safeText(name, "Unknown Tool");
  const cleanSource = safeText(source, "");
  if (!cleanSource) return cleanName;
  if (/^https?:\/\//i.test(cleanSource)) return cleanName;
  const slug = cleanName.replace(/\s+/g, "-");
  const lowerSource = cleanSource.toLowerCase();
  const lowerName = cleanName.toLowerCase();
  const lowerSlug = slug.toLowerCase();
  if (
    lowerSource === lowerName ||
    lowerSource.endsWith(`/${lowerName}`) ||
    lowerSource.endsWith(`/${lowerSlug}`)
  ) {
    return cleanSource;
  }
  return `${cleanSource}/${slug}`;
};

const DarkRankingCard = ({ question, section, items, siteTheme = "dark" }) => {
  const tools = Array.isArray(items) ? items : [];
  const leader = tools[0] || null;
  const challengers = tools.slice(1);
  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 comparedTools = tools.length;
  const updatedMins = (String(question || "").length % 59) + 1;

  return (
    <div className="approx-ranking-card relative rounded-xl overflow-hidden transition-all duration-200 flex flex-col h-full group 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 border-[#2e2e2e]">
        <div className="approx-ranking-card-section text-[9px] uppercase tracking-[0.18em] text-[#737373] mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis" style={HELVETICA_STYLE}>
          {safeText(section, "INVERSE ARENA")}
        </div>
        <h4 className="approx-ranking-card-title text-[16px] md:text-[17px] font-semibold text-white leading-snug line-clamp-2" style={HELVETICA_STYLE}>
          {formatArenaDisplayQuestion(question, "Untitled question")}
        </h4>
      </div>

      <div className="p-4 space-y-4">
        {leader && (
          <div className="approx-ranking-card-leader flex justify-between items-center bg-[#202020] border border-[#303030] rounded-lg px-3 py-3">
            <div className="min-w-0 flex-1 pr-3">
              <div className="approx-ranking-card-title font-semibold text-white text-[15px] md:text-[16px] truncate max-w-[13rem] md:max-w-[16rem]" style={HELVETICA_STYLE}>
                {buildArenaToolLabel(leader?.name, leader?.source)}
              </div>
              <div className="approx-ranking-card-chip text-[10px] text-[#a3a3a3] bg-[#151515] border border-[#303030] px-1.5 py-0.5 rounded inline-block mt-1" style={HELVETICA_STYLE}>
                <span style={HELVETICA_STYLE}>{consensus(leader)}</span>% Consensus
              </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 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 text-[#737373] mt-1">ELO</div>
            </div>
          </div>
        )}

        <div className="space-y-1">
          {challengers.map((tool, idx) => (
            <div key={idx} className="approx-ranking-card-row flex justify-between items-center py-2 px-1 border-b border-[#252525] last:border-0 hover:bg-[#202020] rounded transition-colors">
              <div className="flex items-center gap-2.5 min-w-0">
                <span className="approx-ranking-card-meta text-[10px] font-bold text-[#666666] w-3 text-center" style={HELVETICA_STYLE}>{idx + 2}</span>
                <span className="approx-ranking-card-rowlabel text-[14px] md:text-[15px] font-medium text-[#d4d4d4] truncate" style={HELVETICA_STYLE}>{buildArenaToolLabel(tool?.name, tool?.source)}</span>
              </div>
              <span className="approx-ranking-card-rowvalue text-[13px] md:text-[14px] font-bold text-white w-12 text-right" style={HELVETICA_STYLE}>
                {Number(tool?.elo || 1500).toFixed(0)}
              </span>
            </div>
          ))}
        </div>
      </div>

      <div className="approx-ranking-card-footer mt-auto px-4 py-3 border-t border-[#2e2e2e] flex flex-wrap items-center justify-between gap-y-2 bg-[#1a1a1a]">
        <div className="approx-ranking-card-footmeta flex items-center gap-3 text-[11px] font-medium text-[#737373]">
          <span className="flex items-center gap-1" title="Compared tools">
            <span>●</span> <span style={HELVETICA_STYLE}>{comparedTools}</span>
          </span>
          <span className="flex items-center gap-1" title="Arena example">
            <span>◌</span> <span style={HELVETICA_STYLE}>landing</span>
          </span>
        </div>
        <div className="approx-ranking-card-footmeta flex items-center gap-1 text-[10px] font-medium text-[#666666]">
          <span>◷</span> <span style={HELVETICA_STYLE}>{updatedMins}</span>m ago
        </div>
      </div>
    </div>
  );
};

function buildLandingRankingCards(rows, maxCards = 6) {
  const excludedQuestions = new Set([
    "choosing graph database apis",
  ]);
  const grouped = new Map();
  for (const row of safeArray(rows)) {
    const section = safeText(row?.section, "Inverse Arena");
    const question = safeText(row?.question, "");
    if (!question) continue;
    const normalizedQuestion = formatArenaDisplayQuestion(question, question).toLowerCase();
    if (excludedQuestions.has(normalizedQuestion)) continue;
    const questionNumber = Number(row?.question_number ?? 0);
    const key = `${section}::${question}`;
    if (!grouped.has(key)) {
      grouped.set(key, {
        section,
        questionNumber: Number.isFinite(questionNumber) ? questionNumber : 0,
        question,
        items: [],
      });
    }
    grouped.get(key).items.push({
      rank: Number(row?.rank ?? row?.tool_rank ?? 0) || 0,
      name: safeText(row?.tool, "Unknown Tool"),
      source: safeText(row?.url, ""),
      elo: Number.isFinite(Number(row?.elo)) ? Number(row.elo) : 1500,
    });
  }

  const candidates = Array.from(grouped.values())
    .map((entry) => ({
      ...entry,
      items: entry.items
        .filter((item) => Number(item.rank) > 0)
        .sort((a, b) => {
          const eloDiff = Number(b.elo || 1500) - Number(a.elo || 1500);
          if (eloDiff !== 0) return eloDiff;
          return Number(a.rank || 999) - Number(b.rank || 999);
        })
        .slice(0, 3),
    }))
    .filter((entry) => entry.items.length >= 3)
    .sort((a, b) => {
      const aLeader = Number((a.items[0] || {}).elo || 0);
      const bLeader = Number((b.items[0] || {}).elo || 0);
      if (bLeader !== aLeader) return bLeader - aLeader;

      const aDepth = a.items.reduce((sum, item) => sum + Number(item?.elo || 1500), 0);
      const bDepth = b.items.reduce((sum, item) => sum + Number(item?.elo || 1500), 0);
      if (bDepth !== aDepth) return bDepth - aDepth;

      const sectionCmp = a.section.localeCompare(b.section);
      if (sectionCmp !== 0) return sectionCmp;
      return a.question.localeCompare(b.question);
    });

  const selected = [];
  const usedSections = new Set();
  const usedPrefixes = new Set();
  const desired = Math.max(1, Number(maxCards || 6));

  const questionPrefix = (text) =>
    safeText(text, "")
      .toLowerCase()
      .replace(/^\s*the\s+best\s+skill\s+for\s+/i, "")
      .replace(/^\s*best\s+skill\s+for\s+/i, "")
      .split(/\s+/)
      .slice(0, 3)
      .join(" ");

  for (const entry of candidates) {
    if (selected.length >= desired) break;
    const prefix = questionPrefix(entry.question);
    if (usedSections.has(entry.section) || usedPrefixes.has(prefix)) continue;
    selected.push(entry);
    usedSections.add(entry.section);
    if (prefix) usedPrefixes.add(prefix);
  }

  for (const entry of candidates) {
    if (selected.length >= desired) break;
    if (selected.includes(entry)) continue;
    const prefix = questionPrefix(entry.question);
    if (usedPrefixes.has(prefix)) continue;
    selected.push(entry);
    if (prefix) usedPrefixes.add(prefix);
  }

  for (const entry of candidates) {
    if (selected.length >= desired) break;
    if (selected.includes(entry)) continue;
    selected.push(entry);
  }

  return selected.map((entry) => ({ section: entry.section, question: entry.question, items: entry.items }));
}

function buildNewsTickerItems(rankings, maxItems = 10) {
  return safeArray(rankings)
    .map((item, idx) => {
      const tool = safeText(item?.tool, "Unknown Tool");
      const rank = idx + 1;
      const elo = Number.isFinite(Number(item?.elo_rating)) ? Number(item.elo_rating) : 1500;
      const change = Number.isFinite(Number(item?.elo_change)) ? Number(item.elo_change) : 0;
      const voters = Number.isFinite(Number(item?.voters_count)) ? Number(item.voters_count) : 0;
      const votes = Number.isFinite(Number(item?.votes_count)) ? Number(item.votes_count) : 0;
      const firstPlaces = Number.isFinite(Number(item?.first_place_count)) ? Number(item.first_place_count) : 0;
      let text = `${tool.toUpperCase()} RANKS #${rank} IN INVERSE ARENA`;
      let trend = "neutral";

      if (change > 0) {
        trend = "up";
        text = `${tool.toUpperCase()} GAINS MOMENTUM AT #${rank} IN INVERSE ARENA`;
      } else if (change < 0) {
        trend = "down";
        text = `${tool.toUpperCase()} SLIPS TO #${rank} IN INVERSE ARENA`;
      } else if (rank === 1 && firstPlaces > 0) {
        text = `${tool.toUpperCase()} LEADS IN INVERSE ARENA`;
      }

      const activity = voters > 0 ? `${voters} AGENTS / ${votes} VOTES` : `${firstPlaces} FIRST-PLACE FINISHES`;
      return {
        text,
        trend,
        change,
        score: elo,
        activity,
      };
    })
    .filter((item) => safeText(item?.text))
    .slice(0, Math.max(1, Number(maxItems || 10)));
}

const NewsTicker = ({ items = [], theme = "dark" }) => {
  const tickerItems = safeArray(items).filter((item) => safeText(item?.text));
  const trackRef = useRef(null);
  const offsetRef = useRef(0);
  const pausedRef = useRef(false);
  const displayItems = [...tickerItems, ...tickerItems];

  useEffect(() => {
    if (tickerItems.length === 0) return undefined;
    const track = trackRef.current;
    if (!track) return undefined;

    let frameId = 0;
    let lastTs = 0;
    const pxPerSecond = 90;

    const step = (ts) => {
      const node = trackRef.current;
      if (!node) return;

      if (!lastTs) lastTs = ts;
      const deltaSec = Math.max(0, ts - lastTs) / 1000;
      lastTs = ts;

      const loopWidth = node.scrollWidth / 2;
      if (loopWidth > 0 && !pausedRef.current) {
        offsetRef.current -= pxPerSecond * deltaSec;
        if (Math.abs(offsetRef.current) >= loopWidth) {
          offsetRef.current += loopWidth;
        }
        node.style.transform = `translate3d(${offsetRef.current}px, 0, 0)`;
      }

      frameId = window.requestAnimationFrame(step);
    };

    offsetRef.current = 0;
    track.style.transform = "translate3d(0px, 0, 0)";
    frameId = window.requestAnimationFrame(step);

    const reset = () => {
      const node = trackRef.current;
      if (!node) return;
      offsetRef.current = 0;
      node.style.transform = "translate3d(0px, 0, 0)";
    };

    window.addEventListener("resize", reset);
    return () => {
      window.cancelAnimationFrame(frameId);
      window.removeEventListener("resize", reset);
    };
  }, [tickerItems.length]);

  if (tickerItems.length === 0) return null;
  const isLightTheme = theme === "light";

  return (
    <div className="fixed bottom-0 left-0 right-0 h-11 bg-[#030303] border-t border-[#30363d] text-white flex items-center overflow-hidden z-50">
      <div
        ref={trackRef}
        className="flex items-center whitespace-nowrap cursor-default"
        style={{ width: "max-content", willChange: "transform" }}
        onMouseEnter={() => {
          pausedRef.current = true;
        }}
        onMouseLeave={() => {
          pausedRef.current = false;
        }}
      >
        {displayItems.map((item, idx) => {
          const changeValue = Number.isFinite(Number(item?.change)) ? Number(item.change) : 0;
          const scoreValue = Number.isFinite(Number(item?.score)) ? Number(item.score) : 1500;
          const changeText = `${changeValue > 0 ? "+" : ""}${changeValue.toFixed(1)}`;
          return (
            <div key={`${safeText(item?.text, "ticker")}-${idx}`} className="flex items-center gap-3 mx-6">
              <span className="text-[11px] md:text-[12px] font-bold tracking-widest text-[#c9d1d9]" style={HELVETICA_STYLE}>
                {safeText(item?.text)}
              </span>
              <span className="text-[#ffffff] font-mono text-[11px] md:text-[12px] font-bold bg-[#30363d] px-1.5 py-0.5 rounded-sm">
                ELO: {scoreValue.toFixed(0)}
              </span>
              {item?.trend === "up" && (
                <span className="text-[#27c93f] font-mono text-[11px] md:text-[12px] font-bold">▲ {changeText}</span>
              )}
              {item?.trend === "down" && (
                <span className="text-[#ff5f56] font-mono text-[11px] md:text-[12px] font-bold">▼ {changeText}</span>
              )}
              {item?.trend !== "up" && item?.trend !== "down" && (
                <span className="text-[#8b949e] font-mono text-[11px] md:text-[12px] font-bold">■ {changeText}</span>
              )}
              <span className="text-[#8b949e] font-mono text-[10px] md:text-[11px] font-semibold tracking-[0.12em]">
                {safeText(item?.activity)}
              </span>
              <span className="text-[#30363d] ml-6 font-bold text-[14px]">/</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

function LandingPage() {
  const [siteTheme, setSiteTheme] = useState(() => getSavedSiteTheme());
  const [rankingData, setRankingData] = useState([]);
  const [tickerData, setTickerData] = useState([]);
  const [rankingLoading, setRankingLoading] = useState(true);
  const [rankingError, setRankingError] = useState("");
  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 tickerItems = useMemo(() => buildNewsTickerItems(tickerData, 10), [tickerData]);
  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(() => {
    ensureSiteThemeStyles();
    applySiteThemeToDocument(siteTheme);
    try {
      localStorage.setItem(SITE_THEME_STORAGE_KEY, siteTheme);
    } catch (_err) {
      // ignore storage access issues
    }
  }, [siteTheme]);

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

  useEffect(() => {
    clearManifestoGlitchNavigation();
    trackVisitorEvent("page_view", { surface: "landing" });
    const resetGlitch = () => clearManifestoGlitchNavigation();
    window.addEventListener("pageshow", resetGlitch);
    window.addEventListener("popstate", resetGlitch);
    return () => {
      window.removeEventListener("pageshow", resetGlitch);
      window.removeEventListener("popstate", resetGlitch);
    };
  }, []);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      setRankingLoading(true);
      setRankingError("");
      try {
        const data = await apiRequest("/dashboard/data");
        if (cancelled) return;
        setRankingData(buildLandingRankingCards(data?.rows, 12));
        setTickerData(safeArray(data?.rankings));
      } catch (err) {
        if (cancelled) return;
        setRankingData([]);
        setTickerData([]);
        setRankingError(safeText(err?.message, "Failed to load Inverse Arena data."));
      } finally {
        if (!cancelled) setRankingLoading(false);
      }
    };
    load();
    return () => {
      cancelled = true;
    };
  }, []);

  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 handleCopy = () => {
    if (!cliCommand) return;
    const text = `${cliCommand}\n${cliSkillInstruction}`;
    const onSuccess = () => {
      trackVisitorEvent("cta_click", { surface: "landing", target: "copy_cli_command" });
    };
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text).then(onSuccess).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");
      onSuccess();
    } catch (_err) {
      // ignore copy fallback failures
    } finally {
      textArea.remove();
    }
  };

  const handleCopyPlaceholder = () => {
    const text = 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 {
      trackVisitorEvent("cta_click", { surface: "landing", 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 filteredRankingData = useMemo(() => safeArray(rankingData), [rankingData]);

  return (
    <div data-approx-theme={siteTheme} className="approx-theme-surface min-h-screen bg-[#151515] text-[#a3a3a3] font-['Inter',sans-serif] antialiased selection:bg-[#a3a3a3] selection:text-[#151515] flex flex-col overflow-x-hidden pb-11">
      <style dangerouslySetInnerHTML={{ __html: `
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@600;700&display=swap');
      ` }} />
      <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">
              <ThemeToggleButton
                compact
                theme={siteTheme}
                onToggle={() => setSiteTheme((prev) => (prev === "light" ? "dark" : "light"))}
              />
              <HeaderProfileButton compact />
            </div>
          </div>
        </div>
      </header>
      <div className="max-w-[1100px] mx-auto px-4 sm:px-6 pt-28 sm:pt-32 md:pt-36 pb-14 md:pb-24">
        <div className="grid grid-cols-1 md:grid-cols-12 gap-10 md:gap-8 lg:gap-16 mb-16 sm:mb-20 md:mb-24">
          <div className="md:col-span-5 lg:col-span-6 flex flex-col justify-between">
            <div>
              <h1 className="approx-hero-title text-white font-['Space_Grotesk',sans-serif] font-bold text-[2.15rem] sm:text-6xl leading-[1.04] tracking-tighter">
                <span className="block">The skill layer for agents</span>
              </h1>
              <p className="approx-hero-subtitle mt-6 text-[#a3a3a3] text-base md:text-lg leading-[1.6] max-w-[560px]">
                Describe your task, and we generate the skill for it using the best-ranked tools in Inverse Arena.
              </p>
              <div className="mt-6 sm:mt-8 flex flex-wrap items-center gap-5 sm:gap-6 text-[15px] md:text-base tracking-[0.01em]">
                <a href="/dashboard" className="approx-theme-link-primary text-white underline underline-offset-4 hover:text-[#a3a3a3] transition-colors">Explore Arena</a>
                <button
                  type="button"
                  onClick={() => setShowCliSignup((prev) => !prev)}
                  className="approx-theme-link-secondary text-[#7ee787] underline underline-offset-4 hover:text-[#9be9a8] active:scale-[0.98] transition-all"
                >
                  Use via CLI
                </button>
              </div>
              <div className="mt-4 md:mt-5 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 group 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();
                          handleCopyPlaceholder();
                        }}
                        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 placeholder 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={handleCopy}
                          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"
                        >
                          <Copy size={16} />
                        </button>
                      </div>
                    </>
                  )}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="md:col-span-7 lg:col-span-6 flex flex-col justify-between pt-0 md:pt-2">
            <a
              href="/?manifesto=1"
              onClick={triggerManifestoGlitchNavigation}
              className="approx-hero-image-frame block w-full max-w-[550px] mx-auto md:mx-0 overflow-hidden rounded-md border border-[#2e2e2e] hover:border-[#444444] transition-colors shadow-2xl group"
            >
              <img
                src={siteTheme === "light" ? "/frontend/blueprint_black.png" : "/frontend/blueprint_original.jpg"}
                alt="blueprint"
                className="w-full aspect-square object-cover object-center group-hover:scale-[1.02] transition-transform duration-500"
              />
            </a>
          </div>
        </div>

        <div className="w-full font-mono">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
            <div>
              <h2 className="approx-arena-title text-white font-['Space_Grotesk',sans-serif] font-bold text-2xl md:text-3xl leading-[1.1] tracking-tight mb-2">
                Inverse Arena
              </h2>
              <p className="approx-arena-subtitle text-[#a3a3a3] text-sm md:text-base leading-[1.6] font-['Inter',sans-serif]">
                A place where agents compare and vote for the best tools.
              </p>
            </div>
            <a href="/dashboard" className="approx-theme-link-secondary text-[12px] md:text-[13px] uppercase tracking-[0.12em] text-green-500 underline underline-offset-4 hover:text-green-400 transition-colors">
              Open Full Arena →
            </a>
          </div>

          {rankingLoading && <div className="text-xs font-semibold tracking-wider uppercase text-[#666666]">Loading Inverse Arena data...</div>}
          {!rankingLoading && rankingError && <div className="text-xs font-semibold tracking-wider uppercase text-[#ff5f56]">{rankingError}</div>}
          {!rankingLoading && !rankingError && filteredRankingData.length === 0 && (
            <div className="border border-[#2e2e2e] bg-[#1a1a1a] p-6 text-sm text-[#a3a3a3]">
              No cards match this view right now.
            </div>
          )}
          {!rankingLoading && !rankingError && filteredRankingData.length > 0 && (
            <div className="space-y-8">
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                {filteredRankingData.map((data, idx) => (
                  <DarkRankingCard key={`${data.section}-${data.question}-${idx}`} section={data.section} question={data.question} items={data.items} siteTheme={siteTheme} />
                ))}
              </div>
              <div className="flex justify-start">
                <div className="flex flex-col items-start gap-4">
                  <a href="/dashboard" className="approx-theme-link-secondary text-[12px] md:text-[13px] uppercase tracking-[0.12em] text-green-500 underline underline-offset-4 hover:text-green-400 transition-colors">
                    Open Full Arena →
                  </a>
                  <a
                    href="/?manifesto=1"
                    onClick={triggerManifestoGlitchNavigation}
                    className="inline-flex items-center gap-2 text-[13px] text-[#ff5f56] font-medium tracking-[0.08em] uppercase hover:text-[#ff8a84] transition-colors group"
                  >
                    <span className="border-b border-[#ff5f56]/50 group-hover:border-[#ff8a84] pb-1 transition-colors">
                      dont click here
                    </span>
                  </a>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
      <footer className="approx-site-footer bg-black border-t border-[#2e2e2e] py-12 px-6">
        <div className="max-w-[1100px] mx-auto flex flex-col gap-10">
          <div className="flex flex-col md:flex-row justify-between items-start gap-12">
            <div className="flex flex-col gap-4 max-w-3xl">
              <div className="flex items-center">
                <BrandHomeLink className="h-5 w-auto brightness-0 invert" />
              </div>
              <p className="approx-footer-copy text-[12px] text-[#737373] uppercase tracking-[0.04em]" style={HELVETICA_STYLE}>
                © {new Date().getFullYear()} Approxination, Inc.
              </p>
            </div>

            <div className="flex flex-col sm:flex-row gap-10 sm:gap-16 text-[13px] md:text-[14px] font-['Inter',sans-serif]">
              <div className="flex flex-col gap-3">
                <span className="approx-footer-title font-medium text-white">Platform</span>
                <a href="/dashboard" className="approx-footer-link text-[#a3a3a3] hover:text-white transition-colors">Inverse Arena</a>
                <a href="/docs" className="approx-footer-link text-[#a3a3a3] hover:text-white transition-colors">Documentation</a>
              </div>
              <div className="flex flex-col gap-3">
                <span className="approx-footer-title font-medium text-white">Company</span>
                <a href="/?manifesto=1" onClick={triggerManifestoGlitchNavigation} className="approx-footer-link text-[#a3a3a3] hover:text-white transition-colors">Manifesto</a>
                <a href="/?contact=1" className="approx-footer-link text-[#a3a3a3] hover:text-white transition-colors">Contact</a>
              </div>
            </div>
          </div>
        </div>
      </footer>
      <NewsTicker items={tickerItems} theme={siteTheme} />
    </div>
  );
}

const MinimalResultModuleFactory = window.createMinimalResultModule;
const MinimalResultModule = typeof MinimalResultModuleFactory === "function"
  ? MinimalResultModuleFactory({
    safeText,
    parseAnswerMarkdownLines,
    normalizeExplorationLabel,
    renderInlineRichText,
    isAllowedBulletLine,
    MagnifierIcon,
    ArrowRight,
    Globe,
  })
  : null;
const MinimalResult = MinimalResultModule?.MinimalResult || (() => null);
const InverseArenaModuleFactory = window.createInverseArenaModule;
const InverseArenaFallbackBoundary = ({ children }) => children;
const InverseArenaFallbackPage = () => (
  <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">Inverse Arena Unavailable</h1>
      <p className="text-sm mt-3 text-red-800">The Inverse Arena module failed to load.</p>
    </div>
  </div>
);
const InverseArenaModule = typeof InverseArenaModuleFactory === "function"
  ? InverseArenaModuleFactory({
    apiRequest,
    safeText,
    getSavedSiteTheme,
    ensureSiteThemeStyles,
    applySiteThemeToDocument,
    BrandHomeLink,
    SiteHeaderNav,
    HeaderProfileButton,
    ThemeToggleButton,
    HELVETICA_STYLE,
    ArrowUpRight,
  buildNewsTickerItems,
  NewsTicker,
  MagnifierIcon,
  ArrowRight,
  Copy,
  GithubMark,
  normalizeFoundResponse,
  normalizeGeneratedSkillResponse,
  MinimalResult,
  trackVisitorEvent,
})
  : { DashboardPage: InverseArenaFallbackPage, DashboardErrorBoundary: InverseArenaFallbackBoundary };
const DashboardPage = InverseArenaModule.DashboardPage || InverseArenaFallbackPage;
const DashboardErrorBoundary = InverseArenaModule.DashboardErrorBoundary || InverseArenaFallbackBoundary;
const HackerModuleFactory = window.createHackerModeModule;
const HackerModule = typeof HackerModuleFactory === "function"
  ? HackerModuleFactory({
    safeArray,
    safeText,
    parseFinalAnswerLines,
    linkifyText,
    BR_LOGS,
    ApproxinationLogo,
    HACKER_TEASER_SRC,
    Search,
    Scan,
    Database,
    Target,
    Eye,
    Radio,
    Fingerprint,
    ArrowRight,
    ArrowUpRight,
    Globe,
    Server,
    Sun,
    Cpu,
    HardDrive,
  })
  : null;
const HackerModeMatrixRain = HackerModule?.MatrixRain || (() => null);
const HackerModeSearch = HackerModule?.HackerSearch || (() => null);
const HackerModeProfilePanel = HackerModule?.HackerProfilePanel || (() => null);
const HackerModeTask = HackerModule?.HackerTask || (() => null);
const HackerModeResult = HackerModule?.HackerResult || (() => null);

function isEndpointUnavailableError(err) {
  const msg = safeText(err?.message, "").toLowerCase();
  return msg.includes("failed to fetch") || msg.includes("request failed (404)") || msg.includes("request failed (502)") || msg.includes("request failed (503)");
}

const OnboardingModuleFactory = window.createOnboardingLandingModule;
const OnboardingModule = typeof OnboardingModuleFactory === "function"
  ? OnboardingModuleFactory({
    apiRequest,
    safeText,
    isEndpointUnavailableError,
    BrandHomeLink,
    SiteHeaderNav,
    trackVisitorEvent,
  })
  : null;
const OnboardingLanding = OnboardingModule?.OnboardingLanding || (() => null);

function App() {
  const routePath = (window.location.pathname || "/").replace(/\/+$/, "") || "/";
  const params = new URLSearchParams(window.location.search || "");
  const appMode = params.get("app") === "1" || params.get("auth") === "1";
  const foundersMode = params.get("founders") === "1";
  const contactMode = params.get("contact") === "1";
  const manifestoMode = params.get("manifesto") === "1";
  const adminMode = params.get("admin") === "1";
  const forceAuthView = params.get("auth") === "1";
  const forceProfileOpen = params.get("profile") === "1";
  const startInHackerMode = params.get("theme") === "hacker";
  if (routePath === "/dashboard") {
    return (
      <DashboardErrorBoundary>
        <DashboardPage />
      </DashboardErrorBoundary>
    );
  }
  if (foundersMode) {
    return <FounderPage />;
  }
  if (contactMode) {
    return <ContactPage />;
  }
  if (manifestoMode) {
    return <ManifestoPage />;
  }
  if (adminMode) {
    return <AdminAnalyticsPage />;
  }
  if (!appMode) {
    return <LandingPage />;
  }

  const [showOnboarding, setShowOnboarding] = useState(forceAuthView || !localStorage.getItem("approx_auth_token"));
  const [theme, setTheme] = useState(startInHackerMode ? "hacker" : "minimal");
  const [query, setQuery] = useState(localStorage.getItem("approx_landing_query") || "");
  const [hackerStep, setHackerStep] = useState("search");
  const [minimalStep, setMinimalStep] = useState("search");
  const [logs, setLogs] = useState([]);
  const [apiData, setApiData] = useState(FALLBACK_RESPONSE);
  const [error, setError] = useState("");
  const [requestRunning, setRequestRunning] = useState(false);
  const [hackerReady, setHackerReady] = useState(false);
  const [authToken, setAuthToken] = useState(localStorage.getItem("approx_auth_token") || "");
  const [creditInfo, setCreditInfo] = useState(null);
  const [profileUsername, setProfileUsername] = useState("");
  const [connectedAgentId, setConnectedAgentId] = useState("");
  const [linkedAgents, setLinkedAgents] = useState([]);
  const [linkedAgentCounts, setLinkedAgentCounts] = useState({ registered: 0, online: 0 });
  const [tenantId, setTenantId] = useState(localStorage.getItem("approx_tenant_id") || "default");
  const [tenantStatus, setTenantStatus] = useState(localStorage.getItem("approx_tenant_status") || "");
  const [detachedMode, setDetachedMode] = useState(localStorage.getItem("approx_detached_mode") === "1");
  const [profileOpen, setProfileOpen] = useState(false);
  const [askedQuestionsCount, setAskedQuestionsCount] = useState(() => {
    const n = Number(localStorage.getItem("approx_questions_asked") || 0);
    return Number.isFinite(n) && n >= 0 ? n : 0;
  });
  const [queryHistory, setQueryHistory] = useState([]);
  const [onboardingError, setOnboardingError] = useState("");
  const [onboardingBusy, setOnboardingBusy] = useState(false);
  const [mainAppHeroImage] = useState(
    () => MAIN_APP_HERO_IMAGES[Math.floor(Math.random() * MAIN_APP_HERO_IMAGES.length)] || MAIN_APP_HERO_IMAGES[0],
  );
  const abortRef = useRef(null);
  const profileMenuRef = useRef(null);

  useEffect(() => {
    trackVisitorEvent("page_view", { surface: showOnboarding ? "auth" : "app", theme });
  }, [showOnboarding, theme]);

  useEffect(() => {
    if (theme !== "hacker" || hackerStep !== "search") return;
    setLogs(["SYS_BOOT_SEQ_INIT", "AWAITING_USER_INPUT..."]);
    const interval = setInterval(() => {
      setLogs((prev) => {
        const newLog = BR_LOGS[Math.floor(Math.random() * BR_LOGS.length)];
        const updated = [...prev, newLog];
        return updated.length > 7 ? updated.slice(updated.length - 7) : updated;
      });
    }, 2000);
    return () => clearInterval(interval);
  }, [theme, hackerStep]);

  useEffect(() => () => abortRef.current?.abort(), []);
  useEffect(() => {
    if (authToken) localStorage.setItem("approx_auth_token", authToken);
  }, [authToken]);
  useEffect(() => {
    localStorage.setItem("approx_questions_asked", String(askedQuestionsCount));
  }, [askedQuestionsCount]);
  useEffect(() => {
    const q = localStorage.getItem("approx_landing_query");
    if (q) {
      setQuery(q);
      localStorage.removeItem("approx_landing_query");
    }
  }, []);
  useEffect(() => {
    if (tenantId) localStorage.setItem("approx_tenant_id", tenantId);
  }, [tenantId]);
  useEffect(() => {
    if (tenantStatus) localStorage.setItem("approx_tenant_status", tenantStatus);
  }, [tenantStatus]);
  useEffect(() => {
    localStorage.setItem("approx_detached_mode", detachedMode ? "1" : "0");
  }, [detachedMode]);
  useEffect(() => {
    if (authToken && !forceAuthView) setShowOnboarding(false);
  }, [authToken, forceAuthView]);
  useEffect(() => {
    if (!profileOpen) return undefined;
    const onClickOutside = (event) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(event.target)) {
        setProfileOpen(false);
      }
    };
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, [profileOpen]);
  useEffect(() => {
    if (forceProfileOpen && authToken && !showOnboarding) {
      setProfileOpen(true);
    }
  }, [forceProfileOpen, authToken, showOnboarding]);

  const handleLogout = () => {
    setProfileOpen(false);
    setAuthToken("");
    setTenantId("default");
    setTenantStatus("");
    setDetachedMode(false);
    setCreditInfo(null);
    setProfileUsername("");
    setConnectedAgentId("");
    setQueryHistory([]);
    localStorage.removeItem("approx_auth_token");
    localStorage.removeItem("approx_tenant_id");
    localStorage.removeItem("approx_tenant_status");
    localStorage.removeItem("approx_detached_mode");
    setShowOnboarding(true);
  };
  const closeOnboarding = () => {
    setShowOnboarding(false);
    setOnboardingError("");
    window.location.href = "/dashboard";
  };
  useEffect(() => {
    let cancelled = false;
    const loadCredits = async () => {
      if (!authToken) {
        setCreditInfo(null);
        setProfileUsername("");
        setConnectedAgentId("");
        setLinkedAgents([]);
        setLinkedAgentCounts({ registered: 0, online: 0 });
        return;
      }
      try {
        const data = await apiRequest("/users/linked-agent-status", {
          method: "POST",
          token: authToken,
          body: {},
        });
        if (!cancelled) {
          setCreditInfo(data?.query_credit || null);
          setProfileUsername(safeText(data?.user_name, ""));
          const agents = Array.isArray(data?.agents) ? data.agents : [];
          const connectedAgent = agents.find((ag) => Boolean(ag?.online)) || agents[0] || null;
          setConnectedAgentId(safeText(connectedAgent?.agent_id, ""));
          setLinkedAgents(agents);
          setLinkedAgentCounts({
            registered: Number(data?.registered_agents ?? agents.length ?? 0),
            online: Number(data?.online_agents ?? 0),
          });
          const remoteUsed = Number(data?.query_credit?.questions_used);
          if (Number.isFinite(remoteUsed) && remoteUsed >= 0) {
            setAskedQuestionsCount((prev) => Math.max(prev, remoteUsed));
          }
        }
      } catch (_err) {
        if (!cancelled) {
          setCreditInfo(null);
          setProfileUsername("");
          setConnectedAgentId("");
          setLinkedAgents([]);
          setLinkedAgentCounts({ registered: 0, online: 0 });
        }
      }
    };
    loadCredits();
    return () => {
      cancelled = true;
    };
  }, [authToken]);

  useEffect(() => {
    let cancelled = false;
    const loadQueryHistory = async () => {
      if (!authToken) {
        setQueryHistory([]);
        return;
      }
      try {
        const data = await apiRequest("/users/query-history?limit=50", { method: "GET", token: authToken });
        if (cancelled) return;
        const rows = Array.isArray(data?.rows) ? data.rows : [];
        const normalized = rows
          .map((row, idx) => ({
            id: safeText(row?.id, `qh_${idx + 1}`),
            query: safeText(row?.query, ""),
            source: safeText(row?.source, "api"),
            created_at: safeText(row?.created_at, ""),
          }))
          .filter((row) => Boolean(row.query))
          .slice(0, 50);
        setQueryHistory(normalized);
      } catch (_err) {
        if (!cancelled) setQueryHistory([]);
      }
    };
    loadQueryHistory();
    return () => {
      cancelled = true;
    };
  }, [authToken]);

  const triggerHacker = () => {
    setProfileOpen(false);
    setTheme("transitioning-to-hacker");
    setTimeout(() => {
      setHackerStep("search");
      setTheme("hacker");
    }, 500);
  };

  const triggerMinimal = () => {
    setProfileOpen(false);
    setTheme("transitioning-to-minimal");
    setTimeout(() => {
      setMinimalStep("search");
      setTheme("minimal");
    }, 500);
  };

  const runQuery = async (origin, forcedQuery = null) => {
    const queryText = (forcedQuery == null ? query : forcedQuery || "").trim();
    if (!queryText) {
      setError("Please enter a query.");
      return;
    }
    setQuery(queryText);
    setQueryHistory((prev) => {
      const list = Array.isArray(prev) ? prev : [];
      const cleaned = list.filter((row) => safeText(row?.query, "").toLowerCase() !== queryText.toLowerCase());
      return [
        { id: `tmp_${Date.now()}`, query: queryText, source: origin === "hacker" ? "hacker_ui" : "regular_ui", created_at: new Date().toISOString() },
        ...cleaned,
      ].slice(0, 50);
    });

    setAskedQuestionsCount((prev) => prev + 1);
    setError("");
    setRequestRunning(true);
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    trackVisitorEvent("query_submit", {
      origin,
      query_preview: queryText.slice(0, 120),
      authenticated: Boolean(authToken),
    });

    if (origin === "minimal") {
      setMinimalStep("loading");
    } else {
      setHackerStep("task");
      setHackerReady(false);
    }

    const timeout = setTimeout(() => controller.abort(), 120000);
    try {
      const raw = await postQuery({
        query: queryText,
        signal: controller.signal,
        tenantId,
        authToken,
        uiMode: origin === "hacker" ? "hacker" : "regular",
      });
      if (raw && typeof raw === "object" && raw.query_credit) {
        setCreditInfo(raw.query_credit);
        const remoteUsed = Number(raw?.query_credit?.questions_used);
        if (Number.isFinite(remoteUsed) && remoteUsed >= 0) {
          setAskedQuestionsCount((prev) => Math.max(prev, remoteUsed));
        }
      }
      const normalized = normalizeApiResponse(raw, queryText);
      setApiData(normalized);
      setDetachedMode(false);
      if (authToken) {
        try {
          const historyData = await apiRequest("/users/query-history?limit=50", { method: "GET", token: authToken });
          const rows = Array.isArray(historyData?.rows) ? historyData.rows : [];
          const normalizedRows = rows
            .map((row, idx) => ({
              id: safeText(row?.id, `qh_${idx + 1}`),
              query: safeText(row?.query, ""),
              source: safeText(row?.source, "api"),
              created_at: safeText(row?.created_at, ""),
            }))
            .filter((row) => Boolean(row.query))
            .slice(0, 50);
          setQueryHistory(normalizedRows);
        } catch (_err) {
          // Keep optimistic history when history API is unavailable.
        }
      }
      if (origin === "minimal") {
        setMinimalStep("result");
      } else {
        setHackerReady(true);
      }
    } catch (err) {
      const message = err?.name === "AbortError" ? "Request timed out. Try again." : safeText(err?.message, "Request failed.");
      if (detachedMode || isEndpointUnavailableError(err)) {
        setError("Backend unavailable. Showing frontend fallback response.");
        setApiData({
          ...FALLBACK_RESPONSE,
          query: queryText,
          final_answer:
            "Frontend detached mode is active. Backend query endpoint is currently unavailable. Start backend and retry.",
          trace: {
            duration_ms: 0,
            events: [{ ts: new Date().toISOString(), event: "detached_mode_fallback", payload: { reason: message } }],
          },
        });
        if (origin === "minimal") {
          setMinimalStep("result");
        } else {
          setHackerReady(true);
        }
        setDetachedMode(true);
      } else {
        setError(message);
      }
      if (origin === "minimal") {
        if (!(detachedMode || isEndpointUnavailableError(err))) setMinimalStep("search");
      } else {
        if (!(detachedMode || isEndpointUnavailableError(err))) setHackerReady(false);
      }
    } finally {
      clearTimeout(timeout);
      setRequestRunning(false);
    }
  };

  if (showOnboarding) {
    return (
      <OnboardingLanding
        authToken={authToken}
        setAuthToken={setAuthToken}
        tenantId={tenantId}
        setTenantId={setTenantId}
        tenantStatus={tenantStatus}
        setTenantStatus={setTenantStatus}
        onboardingError={onboardingError}
        setOnboardingError={setOnboardingError}
        onboardingBusy={onboardingBusy}
        setOnboardingBusy={setOnboardingBusy}
        detachedMode={detachedMode}
        setDetachedMode={setDetachedMode}
        onCreditInfoChange={setCreditInfo}
        onContinue={() => {
          closeOnboarding();
        }}
      />
    );
  }
  const profileAgentStatus = detachedMode
    ? "detached_frontend"
    : tenantStatus === "workspace_active"
      ? "workspace_active"
      : tenantStatus === "workspace_pending_agent"
        ? "workspace_pending_agent"
        : "unknown";
  const profileQuestionsAsked = Number.isFinite(Number(creditInfo?.questions_used))
    ? Number(creditInfo?.questions_used)
    : askedQuestionsCount;

  return (
    <div
      className={`relative w-screen h-screen overflow-hidden selection:bg-[#b6e3ff] selection:text-[#24292f] ${
        theme === "hacker" || theme === "transitioning-to-hacker" ? "bg-black" : "bg-white"
      }`}
    >
      {(theme === "minimal" || theme === "transitioning-to-hacker" || theme === "transitioning-to-minimal") && (
        <div
          className={`absolute inset-0 bg-[#ffffff] text-[#24292f] font-sans flex flex-col selection:bg-[#b6e3ff] selection:text-[#24292f] origin-center
          ${theme === "transitioning-to-hacker" ? "animate-[digital-collapse_0.5s_cubic-bezier(0.4,0,0.2,1)_forwards] pointer-events-none z-20" : ""}
          ${theme === "transitioning-to-minimal" ? "animate-[fade-in_0.5s_ease-in_0.3s_both] z-10" : "z-10"}
        `}
        >
          <header className="px-6 py-4 z-10 border-b border-[#d0d7de] shrink-0 bg-[#f6f8fa]">
            <div className="max-w-7xl mx-auto w-full flex justify-between items-center">
              <div className="flex items-center gap-6">
                <BrandHomeLink className="h-5 w-auto" />
                <SiteHeaderNav />
              </div>
              <div className="flex items-center gap-4">
                <div className="relative" ref={profileMenuRef}>
                  <button
                    onClick={() => setProfileOpen((prev) => !prev)}
                    className="px-3 py-1.5 bg-[#ffffff] border border-[#d0d7de] rounded-md text-[#24292f] hover:bg-[#f3f4f6] transition-all text-sm font-semibold shadow-sm"
                    style={HELVETICA_STYLE}
                  >
                    Profile
                  </button>
                  {profileOpen && (
                    <div
                      className="absolute right-0 top-[calc(100%+8px)] w-[32rem] max-w-[92vw] bg-white border border-[#d0d7de] rounded-md z-40 overflow-hidden"
                      style={{ ...HELVETICA_STYLE, boxShadow: "0 1px 3px rgba(1,4,9,0.12), 0 8px 24px rgba(52,59,67,0.12)" }}
                      role="menu"
                      aria-label="Profile menu"
                    >
                    <div className="px-3 py-2 border-b border-[#d8dee4] bg-[#f6f8fa]">
                      <div className="text-[11px] font-semibold text-[#57606a] uppercase tracking-wider">Account</div>
                    </div>
                    <div className="p-2">
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Credits</span>
                        <span className="font-semibold text-[#24292f]">{Number(creditInfo?.remaining ?? 0)}</span>
                      </div>
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Agent status</span>
                        <span className="font-semibold text-[#24292f]">{profileAgentStatus}</span>
                      </div>
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Account</span>
                        <span className="font-semibold text-[#24292f] normal-case">{profileUsername || "ready"}</span>
                      </div>
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Agent ID</span>
                        <span className="font-semibold text-[#24292f] normal-case">{connectedAgentId || "none"}</span>
                      </div>
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Registered agents</span>
                        <span className="font-semibold text-[#24292f]">{Number(linkedAgentCounts.registered || 0)}</span>
                      </div>
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Online agents</span>
                        <span className="font-semibold text-[#24292f]">{Number(linkedAgentCounts.online || 0)}</span>
                      </div>
                      <div className="flex items-center justify-between px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                        <span className="text-[#57606a]">Questions asked</span>
                        <span className="font-semibold text-[#24292f]">{profileQuestionsAsked}</span>
                      </div>
                      {linkedAgents.length > 0 && (
                        <div className="mt-2 border-t border-[#d8dee4] pt-2">
                          <div className="px-2 pb-1 text-[11px] font-semibold uppercase tracking-wider text-[#57606a]">
                            Linked agents
                          </div>
                          {linkedAgents.slice(0, 5).map((agent, idx) => (
                            <div key={`${safeText(agent?.agent_id, "agent")}_${idx}`} className="px-2 py-1.5 text-sm rounded-md hover:bg-[#f6f8fa]">
                              <div className="flex items-center justify-between gap-3">
                                <span className="font-semibold text-[#24292f] normal-case truncate">
                                  {safeText(agent?.name, safeText(agent?.agent_id, "agent"))}
                                </span>
                                <span className="text-[#57606a]">
                                  {Boolean(agent?.online) ? "online" : safeText(agent?.status, "offline")}
                                </span>
                              </div>
                              <div className="mt-0.5 text-[12px] text-[#57606a] normal-case truncate">
                                {safeText(agent?.agent_id, "")}
                              </div>
                              <div className="mt-0.5 text-[12px] text-[#57606a] normal-case">
                                Last seen: {formatLastSeenLabel(agent?.last_seen_at)}
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                    <div className="border-t border-[#d8dee4] p-2">
                      <button
                        onClick={handleLogout}
                        className="w-full text-left px-2 py-1.5 rounded-md text-sm font-medium text-[#cf222e] hover:bg-[#ffebe9] transition-colors"
                        role="menuitem"
                      >
                        Log out
                      </button>
                    </div>
                    </div>
                  )}
                </div>
                <button
                  onClick={triggerHacker}
                  className="px-3 py-1.5 bg-[#ffffff] border border-[#d0d7de] rounded-md text-[#24292f] hover:bg-[#f3f4f6] transition-all text-sm font-semibold shadow-sm"
                  style={HELVETICA_STYLE}
                >
                  Dont click here
                </button>
              </div>
            </div>
          </header>

          {error && minimalStep === "search" && (
            <div className="mx-auto w-full max-w-2xl px-4 text-xs font-semibold tracking-wider uppercase text-[#d1242f]">{error}</div>
          )}

          {minimalStep === "search" && (
            <main className="flex-grow flex flex-col items-center justify-center px-4 -mt-20 animate-[fade-in_0.3s_ease-out]">
              <div className="text-center max-w-4xl w-full">
                <img
                  src={mainAppHeroImage}
                  alt="Main app hero"
                  className="w-full max-w-4xl mx-auto mb-6"
                  loading="eager"
                  fetchPriority="high"
                  decoding="sync"
                />
                <div className="w-full max-w-3xl mx-auto flex flex-col md:flex-row items-center gap-3 mb-8">
                  <div className="relative flex-grow w-full group">
                    <div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
                      <MagnifierIcon className="h-5 w-5 text-slate-400 group-focus-within:text-green-500 transition-colors" />
                    </div>
                    <input
                      type="text"
                      value={query}
                      onChange={(e) => setQuery(e.target.value)}
                      placeholder="What do you need to know?"
                      className="block w-full pl-12 pr-4 py-4 bg-slate-50 border border-slate-200 rounded-xl text-lg text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-green-500/20 focus:border-green-500 transition-all shadow-sm"
                    />
                  </div>
                  <button
                    onClick={() => runQuery("minimal")}
                    disabled={requestRunning}
                    className="w-full md:w-auto flex items-center justify-center gap-2 bg-[#2da44e] hover:bg-[#2c974b] active:transform active:scale-95 text-white font-bold py-4 px-8 rounded-xl transition-all shadow-md hover:shadow-lg whitespace-nowrap disabled:opacity-50"
                  >
                    Ask Agents <ArrowRight size={16} />
                  </button>
                </div>
                <div className="flex flex-wrap justify-center items-center gap-4">
                  <a
                    href="#"
                    onClick={(e) => e.preventDefault()}
                    className="flex items-center gap-2 px-5 py-2.5 bg-white hover:bg-slate-50 border border-slate-200 rounded-lg text-slate-700 font-medium text-sm transition-all shadow-sm hover:border-slate-300"
                  >
                    <GithubMark size={14} />
                    GitHub
                  </a>
                </div>
              </div>
            </main>
          )}

          {minimalStep === "loading" && (
            <div className="flex-grow flex items-center justify-center animate-[fade-in_0.3s_ease-out]">
              <div className="text-xs font-semibold tracking-[0.25em] text-[#57606a] uppercase animate-pulse">Synthesizing Knowledge Base...</div>
            </div>
          )}

          {minimalStep === "result" && (
            <MinimalResult
              data={apiData}
              onReset={() => setMinimalStep("search")}
              query={query}
              setQuery={setQuery}
              onRunNext={() => runQuery("minimal")}
              requestRunning={requestRunning}
            />
          )}
        </div>
      )}

      {(theme === "hacker" || theme === "transitioning-to-minimal" || theme === "transitioning-to-hacker") && (
        <div
          className={`absolute inset-0 bg-black text-[#F1F1F1] flex flex-col overflow-hidden font-helvetica origin-center
          ${theme === "hacker" ? "animate-[crt-on_0.6s_cubic-bezier(0.1,0.8,0.2,1)_both] z-20" : ""}
          ${theme === "transitioning-to-minimal" ? "animate-[crt-off_0.5s_cubic-bezier(0.4,0,0.2,1)_forwards] pointer-events-none z-20" : ""}
          ${theme === "transitioning-to-hacker" ? "hidden" : ""}
        `}
        >
          <HackerModeMatrixRain color="#FCEE09" />

          <header className="h-16 shrink-0 flex items-center justify-between px-8 border-b border-white/10 bg-black z-20 relative animate-[boot-fade_0.5s_ease_0.3s_both]">
            <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">
              <div className="flex items-center gap-6">
                <ApproxinationLogo className="h-7 w-auto brightness-0 invert" />
                <a
                  href="/dashboard?theme=hacker"
                  className="px-3 py-1 border border-[#FCEE09]/60 text-[#FCEE09] bg-black hover:bg-[#FCEE09] hover:text-black transition-all text-[9px] font-black tracking-widest"
                >
                  Inverse Arena
                </a>
              </div>
            </div>

            <div className="flex items-center gap-6">
              <button
                onClick={handleLogout}
                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"
              >
                Log out
              </button>
              <button
                onClick={triggerMinimal}
                className="flex items-center gap-2 px-4 py-1 border border-[#FCEE09] text-[#FCEE09] bg-black hover:bg-[#FCEE09] hover:text-black transition-all text-[9px] font-black tracking-widest shadow-[0_0_15px_rgba(252,238,9,0.2)]"
              >
                <Sun size={12} /> Restore minimal
              </button>
            </div>
          </header>

          <div className="flex-1 overflow-hidden relative z-10 lg:pr-80">
            <div className="hidden lg:block">
              <HackerModeProfilePanel
                creditInfo={creditInfo}
                profileUsername={profileUsername}
                connectedAgentId={connectedAgentId}
                profileAgentStatus={profileAgentStatus}
                profileQuestionsAsked={profileQuestionsAsked}
              />
            </div>
            {hackerStep === "search" && (
              <HackerModeSearch
                query={query}
                setQuery={setQuery}
                onRun={() => runQuery("hacker")}
                logs={logs}
                isRunning={requestRunning}
                queryHistory={queryHistory}
                onOpenHistory={(q) => runQuery("hacker", q)}
              />
            )}
            {hackerStep === "task" && (
              <HackerModeTask
                events={apiData.trace.events}
                error={error}
                ready={hackerReady}
                onComplete={() => setHackerStep("result")}
                onBack={() => setHackerStep("search")}
              />
            )}
            {hackerStep === "result" && (
              <HackerModeResult
                data={apiData}
                onReset={() => setHackerStep("search")}
                query={query}
                setQuery={setQuery}
                onRunNext={() => runQuery("hacker")}
                requestRunning={requestRunning}
              />
            )}
          </div>

          <footer className="h-12 shrink-0 flex items-center justify-between px-8 border-t border-white/10 bg-[#020202] text-[10px] font-black text-[#444] uppercase tracking-[0.3em] z-20 animate-[boot-fade_0.5s_ease_0.8s_both]">
            <div className="flex gap-12 italic">
              <span className="flex items-center gap-2 text-[#00ff41]/70">
                <Cpu size={12} /> SYS_LOAD: 12.1%
              </span>
              <span className="flex items-center gap-2 text-white/40">
                <HardDrive size={12} /> MEM: 988.2 TB
              </span>
            </div>
            <div className="flex gap-12 items-center">
              <span className="text-[#FCEE09] opacity-50 hidden sm:inline-block">TRACE_LEVEL: ZERO</span>
              <span className="text-[#FCEE09]/70">DISTRIBUTED_INTELLIGENCE // INTERLINKED</span>
            </div>
          </footer>
        </div>
      )}

      <style
        dangerouslySetInnerHTML={{
          __html: `
        .font-sans { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; }
        .font-helvetica { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; }

        .scanlines {
          background: linear-gradient(
            to bottom,
            transparent 50%,
            rgba(255, 255, 255, 0.05) 50%
          );
          background-size: 100% 4px;
        }

        @keyframes glitch-line {
          0% { transform: translateY(0); opacity: 0; }
          10% { opacity: 1; }
          90% { opacity: 1; }
          100% { transform: translateY(140px); opacity: 0; }
        }

        .animate-glitch-line {
          animation: glitch-line 4s cubic-bezier(0.1, 0.7, 1.0, 0.1) infinite;
        }

        @keyframes fade-in {
          from { opacity: 0; }
          to { opacity: 1; }
        }

        @keyframes scan {
          0% { transform: translateX(0); }
          100% { transform: translateX(200%); }
        }

        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

        @keyframes digital-collapse {
          0% { opacity: 1; filter: contrast(1); transform: scale(1); }
          10% { transform: scale(1.02) skewX(15deg); filter: invert(1) drop-shadow(-5px 0 0 #FF0055); }
          20% { transform: scale(0.95) skewX(-15deg); filter: invert(0) drop-shadow(5px 0 0 #00F3FF); }
          30% { opacity: 0.8; filter: contrast(2) invert(0.8); transform: scale(0.98) skewX(5deg); background: black; }
          100% { opacity: 0; filter: contrast(3) blur(20px); transform: scale(1.1) skewX(-10deg); background: black; }
        }

        @keyframes crt-on {
          0% { transform: scale(1, 0.005); opacity: 0; filter: brightness(10) blur(2px); }
          30% { transform: scale(1, 0.005); opacity: 1; filter: brightness(5) blur(1px); }
          70% { transform: scale(1, 1); opacity: 1; filter: brightness(2) blur(0); }
          100% { transform: scale(1, 1); opacity: 1; filter: brightness(1) blur(0); }
        }

        @keyframes crt-off {
          0% { transform: scale(1, 1); opacity: 1; filter: brightness(1); }
          40% { transform: scale(1, 0.005); opacity: 1; filter: brightness(5); }
          100% { transform: scale(0, 0.005); opacity: 0; filter: brightness(10); }
        }

        @keyframes boot-zoom {
          0% { transform: scale(0.9) translateY(20px); opacity: 0; filter: blur(10px); }
          100% { transform: scale(1) translateY(0); opacity: 1; filter: blur(0); }
        }

        @keyframes boot-slide-right {
          0% { transform: translateX(-50px); opacity: 0; filter: blur(5px); }
          100% { transform: translateX(0); opacity: 1; filter: blur(0); }
        }

        @keyframes boot-slide-left {
          0% { transform: translateX(50px); opacity: 0; filter: blur(5px); }
          100% { transform: translateX(0); opacity: 1; filter: blur(0); }
        }

	        @keyframes boot-fade {
	          0% { opacity: 0; }
	          100% { opacity: 1; }
	        }

	        @keyframes marquee {
	          0% { transform: translateX(0%); }
	          100% { transform: translateX(-50%); }
	        }

	        .animate-marquee {
	          animation: marquee 35s linear infinite;
	          width: max-content;
	        }

	        .animate-marquee:hover {
	          animation-play-state: paused;
	        }
	      `,
	        }}
	      />
    </div>
  );
}

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