window.renderTerminalVariation = function (mount) {
  const { useEffect, useState } = React;
  const { ApplyModal, FAQ } = window.ApexUI;
  const { HumansVsMachinesHero } = window.ApexHeroMachines;
  const D = window.ApexData;

  function useResponsive() {
    const [w, setW] = useState(typeof window !== "undefined" ? window.innerWidth : 1280);
    useEffect(() => {
      const onResize = () => setW(window.innerWidth);
      window.addEventListener("resize", onResize);
      return () => window.removeEventListener("resize", onResize);
    }, []);
    return { w, isMobile: w < 768, isTablet: w >= 768 && w < 1024 };
  }

  const theme = {
    bg: "#0A0B0D",
    surface: "#0F1114",
    surfaceAlt: "#12151A",
    border: "rgba(255,255,255,0.07)",
    borderStrong: "rgba(255,255,255,0.14)",
    fg: "#E7E9EC",
    dim: "rgba(231,233,236,0.55)",
    dimmer: "rgba(231,233,236,0.35)",
    accent: "#00D4C8",
    green: "#00C389",
    red: "#E5484D",
    mono: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
    sans: '"Inter Tight", "Inter", system-ui, -apple-system, sans-serif',
  };

  function fmtPct(value, digits = 1) {
    if (value === null || value === undefined || Number.isNaN(Number(value))) return "—";
    return `${Number(value).toFixed(digits)}%`;
  }

  function fmtNumber(value, digits = 1) {
    if (value === null || value === undefined || Number.isNaN(Number(value))) return "—";
    return Number(value).toFixed(digits);
  }

  function fetchFeatured() {
    return fetch("/api/v1/public/main-page")
      .then((response) => {
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json();
      });
  }

  function Nav({ onApply, r }) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: r.isMobile ? "12px 16px" : "14px 32px", borderBottom: `1px solid ${theme.border}`, background: theme.bg, gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 14, height: 14, background: theme.accent, transform: "rotate(45deg)", flexShrink: 0 }} />
          <span style={{ fontSize: 15, fontFamily: theme.sans, fontWeight: 600, letterSpacing: "-0.01em" }}>Apex Algo</span>
        </div>
        <div style={{ display: "flex", gap: 8, flexShrink: 0, alignItems: "center" }}>
          <a href="/members" style={{ ...btnSecondary(theme, r.isMobile ? { padding: "8px 10px", fontSize: 12 } : {}), textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6, whiteSpace: "nowrap" }} aria-label="Members area">
            <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="10" height="10" rx="1"/><path d="M7 8h6M10 5l3 3-3 3"/></svg>
            {r.isMobile ? "Members" : "Members area"}
          </a>
          <button onClick={onApply} style={btnPrimary(theme, r.isMobile ? { padding: "8px 12px", fontSize: 12 } : {})}>{r.isMobile ? "Free trial →" : "Start 14-day free trial →"}</button>
        </div>
      </div>
    );
  }

  function SectionHead({ eyebrow, title, sub, r }) {
    return (
      <div>
        <div style={{ fontSize: 11, letterSpacing: "0.2em", color: theme.accent, fontFamily: theme.mono, textTransform: "uppercase" }}>{eyebrow}</div>
        <div style={{ fontFamily: theme.sans, fontSize: r.isMobile ? 26 : 36, letterSpacing: "-0.02em", color: theme.fg, marginTop: 8, maxWidth: 760, lineHeight: 1.12 }}>{title}</div>
        {sub && <div style={{ color: theme.dim, fontSize: r.isMobile ? 14 : 15, marginTop: 10, maxWidth: 640, lineHeight: 1.6 }}>{sub}</div>}
      </div>
    );
  }

  function MetricCard({ label, value, tone = "fg", note }) {
    return (
      <div style={{ border: `1px solid ${theme.border}`, background: theme.surfaceAlt, padding: "18px 18px 16px" }}>
        <div style={{ fontSize: 10, letterSpacing: "0.14em", color: theme.dimmer, fontFamily: theme.mono, textTransform: "uppercase" }}>{label}</div>
        <div style={{ fontFamily: theme.mono, fontSize: 28, marginTop: 8, color: tone === "accent" ? theme.accent : tone === "red" ? theme.red : theme.fg }}>{value}</div>
        {note ? <div style={{ color: theme.dim, fontSize: 12, marginTop: 8, lineHeight: 1.5 }}>{note}</div> : null}
      </div>
    );
  }

  function RiskTabs({ riskProfiles, activeRiskId, onChange, r }) {
    return (
      <div style={{ display: "inline-flex", gap: 0, border: `1px solid ${theme.border}` }}>
        {riskProfiles.map((risk) => {
          const active = risk.id === activeRiskId;
          return (
            <button
              key={risk.id}
              type="button"
              onClick={() => onChange(risk.id)}
              style={{
                background: active ? theme.accent : "transparent",
                color: active ? "#0A0B0D" : theme.dim,
                border: "none",
                borderLeft: riskProfiles[0].id === risk.id ? "none" : `1px solid ${theme.border}`,
                padding: r.isMobile ? "9px 12px" : "10px 16px",
                fontSize: 12,
                fontFamily: theme.mono,
                cursor: "pointer",
              }}
            >
              {risk.label}
            </button>
          );
        })}
      </div>
    );
  }

  function Hero({ featured, activeRisk, activeRiskId, onRiskChange, onApply, r, loading, error }) {
    const annualReturn = fmtPct(activeRisk?.annualized_return_pct);
    const maxDrawdown = fmtPct(activeRisk?.max_drawdown_pct);
    const strategyCount = featured?.strategy_count || 10;
    const tradeStats = featured?.trade_stats || {};
    const avgTradesPerMonth = fmtNumber(tradeStats.average_trades_per_month, 1);
    const avgHoldTime = tradeStats.average_hold_time || "—";
    return (
      <section style={{ padding: r.isMobile ? "40px 16px 40px" : "64px 32px 56px", borderBottom: `1px solid ${theme.border}`, position: "relative", overflow: "hidden" }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: `linear-gradient(${theme.border} 1px, transparent 1px), linear-gradient(90deg, ${theme.border} 1px, transparent 1px)`,
          backgroundSize: "64px 64px", maskImage: "radial-gradient(ellipse at 80% 50%, #000 30%, transparent 75%)",
          opacity: 0.6, pointerEvents: "none",
        }} />
        <div style={{ position: "relative", display: "grid", gridTemplateColumns: r.isMobile ? "1fr" : "1.04fr 0.96fr", gap: r.isMobile ? 28 : 48, alignItems: "stretch" }}>
          <div>
            <div style={{ fontSize: 11, letterSpacing: "0.2em", color: theme.accent, fontFamily: theme.mono, textTransform: "uppercase", marginBottom: r.isMobile ? 14 : 18 }}>
              Featured models
            </div>
            <h2 style={{ fontFamily: theme.sans, fontSize: r.isMobile ? 30 : 48, lineHeight: 1.05, letterSpacing: "-0.025em", margin: 0, fontWeight: 500 }}>
              {featured?.label || "BTC Algo 0001"}
            </h2>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 0, marginTop: r.isMobile ? 32 : 44, borderTop: `1px solid ${theme.border}`, borderLeft: `1px solid ${theme.border}` }}>
              {[
                { k: "Asset", v: (featured?.asset || "BTC").toUpperCase() },
                { k: "Strategies", v: String(strategyCount) },
                { k: "Avg trades / month", v: avgTradesPerMonth },
                { k: "Avg hold time", v: avgHoldTime },
              ].map((item) => (
                <div key={item.k} style={{ padding: "14px 16px", borderRight: `1px solid ${theme.border}`, borderBottom: `1px solid ${theme.border}` }}>
                  <div style={{ fontSize: 10, letterSpacing: "0.12em", color: theme.dimmer, fontFamily: theme.mono, textTransform: "uppercase" }}>{item.k}</div>
                  <div style={{ fontFamily: theme.mono, fontSize: r.isMobile ? 16 : 18, color: theme.fg, marginTop: 5 }}>{item.v}</div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ border: `1px solid ${theme.borderStrong}`, background: theme.surface, display: "flex", flexDirection: "column", minHeight: "100%" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 14px", borderBottom: `1px solid ${theme.border}`, fontFamily: theme.mono, fontSize: 11, color: theme.dim, gap: 12 }}>
              <span>APX://main/featured</span>
              <span style={{ color: theme.green }}>● backtested window</span>
            </div>
            <div style={{ padding: r.isMobile ? 16 : 18, display: "grid", gap: 16, flex: 1 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                <div>
                  <div style={{ fontSize: 11, color: theme.dim, fontFamily: theme.mono, letterSpacing: "0.1em" }}>APPROVED RISK PROFILES</div>
                </div>
                <RiskTabs riskProfiles={featured?.risk_profiles || []} activeRiskId={activeRiskId} onChange={onRiskChange} r={r} />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: r.isMobile ? "1fr" : "1fr 1fr", gap: 14 }}>
                <MetricCard
                  label="Historic annual return (backtested)"
                  value={loading ? "…" : annualReturn}
                  tone="accent"
                  note={activeRisk ? `${activeRisk.label} profile` : null}
                />
                <MetricCard
                  label="Max historic drawdown (backtested)"
                  value={loading ? "…" : maxDrawdown}
                  tone="fg"
                  note={activeRisk ? `${activeRisk.label} profile` : null}
                />
              </div>

              <div style={{ borderTop: `1px solid ${theme.border}`, paddingTop: 14, color: theme.dim, fontSize: 12.5, lineHeight: 1.6 }}>
                <div>
                  {error
                    ? "Public performance data is temporarily unavailable."
                    : featured?.disclaimer || "Based on the prior 3-year backtest window. Past performance does not guarantee future results."}
                </div>
                {!error && featured?.live_calibration_note ? (
                  <div style={{ marginTop: 8 }}>
                    {featured.live_calibration_note}
                  </div>
                ) : null}
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  function Process({ r }) {
    const steps = [
      { n: "01", k: "We research and validate", d: "Strategies are developed through our proprietary research process, then promoted only after they pass live validation." },
      { n: "02", k: "You connect your exchange", d: "Link a supported exchange or broker account." },
      { n: "03", k: "You choose the approved risk profile", d: "Select the approved risk profile that fits you, then launch the model on your own account." },
      { n: "04", k: "The software trades for you", d: "The software runs on your broker or exchange. We license the system; we do not handle your money." },
    ];
    const cols = r.isMobile ? 1 : (r.isTablet ? 2 : 4);
    return (
      <section id="process" style={{ padding: r.isMobile ? "56px 16px" : "88px 32px", borderBottom: `1px solid ${theme.border}` }}>
        <SectionHead eyebrow="How it works" title="From our research to your account, in four steps." r={r} />
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 0, marginTop: r.isMobile ? 28 : 40, borderTop: `1px solid ${theme.border}` }}>
          {steps.map((step, index) => (
            <div key={step.n} style={{ padding: r.isMobile ? "22px 18px 24px" : "26px 24px 32px", borderRight: ((index + 1) % cols !== 0) ? `1px solid ${theme.border}` : "none", borderBottom: `1px solid ${theme.border}` }}>
              <div style={{ fontFamily: theme.mono, fontSize: 11, color: theme.dimmer, letterSpacing: "0.14em" }}>{step.n} / 04</div>
              <div style={{ fontFamily: theme.sans, fontSize: r.isMobile ? 20 : 22, color: theme.fg, marginTop: 10, marginBottom: 10, letterSpacing: "-0.01em" }}>{step.k}</div>
              <div style={{ color: theme.dim, fontSize: 13.5, lineHeight: 1.6 }}>{step.d}</div>
            </div>
          ))}
        </div>
      </section>
    );
  }

  function Pricing({ onApply, r }) {
    const plans = [
      {
        name: "Access License",
        price: "$4,999",
        suffix: "upfront",
        note: "$499/mo · up to $100k allocated capital",
      },
      {
        name: "Lifetime License",
        price: "$20,000",
        suffix: "one-time",
        note: "No monthly dues · up to $250k allocated capital",
      },
      {
        name: "Lifetime License Unlimited",
        price: "$20,000",
        suffix: "+ $999/mo",
        note: "No allocated-capital limit",
      },
    ];
    return (
      <section id="pricing" style={{ padding: r.isMobile ? "56px 16px" : "88px 32px", borderBottom: `1px solid ${theme.border}`, background: theme.surface }}>
        <SectionHead eyebrow="Pricing" title="Choose the license that matches your account size." r={r} />
        <div style={{ display: "grid", gridTemplateColumns: r.isMobile ? "1fr" : "repeat(3, 1fr)", gap: 0, marginTop: r.isMobile ? 28 : 40, borderTop: `1px solid ${theme.borderStrong}`, borderLeft: `1px solid ${theme.borderStrong}` }}>
          {plans.map((plan) => (
            <div key={plan.name} style={{ padding: r.isMobile ? 24 : 30, background: theme.surfaceAlt, borderRight: `1px solid ${theme.borderStrong}`, borderBottom: `1px solid ${theme.borderStrong}`, display: "flex", flexDirection: "column", minHeight: r.isMobile ? 210 : 240 }}>
              <div style={{ fontFamily: theme.mono, fontSize: 11, color: theme.accent, letterSpacing: "0.14em", textTransform: "uppercase" }}>{plan.name}</div>
              <div style={{ fontFamily: theme.sans, fontSize: r.isMobile ? 38 : 44, letterSpacing: "-0.03em", marginTop: 16, lineHeight: 1 }}>
                {plan.price}<span style={{ fontSize: r.isMobile ? 13 : 15, color: theme.dim, marginLeft: 8 }}>USD</span>
              </div>
              <div style={{ color: theme.fg, fontSize: 14, marginTop: 10, fontFamily: theme.mono }}>{plan.suffix}</div>
              <div style={{ color: theme.dim, fontSize: 13, marginTop: 12, lineHeight: 1.55 }}>{plan.note}</div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 18, color: theme.dim, fontSize: 12.5, lineHeight: 1.6, marginTop: 18, textAlign: "center" }}>
          <div style={{ maxWidth: 760 }}>
            No performance fee. Client funds remain with their broker or exchange.
          </div>
          <button onClick={onApply} style={btnSecondary(theme, { padding: "13px 22px", fontSize: 14, width: r.isMobile ? "100%" : "auto" })}>
            Apply for a license
          </button>
        </div>
      </section>
    );
  }

  function FAQSection({ r }) {
    return (
      <section id="faq" style={{ padding: r.isMobile ? "56px 16px" : "88px 32px", borderBottom: `1px solid ${theme.border}` }}>
        <div style={{ display: "grid", gridTemplateColumns: r.isMobile ? "1fr" : "1fr 2fr", gap: r.isMobile ? 28 : 60, alignItems: "flex-start" }}>
          <SectionHead eyebrow="FAQ" title="Questions worth answering." r={r} />
          <FAQ items={D.faqs} theme={theme} />
        </div>
      </section>
    );
  }

  function FinalCTA({ onApply, r }) {
    return (
      <section style={{ padding: r.isMobile ? "56px 16px" : "88px 32px", borderBottom: `1px solid ${theme.border}`, textAlign: "center", position: "relative", overflow: "hidden" }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: `linear-gradient(${theme.border} 1px, transparent 1px)`,
          backgroundSize: "100% 48px",
          opacity: 0.8,
          pointerEvents: "none",
          maskImage: "radial-gradient(ellipse at center, #000 20%, transparent 70%)",
        }} />
        <div style={{ position: "relative" }}>
          <div style={{ fontSize: 11, color: theme.accent, fontFamily: theme.mono, letterSpacing: "0.2em" }}>APPLICATIONS OPEN</div>
          <h2 style={{ fontFamily: theme.sans, fontSize: r.isMobile ? 30 : 48, margin: "16px auto 20px", letterSpacing: "-0.02em", maxWidth: 720, lineHeight: 1.12 }}>
            If the numbers earn your attention, apply.
          </h2>
          <p style={{ color: theme.dim, fontSize: r.isMobile ? 14 : 15, maxWidth: 520, margin: "0 auto 28px", lineHeight: 1.6 }}>
            We review applications personally. Reach us at <span style={{ fontFamily: theme.mono, color: theme.fg, wordBreak: "break-all" }}>access@theapexalgo.com</span>.
          </p>
          <button onClick={onApply} style={btnSecondary(theme, { padding: "14px 26px", fontSize: 15 })}>Apply for a license</button>
        </div>
      </section>
    );
  }

  function Footer({ r }) {
    return (
      <footer style={{ padding: r.isMobile ? "32px 16px 24px" : "48px 32px 32px", color: theme.dimmer }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 32, flexWrap: "wrap" }}>
          <div style={{ maxWidth: 460 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <div style={{ width: 12, height: 12, background: theme.accent, transform: "rotate(45deg)" }} />
              <span style={{ fontSize: 14, fontFamily: theme.sans, fontWeight: 600, color: theme.fg, letterSpacing: "-0.01em" }}>Apex Algo</span>
            </div>
            <div style={{ fontSize: 11.5, lineHeight: 1.7, fontFamily: theme.mono, color: theme.dim }}>
              Past performance does not guarantee future results. Trading involves substantial risk of loss. Apex Algo provides a software license and does not custody client capital or provide investment advice.
            </div>
          </div>
          <div style={{ display: "flex", gap: 48, fontFamily: theme.mono, fontSize: 12 }}>
            <div>
              <div style={{ color: theme.dim, letterSpacing: "0.14em", marginBottom: 10, fontSize: 10 }}>CONTACT</div>
              <div style={{ lineHeight: 2, color: theme.fg }}>
                <div>access@theapexalgo.com</div>
              </div>
            </div>
          </div>
        </div>
        <div style={{ borderTop: `1px solid ${theme.border}`, marginTop: 32, paddingTop: 18, display: "flex", justifyContent: "space-between", fontFamily: theme.mono, fontSize: 11, color: theme.dimmer }}>
          <span>© 2026 Apex Algo</span>
          <span>theapexalgo.com</span>
        </div>
      </footer>
    );
  }

  function App() {
    const [modal, setModal] = useState(false);
    const [featured, setFeatured] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    const [activeRiskId, setActiveRiskId] = useState("moderate");
    const r = useResponsive();

    useEffect(() => {
      let cancelled = false;
      setLoading(true);
      fetchFeatured()
        .then((payload) => {
          if (cancelled) return;
          setFeatured(payload);
          const available = Array.isArray(payload?.risk_profiles) ? payload.risk_profiles : [];
          const defaultRisk = payload?.default_risk_profile_id || available[0]?.id || "moderate";
          setActiveRiskId(defaultRisk);
          setError("");
        })
        .catch(() => {
          if (cancelled) return;
          setError("Failed to load public model data.");
        })
        .finally(() => {
          if (!cancelled) setLoading(false);
        });
      return () => {
        cancelled = true;
      };
    }, []);

    const riskProfiles = Array.isArray(featured?.risk_profiles) ? featured.risk_profiles : [];
    const activeRisk = riskProfiles.find((risk) => risk.id === activeRiskId) || riskProfiles[0] || null;

    return (
      <div style={{ background: theme.bg, color: theme.fg, fontFamily: theme.sans, minHeight: "100%" }}>
        <Nav onApply={() => setModal(true)} r={r} />
        <HumansVsMachinesHero theme={theme} r={r} onApply={() => setModal(true)} />
        <Hero
          featured={featured}
          activeRisk={activeRisk}
          activeRiskId={activeRiskId}
          onRiskChange={setActiveRiskId}
          onApply={() => setModal(true)}
          r={r}
          loading={loading}
          error={error}
        />
        <Process r={r} />
        <Pricing onApply={() => setModal(true)} r={r} />
        <FAQSection r={r} />
        <FinalCTA onApply={() => setModal(true)} r={r} />
        <Footer r={r} />
        <ApplyModal open={modal} onClose={() => setModal(false)} theme={theme} />
      </div>
    );
  }

  ReactDOM.createRoot(mount).render(<App />);
};

function btnPrimary(t, extra = {}) {
  return {
    background: t.accent,
    color: "#0A0B0D",
    border: "none",
    padding: "9px 16px",
    fontSize: 13,
    fontWeight: 500,
    cursor: "pointer",
    borderRadius: 2,
    fontFamily: t.sans,
    letterSpacing: "-0.005em",
    ...extra,
  };
}

function btnSecondary(t, extra = {}) {
  return {
    background: "transparent",
    color: t.fg,
    border: `1px solid ${t.border}`,
    padding: "9px 16px",
    fontSize: 13,
    cursor: "pointer",
    borderRadius: 2,
    fontFamily: t.sans,
    ...extra,
  };
}
