const DEFAULT_TOP_SKILLS = [
  "Quant Research",
  "Python",
  "C++",
  "Derivatives / Options",
  "Market Making",
  "Execution / TCA",
  "Monte Carlo",
  "Risk Management",
  "Market Microstructure",
  "Backtesting (Walk-forward)",
  "Reinforcement Learning",
  "Time Series",
  "Statistics",
  "Optimization",
  "XGBoost",
  "OpenMP / Parallelism",
];

const DEFAULT_SKILLS_GRAPH = {
  "Alpha Research": ["Hoops-Spread", "Election Microstructure", "IMC Prosperity"],
  "Signal Processing (FFT)": ["Fourier Trading Factor", "Hoops-Spread", "Monte Carlo Pricer"],
  "Backtesting (Walk-forward)": ["Hoops-Spread", "RL Hedger"],
  "Market Microstructure": ["Election Microstructure", "MQC Market Making", "RL Hedger"],
  "Market Making": ["MQC Market Making", "SCALP Trade (Incoming)", "IMC Prosperity"],
  "Execution / TCA": ["RL Hedger", "MQC Market Making", "SCALP Trade (Incoming)"],
  "Risk Management": ["RL Hedger", "Hoops-Spread", "IMC Prosperity"],
  "Portfolio / Kelly": ["Hoops-Spread", "IMC Prosperity"],
  "Derivatives (Greeks)": ["RL Hedger", "Monte Carlo Pricer"],
  "Options Pricing": ["Monte Carlo Pricer", "RL Hedger"],
  "Rough Volatility (rBergomi)": ["RL Hedger", "Monte Carlo Pricer"],
  "Monte Carlo Simulation": ["Monte Carlo Pricer", "RL Hedger"],
  "American Options (LSM)": ["Monte Carlo Pricer"],
  "Bounds (Dual / Branching)": ["Monte Carlo Pricer"],
  "Reinforcement Learning": ["RL Hedger"],
  "Deep Learning (PyTorch/LibTorch)": ["RL Hedger", "Monte Carlo Pricer", "DemandEngine"],
  "Bayesian / Uncertainty": ["Monte Carlo Pricer", "RL Hedger"],
  "Machine Learning (XGBoost)": ["Hoops-Spread", "IMC Prosperity"],
  "Feature Selection (Boruta/SHAP)": ["Hoops-Spread"],
  "Time Series": ["Hoops-Spread", "Election Microstructure", "IMC Prosperity"],
  "Econometrics (VAR/Granger)": ["Election Microstructure"],
  "Clustering (GMM)": ["Election Microstructure"],
  "Hypothesis Testing": ["Election Microstructure", "Hoops-Spread"],
  "Optimization (Optuna/HPO)": ["RL Hedger", "Hoops-Spread"],
  "Numerical Methods": ["Monte Carlo Pricer", "RL Hedger"],
  "Parallel Computing (OpenMP)": ["Monte Carlo Pricer"],
  "GPU Acceleration (CUDA/CuPy)": ["RL Hedger", "Monte Carlo Pricer"],
  "Data Visualization": ["Hoops-Spread", "Election Microstructure", "Monte Carlo Pricer", "RL Hedger"],
  "Data Engineering / ETL": ["DemandEngine", "Hoops-Spread", "Election Microstructure"],
  "APIs / Data Feeds": ["Election Microstructure", "DemandEngine"],
  "Web Scraping": ["Hoops-Spread", "DemandEngine", "Election Microstructure"],
  Databases: ["DemandEngine"],
  "Web Security": ["DemandEngine"],
  "CI/CD & Deployment": ["DemandEngine"],
  "Product Engineering": ["DemandEngine"],
  Python: ["Hoops-Spread", "RL Hedger", "Election Microstructure", "DemandEngine", "IMC Prosperity"],
  "C++": ["Monte Carlo Pricer"],
  Competitions: ["IMC Prosperity", "MQC Market Making"],
  "Quant Internship": ["SCALP Trade (Incoming)"],
  "FEA / Structural Analysis": ["Rocket Lab", "Copeland", "EMTECH"],
  "Thermal Analysis": ["Harris", "EMTECH"],
  Robotics: ["Michigan Robotic Submarine", "Safety Enclosure", "Competitive Robot Design"],
  "CAD & Design": ["Michigan Robotic Submarine", "Safety Enclosure", "Competitive Robot Design"],
  "CFD & Simulation": ["Michigan Robotic Submarine", "Safety Enclosure"],
  "NLP / Sentiment": ["Hoops-Spread", "DemandEngine", "Stealth Startup"],
  Java: ["Android Apps"],
  GIS: ["Iklaina Archaeological Project"],
};

const DEFAULT_FULL_SKILLS_LIST = {
  "Quant Trading": [
    "Alpha Research & Signal Design",
    "Backtesting",
    "Market Making",
    "Execution & TCA",
    "Risk Management",
    "Portfolio Construction & Kelly Sizing",
    "Performance Metrics",
    "Strategy Evaluation",
    "Research Workflows",
  ],
  "Derivatives & Volatility": [
    "Black-Scholes & Greeks",
    "Delta / Gamma / Vega Hedging",
    "American Options (LSM, branching bounds)",
    "Monte Carlo Pricing",
    "Rough Volatility (rBergomi)",
    "Path Simulation (fGn / FFT)",
    "Volatility Surfaces",
    "Stress / Scenario Analysis",
  ],
  "Market Microstructure & Econometrics": [
    "Flow / Impact Regressions",
    "Power Laws & Tail Behavior",
    "Stationarity Testing & Differencing",
    "VAR / Granger Causality",
    "Event Studies",
    "GMM Clustering",
    "Nonparametric Tests",
  ],
  "Modeling, ML & RL": [
    "XGBoost",
    "Feature Selection (Boruta) & SHAP",
    "Deep Learning (PyTorch)",
    "Reinforcement Learning (PPO, LSTM)",
    "Bayesian / Uncertainty Quantification",
    "Hyperparameter Optimization",
    "Time Series Features",
    "NLP & Sentiment",
  ],
  "Quant Engineering & Performance": [
    "C++17",
    "OpenMP Parallelism",
    "GPU Acceleration (CUDA / CuPy)",
    "Vectorization",
    "Profiling / Benchmarking",
    "Numerical Stability",
    "CLI Tooling",
  ],
  "Data Engineering": [
    "Data Ingestion",
    "ETL Pipelines",
    "Data Cleaning",
    "SQL / Postgres",
    "Parquet / Columnar Storage",
    "DuckDB",
    "Data Quality",
  ],
  "Software & Product": [
    "Python",
    "API Development",
    "Full-Stack Web (React / Django / FastAPI)",
    "Web Security",
    "CI/CD & Deployment",
    "Observability",
  ],
  "Tools & Platforms": [
    "Backtrader",
    "Gym / RL tooling",
    "PyTorch",
    "NumPy / Pandas",
    "Matplotlib",
    "OpenMP",
    "CUDA / CuPy",
    "PostgreSQL / DuckDB",
    "Vercel / GCP",
  ],
  "Engineering & Simulation": [
    "FEA",
    "CFD",
    "Structural / Thermal Analysis",
    "Modal / Vibration Analysis",
    "CAD (SolidWorks)",
    "Robotics",
    "Test Automation",
    "GIS / Digital Mapping",
  ],
};

function getCompanyKeyFromPath() {
  return window.location.pathname.split("/").filter(Boolean)[0] || "";
}

function useCompanyRouteConfig() {
  const [companyConfig, setCompanyConfig] = React.useState(null);
  const [modalOpen, setModalOpen] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    const companyKey = getCompanyKeyFromPath();

    if (!companyKey) {
      setCompanyConfig(null);
      setModalOpen(false);
      return undefined;
    }

    fetch("/configs.json")
      .then((response) => {
        if (!response.ok) throw new Error("configs.json not found");
        return response.json();
      })
      .then((configs) => {
        if (cancelled) return;
        const nextConfig = configs?.[companyKey] || null;
        setCompanyConfig(nextConfig);
        setModalOpen(Boolean(nextConfig));
      })
      .catch((error) => {
        console.error("Could not load company config:", error);
        if (cancelled) return;
        setCompanyConfig(null);
        setModalOpen(false);
      });

    return () => {
      cancelled = true;
    };
  }, []);

  return {
    companyConfig,
    modalOpen,
    closeModal: () => setModalOpen(false),
    openModal: () => setModalOpen(true),
  };
}

function CompanyFitModal({ config, open, onClose }) {
  const [phase, setPhase] = React.useState("prompt");

  React.useEffect(() => {
    setPhase("prompt");
  }, [config?.company, open]);

  if (!config || !open) return null;

  const bulletsMarkdown = Array.isArray(config.fitBullets)
    ? config.fitBullets.map((bullet) => `* ${bullet}`).join("\n")
    : "";

  return (
    <div style={{
      position: "fixed",
      inset: 0,
      zIndex: 80,
      background: "rgba(5,5,6,0.72)",
      backdropFilter: "blur(10px)",
      display: "grid",
      placeItems: "center",
      padding: 24,
    }}>
      <div style={{
        width: "min(760px, 100%)",
        background: "#101012",
        border: "1px solid rgba(237,233,224,0.12)",
        borderRadius: 10,
        boxShadow: "0 30px 80px rgba(0,0,0,0.45)",
        overflow: "hidden",
      }}>
        <div style={{
          padding: "14px 18px",
          borderBottom: "1px solid rgba(237,233,224,0.08)",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 10,
          letterSpacing: "0.22em",
          textTransform: "uppercase",
          color: "rgba(237,233,224,0.48)",
        }}>
          <span>incoming context</span>
          <button onClick={onClose} style={{ background: "transparent", border: "none", color: "rgba(237,233,224,0.65)", cursor: "pointer", fontSize: 18 }}>×</button>
        </div>
        <div style={{ padding: "24px 26px 28px" }}>
          {phase === "prompt" ? (
            <>
              <div style={{
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 11,
                letterSpacing: "0.16em",
                textTransform: "uppercase",
                color: "#6EE7F4",
                marginBottom: 10,
              }}>
                {config.company}
              </div>
              <h2 style={{
                margin: 0,
                fontFamily: "'Instrument Serif', Georgia, serif",
                fontWeight: 400,
                fontSize: "clamp(34px, 5vw, 48px)",
                lineHeight: 1.02,
                letterSpacing: "-0.02em",
              }}>
                Want the short version of why Baz fits the {config.jobTitle} role?
              </h2>
              <p style={{ margin: "18px 0 0", fontSize: 16, lineHeight: 1.65, color: "rgba(237,233,224,0.7)" }}>
                The rest of the site stays fully open. This just keeps the company-specific context that the old site surfaced when you landed on a tailored route.
              </p>
              <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 24 }}>
                <button onClick={() => setPhase("bullets")} style={{
                  padding: "11px 16px",
                  borderRadius: 999,
                  border: "none",
                  background: "#6EE7F4",
                  color: "#0A0A0B",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 11,
                  letterSpacing: "0.14em",
                  textTransform: "uppercase",
                  cursor: "pointer",
                }}>
                  Sure
                </button>
                <button onClick={onClose} style={{
                  padding: "11px 16px",
                  borderRadius: 999,
                  border: "1px solid rgba(237,233,224,0.14)",
                  background: "transparent",
                  color: "#EDE9E0",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 11,
                  letterSpacing: "0.14em",
                  textTransform: "uppercase",
                  cursor: "pointer",
                }}>
                  I’ll look around
                </button>
              </div>
            </>
          ) : (
            <>
              <div style={{
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 11,
                letterSpacing: "0.16em",
                textTransform: "uppercase",
                color: "#6EE7F4",
                marginBottom: 10,
              }}>
                Why he fits
              </div>
              <div
                style={{
                  fontSize: 15,
                  lineHeight: 1.7,
                  color: "rgba(237,233,224,0.8)",
                }}
                dangerouslySetInnerHTML={{ __html: marked.parse(bulletsMarkdown) }}
              />
              <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 24 }}>
                <button onClick={onClose} style={{
                  padding: "11px 16px",
                  borderRadius: 999,
                  border: "none",
                  background: "#6EE7F4",
                  color: "#0A0A0B",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 11,
                  letterSpacing: "0.14em",
                  textTransform: "uppercase",
                  cursor: "pointer",
                }}>
                  Awesome, thanks
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function SkillsExperienceMap({ skillsData }) {
  const canvasRef = React.useRef(null);
  const detailsRef = React.useRef(null);
  const controlsRef = React.useRef({
    zoomIn: null,
    zoomOut: null,
    panLeft: null,
    panRight: null,
    panUp: null,
    panDown: null,
    reset: null,
  });

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const detailsEl = detailsRef.current;
    if (!canvas) return undefined;

    const ctx = canvas.getContext("2d");
    const dataToUse = skillsData && Object.keys(skillsData).length > 0 ? skillsData : DEFAULT_SKILLS_GRAPH;
    let width = canvas.clientWidth;
    let height = canvas.clientHeight;
    canvas.width = width;
    canvas.height = height;
    canvas.style.cursor = "grab";

    const nodes = [];
    const links = [];
    const skillNodes = {};
    const projectNodes = {};

    Object.keys(dataToUse).forEach((skill) => {
      const connectionCount = dataToUse[skill].length;
      const radius = 8 + connectionCount * 1.5;
      const node = { id: skill, type: "skill", radius, x: width / 2 + (Math.random() - 0.5) * 10, y: height / 2 + (Math.random() - 0.5) * 10, vx: 0, vy: 0 };
      nodes.push(node);
      skillNodes[skill] = node;
    });

    const allProjects = [...new Set(Object.values(dataToUse).flat())];
    allProjects.forEach((project) => {
      const node = { id: project, type: "project", radius: 8, x: width / 2 + (Math.random() - 0.5) * 10, y: height / 2 + (Math.random() - 0.5) * 10, vx: 0, vy: 0 };
      nodes.push(node);
      projectNodes[project] = node;
    });

    Object.entries(dataToUse).forEach(([skill, projects]) => {
      projects.forEach((project) => {
        if (skillNodes[skill] && projectNodes[project]) {
          links.push({ source: skillNodes[skill], target: projectNodes[project] });
        }
      });
    });

    const adjacency = new Map();
    nodes.forEach((node) => adjacency.set(node, new Set()));
    links.forEach((link) => {
      adjacency.get(link.source)?.add(link.target);
      adjacency.get(link.target)?.add(link.source);
    });

    ctx.font = '10px "JetBrains Mono"';
    nodes.forEach((node) => {
      node.textWidth = ctx.measureText(node.id).width;
    });

    function renderNodeDetails(node, focusedNode) {
      if (!detailsEl) return;

      if (!node) {
        detailsEl.innerHTML = `
          <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
            <strong style="font-size:13px;color:#EDE9E0;">Selection</strong>
            <span style="font-size:11px;color:rgba(237,233,224,0.45);">hover or click</span>
          </div>
          <p style="margin:10px 0 0;font-size:12px;line-height:1.6;color:rgba(237,233,224,0.55);">Hover a node to preview its neighborhood. Click to pin it. Double-click the empty canvas to reset the view.</p>
        `;
        return;
      }

      const neighbors = Array.from(adjacency.get(node) || []);
      neighbors.sort((a, b) => (b.radius || 0) - (a.radius || 0));
      const chips = neighbors.slice(0, 18).map((neighbor) => `
        <span style="font-size:11px;padding:4px 8px;border-radius:999px;border:1px solid rgba(237,233,224,0.14);background:rgba(237,233,224,0.02);color:#EDE9E0;">${neighbor.id}</span>
      `).join("");
      const clickHint = focusedNode === node ? "Click again to unpin." : "Click to pin this node.";

      detailsEl.innerHTML = `
        <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;">
          <div>
            <strong style="display:block;font-size:14px;color:#EDE9E0;">${node.id}</strong>
            <span style="font-size:12px;color:rgba(237,233,224,0.55);">${node.type === "skill" ? "Connected projects / experiences" : "Connected skills"} · ${neighbors.length}</span>
          </div>
          <span style="font-size:10px;padding:4px 8px;border-radius:999px;border:1px solid rgba(237,233,224,0.14);color:rgba(237,233,224,0.6);text-transform:uppercase;letter-spacing:0.14em;">${node.type}</span>
        </div>
        <div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:12px;">${chips}</div>
        <p style="margin:12px 0 0;font-size:12px;color:rgba(237,233,224,0.55);">${clickHint}</p>
      `;
    }

    let transform = { x: 0, y: 0, k: 1 };
    let dragging = false;
    let dragStart = { x: 0, y: 0 };
    let hoveredNode = null;
    let focusedNode = null;
    let alpha = 0.01;
    let warmingUp = true;
    let frame = 0;

    function clampZoom() {
      transform.k = Math.max(0.45, Math.min(2.6, transform.k));
    }

    function zoomAtPoint(scaleAmount, pointX = width / 2, pointY = height / 2) {
      transform.x = pointX - (pointX - transform.x) * scaleAmount;
      transform.y = pointY - (pointY - transform.y) * scaleAmount;
      transform.k *= scaleAmount;
      clampZoom();
    }

    function panBy(dx, dy) {
      transform.x += dx;
      transform.y += dy;
    }

    function update() {
      if (warmingUp) {
        alpha += 0.1;
        if (alpha >= 0.5) {
          alpha = 1;
          warmingUp = false;
        }
      } else if (alpha > 0.005) {
        alpha *= 0.993;
      }

      links.forEach((link) => {
        const dx = link.target.x - link.source.x;
        const dy = link.target.y - link.source.y;
        const distance = Math.sqrt(dx * dx + dy * dy) || 1;
        const force = (distance - 150) * 0.001 * alpha;
        const fx = (dx / distance) * force;
        const fy = (dy / distance) * force;
        link.source.vx += fx;
        link.source.vy += fy;
        link.target.vx -= fx;
        link.target.vy -= fy;
      });

      for (let i = 0; i < nodes.length; i += 1) {
        for (let j = i + 1; j < nodes.length; j += 1) {
          const left = nodes[i];
          const right = nodes[j];
          const dx = right.x - left.x;
          const dy = right.y - left.y;
          const distance = Math.sqrt(dx * dx + dy * dy) || 1;
          const minDistance = Math.max(left.radius, left.textWidth / 2) + Math.max(right.radius, right.textWidth / 2) + 30;
          if (distance < minDistance) {
            const force = (minDistance - distance) * 0.3 * alpha;
            const fx = (dx / distance) * force;
            const fy = (dy / distance) * force;
            left.vx -= fx;
            left.vy -= fy;
            right.vx += fx;
            right.vy += fy;
          }
        }
      }

      const centerX = width / 2;
      const centerY = height / 2;
      nodes.forEach((node) => {
        node.vx += (centerX - node.x) * 0.005 * alpha;
        node.vy += (centerY - node.y) * 0.005 * alpha;
        node.vx *= 0.98;
        node.vy *= 0.98;
        node.x += node.vx;
        node.y += node.vy;
      });
    }

    function draw() {
      ctx.save();
      ctx.clearRect(0, 0, width, height);
      ctx.translate(transform.x, transform.y);
      ctx.scale(transform.k, transform.k);

      const activeNode = focusedNode || hoveredNode;
      const connectedNodes = new Set();
      if (activeNode) {
        connectedNodes.add(activeNode);
        links.forEach((link) => {
          if (link.source === activeNode) connectedNodes.add(link.target);
          if (link.target === activeNode) connectedNodes.add(link.source);
        });
      }

      renderNodeDetails(activeNode, focusedNode);

      links.forEach((link) => {
        const isActive = activeNode && (link.source === activeNode || link.target === activeNode);
        ctx.beginPath();
        ctx.moveTo(link.source.x, link.source.y);
        ctx.lineTo(link.target.x, link.target.y);
        ctx.strokeStyle = isActive ? "rgba(110,231,244,0.85)" : "rgba(237,233,224,0.18)";
        ctx.globalAlpha = isActive ? 0.9 : 0.35;
        ctx.stroke();
      });
      ctx.globalAlpha = 1;

      nodes.forEach((node) => {
        const isActive = activeNode === node;
        const isConnected = connectedNodes.has(node);
        ctx.beginPath();
        ctx.arc(node.x, node.y, node.radius, 0, Math.PI * 2);
        ctx.fillStyle = node.type === "skill" ? "#6EE7F4" : "#D8B26E";
        ctx.globalAlpha = activeNode && !isConnected ? 0.22 : 1;
        ctx.fill();
        if (isActive) {
          ctx.strokeStyle = "#EDE9E0";
          ctx.lineWidth = 2;
          ctx.stroke();
        }
      });
      ctx.globalAlpha = 1;

      nodes.forEach((node) => {
        const shouldShow = activeNode ? connectedNodes.has(node) : true;
        if (!shouldShow) return;
        ctx.fillStyle = "#EDE9E0";
        ctx.font = '10px "JetBrains Mono"';
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillText(node.id, node.x, node.y + node.radius + 10);
      });

      ctx.restore();
    }

    function animate() {
      if (alpha > 0.005) update();
      draw();
      frame = requestAnimationFrame(animate);
    }

    function toWorldPosition(event) {
      const rect = canvas.getBoundingClientRect();
      return {
        x: (event.clientX - rect.left - transform.x) / transform.k,
        y: (event.clientY - rect.top - transform.y) / transform.k,
      };
    }

    function findNode(event) {
      const point = toWorldPosition(event);
      return nodes.find((node) => Math.sqrt((point.x - node.x) ** 2 + (point.y - node.y) ** 2) < node.radius) || null;
    }

    function handleMouseDown(event) {
      const clickedNode = findNode(event);
      if (clickedNode) {
        focusedNode = focusedNode === clickedNode ? null : clickedNode;
        return;
      }
      dragging = true;
      canvas.style.cursor = "grabbing";
      dragStart = { x: event.clientX - transform.x, y: event.clientY - transform.y };
    }

    function handleMouseUp() {
      dragging = false;
      canvas.style.cursor = "grab";
    }

    function handleMouseMove(event) {
      if (dragging) {
        transform.x = event.clientX - dragStart.x;
        transform.y = event.clientY - dragStart.y;
        return;
      }
      hoveredNode = findNode(event);
    }

    function handleWheel(event) {
      event.preventDefault();
      const rect = canvas.getBoundingClientRect();
      const mouseX = event.clientX - rect.left;
      const mouseY = event.clientY - rect.top;
      if (event.deltaY < 0) {
        zoomAtPoint(1.1, mouseX, mouseY);
      } else {
        zoomAtPoint(1 / 1.1, mouseX, mouseY);
      }
    }

    function handleDoubleClick(event) {
      if (findNode(event)) return;
      transform = { x: 0, y: 0, k: 1 };
    }

    function handleResize() {
      width = canvas.clientWidth;
      height = canvas.clientHeight;
      canvas.width = width;
      canvas.height = height;
    }

    function handleKeyDown(event) {
      if (event.key === "Escape") focusedNode = null;
    }

    controlsRef.current = {
      zoomIn: () => zoomAtPoint(1.12),
      zoomOut: () => zoomAtPoint(1 / 1.12),
      panLeft: () => panBy(36, 0),
      panRight: () => panBy(-36, 0),
      panUp: () => panBy(0, 36),
      panDown: () => panBy(0, -36),
      reset: () => {
        transform = { x: 0, y: 0, k: 1 };
        focusedNode = null;
      },
    };

    animate();
    canvas.addEventListener("mousedown", handleMouseDown);
    canvas.addEventListener("mouseup", handleMouseUp);
    canvas.addEventListener("mouseleave", handleMouseUp);
    canvas.addEventListener("mousemove", handleMouseMove);
    canvas.addEventListener("wheel", handleWheel, { passive: false });
    canvas.addEventListener("dblclick", handleDoubleClick);
    window.addEventListener("resize", handleResize);
    window.addEventListener("keydown", handleKeyDown);

    return () => {
      cancelAnimationFrame(frame);
      controlsRef.current = {
        zoomIn: null,
        zoomOut: null,
        panLeft: null,
        panRight: null,
        panUp: null,
        panDown: null,
        reset: null,
      };
      canvas.removeEventListener("mousedown", handleMouseDown);
      canvas.removeEventListener("mouseup", handleMouseUp);
      canvas.removeEventListener("mouseleave", handleMouseUp);
      canvas.removeEventListener("mousemove", handleMouseMove);
      canvas.removeEventListener("wheel", handleWheel);
      canvas.removeEventListener("dblclick", handleDoubleClick);
      window.removeEventListener("resize", handleResize);
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [skillsData]);

  return (
    <div data-skills-map="true" style={{ display: "grid", gridTemplateColumns: "1.2fr 0.85fr", gap: 18 }}>
      <div style={{ border: "1px solid rgba(237,233,224,0.1)", borderRadius: 8, background: "rgba(237,233,224,0.02)", overflow: "hidden" }}>
        <div style={{ padding: "10px 14px", borderBottom: "1px solid rgba(237,233,224,0.08)", fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(237,233,224,0.45)" }}>skills x experience map</div>
        <div style={{ height: 420, position: "relative" }}>
          <canvas ref={canvasRef} style={{ width: "100%", height: "100%", display: "block" }} />
          <div style={{
            position: "absolute",
            right: 10,
            bottom: 10,
            display: "grid",
            gap: 6,
            background: "rgba(10,10,11,0.72)",
            border: "1px solid rgba(237,233,224,0.14)",
            borderRadius: 8,
            padding: 8,
            backdropFilter: "blur(3px)",
          }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 30px)", gridTemplateAreas: '". up ." "left reset right" ". down ."', gap: 4, justifyContent: "center" }}>
              <button type="button" onClick={() => controlsRef.current.panUp?.()} aria-label="Pan up" style={{ gridArea: "up", ...mapControlButtonStyle }}>↑</button>
              <button type="button" onClick={() => controlsRef.current.panLeft?.()} aria-label="Pan left" style={{ gridArea: "left", ...mapControlButtonStyle }}>←</button>
              <button type="button" onClick={() => controlsRef.current.reset?.()} aria-label="Reset view" title="Reset" style={{ gridArea: "reset", ...mapControlButtonStyle }}>•</button>
              <button type="button" onClick={() => controlsRef.current.panRight?.()} aria-label="Pan right" style={{ gridArea: "right", ...mapControlButtonStyle }}>→</button>
              <button type="button" onClick={() => controlsRef.current.panDown?.()} aria-label="Pan down" style={{ gridArea: "down", ...mapControlButtonStyle }}>↓</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 4 }}>
              <button type="button" onClick={() => controlsRef.current.zoomOut?.()} aria-label="Zoom out" style={{ ...mapControlButtonStyle }}>-</button>
              <button type="button" onClick={() => controlsRef.current.zoomIn?.()} aria-label="Zoom in" style={{ ...mapControlButtonStyle }}>+</button>
            </div>
          </div>
        </div>
      </div>
      <div ref={detailsRef} style={{ border: "1px solid rgba(237,233,224,0.1)", borderRadius: 8, background: "rgba(237,233,224,0.02)", padding: 18, minHeight: 420 }} />
    </div>
  );
}

const mapControlButtonStyle = {
  width: 30,
  height: 26,
  borderRadius: 6,
  border: "1px solid rgba(237,233,224,0.16)",
  background: "rgba(237,233,224,0.04)",
  color: "#EDE9E0",
  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
  fontSize: 13,
  cursor: "pointer",
  lineHeight: 1,
};

function SkillsCatalog({ fullSkillsList }) {
  const [query, setQuery] = React.useState("");
  const normalizedQuery = query.trim().toLowerCase();
  const dataToUse = fullSkillsList && Object.keys(fullSkillsList).length > 0 ? fullSkillsList : DEFAULT_FULL_SKILLS_LIST;

  const filteredEntries = Object.entries(dataToUse)
    .map(([category, skills]) => [
      category,
      skills.filter((skill) => skill.toLowerCase().includes(normalizedQuery)),
    ])
    .filter(([, skills]) => skills.length > 0 || !normalizedQuery);

  return (
    <div>
      <div style={{ marginBottom: 18 }}>
        <input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          placeholder="search skills..."
          style={{
            width: "100%",
            padding: "12px 14px",
            borderRadius: 8,
            border: "1px solid rgba(237,233,224,0.12)",
            background: "rgba(237,233,224,0.03)",
            color: "#EDE9E0",
            fontSize: 14,
          }}
        />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 16 }}>
        {filteredEntries.map(([category, skills]) => (
          <div key={category} style={{ border: "1px solid rgba(237,233,224,0.1)", borderRadius: 8, background: "rgba(237,233,224,0.02)", padding: "18px 20px" }}>
            <h3 style={{ margin: 0, fontFamily: "'Instrument Serif', Georgia, serif", fontWeight: 400, fontSize: 24, lineHeight: 1.1 }}>{category}</h3>
            <ul style={{ margin: "14px 0 0", paddingLeft: 18, color: "rgba(237,233,224,0.72)", fontSize: 14, lineHeight: 1.7 }}>
              {skills.map((skill) => <li key={skill}>{skill}</li>)}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}

function HoopsProfileSummary() {
  const [profile, setProfile] = React.useState("market");
  const profiles = {
    market: {
      roi: "+9.75%",
      hit: "63.2%",
      bets: "15,276",
      sharpe: "2.96",
      clv: "+0.213",
      mdd: "4.32u",
    },
    fundamental: {
      roi: "+1.62%",
      hit: "59.4%",
      bets: "20,284",
      sharpe: "2.86",
      clv: "+0.150",
      mdd: "4.89u",
    },
  };
  const metrics = profiles[profile];

  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
        {Object.keys(profiles).map((key) => {
          const active = key === profile;
          return (
            <button
              key={key}
              type="button"
              onClick={() => setProfile(key)}
              style={{
                padding: "8px 12px",
                borderRadius: 999,
                border: `1px solid ${active ? "rgba(110,231,244,0.4)" : "rgba(237,233,224,0.14)"}`,
                background: active ? "rgba(110,231,244,0.08)" : "transparent",
                color: active ? "#6EE7F4" : "rgba(237,233,224,0.72)",
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 10,
                letterSpacing: "0.14em",
                textTransform: "uppercase",
                cursor: "pointer",
              }}
            >
              {key}
            </button>
          );
        })}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(110px, 1fr))", gap: 10 }}>
        {[
          ["roi", metrics.roi],
          ["hit rate", metrics.hit],
          ["bets", metrics.bets],
          ["sharpe", metrics.sharpe],
          ["clv", metrics.clv],
          ["max dd", metrics.mdd],
        ].map(([label, value]) => (
          <div key={label} style={{ padding: "10px 12px", borderRadius: 8, border: "1px solid rgba(237,233,224,0.1)", background: "rgba(237,233,224,0.02)" }}>
            <div style={{ fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 10, color: "rgba(237,233,224,0.45)", letterSpacing: "0.12em", textTransform: "uppercase" }}>{label}</div>
            <div style={{ marginTop: 6, color: "#6EE7F4", fontSize: 18, fontFamily: "'JetBrains Mono', ui-monospace, monospace" }}>{value}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function createSeriesColor(index, alpha = 0.32) {
  const hue = (index * 37) % 360;
  return `hsla(${hue}, 72%, 68%, ${alpha})`;
}

function getSortedChartValues(chart) {
  return (chart?.data?.datasets || [])
    .flatMap((dataset) => (Array.isArray(dataset.data) ? dataset.data : []))
    .map((point) => Number(point?.y))
    .filter((value) => Number.isFinite(value))
    .sort((left, right) => left - right);
}

function getQuantile(sortedValues, percentile) {
  if (!sortedValues.length) return null;
  if (sortedValues.length === 1) return sortedValues[0];

  const position = (sortedValues.length - 1) * percentile;
  const lowerIndex = Math.floor(position);
  const upperIndex = Math.ceil(position);
  const lowerValue = sortedValues[lowerIndex];
  const upperValue = sortedValues[upperIndex];

  if (lowerIndex === upperIndex) return lowerValue;
  return lowerValue + (upperValue - lowerValue) * (position - lowerIndex);
}

function syncHedgeChartScale(chart, anchorValue = 100) {
  if (!chart?.options?.scales?.y) return;

  const sortedValues = getSortedChartValues(chart);
  const yScale = chart.options.scales.y;
  const baseline = Number.isFinite(anchorValue) ? anchorValue : 100;

  if (!sortedValues.length) {
    yScale.min = baseline * 0.97;
    yScale.max = baseline * 1.03;
    return;
  }

  const lowerBound = getQuantile(sortedValues, 0.1);
  const upperBound = getQuantile(sortedValues, 0.9);
  const trimmedSpan = Math.max(upperBound - lowerBound, baseline * 0.04, 4);
  const padding = Math.max(trimmedSpan * 0.14, 1.5);
  const center = (lowerBound + upperBound) / 2;

  yScale.min = center - trimmedSpan / 2 - padding;
  yScale.max = center + trimmedSpan / 2 + padding;
}

function HedgeRLDemo() {
  const canvasRef = React.useRef(null);
  const chartRef = React.useRef(null);
  const sourceRef = React.useRef(null);
  const simulationDataRef = React.useRef([]);

  const [inputs, setInputs] = React.useState({
    nPaths: 50,
    nSteps: 100,
    xi: 0.04,
    hurst: 0.1,
    eta: 1.0,
    rho: -0.7,
    s0: 100,
    riskFree: 0.0,
  });
  const [isRunning, setIsRunning] = React.useState(false);
  const [status, setStatus] = React.useState("idle");
  const [canDownload, setCanDownload] = React.useState(false);

  React.useEffect(() => {
    if (!canvasRef.current || typeof Chart === "undefined") return undefined;

    const chart = new Chart(canvasRef.current, {
      type: "line",
      data: { datasets: [] },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: false,
        parsing: false,
        interaction: { mode: "nearest", intersect: false },
        plugins: {
          legend: { display: false },
          tooltip: { enabled: false },
        },
        scales: {
          x: { grid: { color: "rgba(237,233,224,0.08)" }, ticks: { color: "rgba(237,233,224,0.55)" } },
          y: { grid: { color: "rgba(237,233,224,0.08)" }, ticks: { color: "rgba(237,233,224,0.55)" } },
        },
      },
    });

    syncHedgeChartScale(chart, Number(inputs.s0));

    chartRef.current = chart;
    return () => {
      sourceRef.current?.close();
      chart.destroy();
      chartRef.current = null;
    };
  }, []);

  const updateInput = (key, value) => {
    setInputs((current) => ({ ...current, [key]: value }));
  };

  const startSimulation = () => {
    const nPaths = Math.min(100, Math.max(1, Number(inputs.nPaths) || 50));
    const nSteps = Math.min(504, Math.max(10, Number(inputs.nSteps) || 100));
    const nextInputs = { ...inputs, nPaths, nSteps };
    setInputs(nextInputs);
    setIsRunning(true);
    setCanDownload(false);
    setStatus("streaming");
    simulationDataRef.current = [];

    sourceRef.current?.close();

    const chart = chartRef.current;
    if (chart) {
      chart.data.datasets = Array.from({ length: nPaths }, (_, index) => ({
        data: [],
        borderColor: createSeriesColor(index),
        borderWidth: 1.2,
        pointRadius: 0,
        tension: 0,
      }));
      syncHedgeChartScale(chart, Number(nextInputs.s0));
      chart.update("none");
    }

    const params = new URLSearchParams({
      n: String(nPaths),
      steps: String(nSteps),
      xi: String(nextInputs.xi),
      h: String(nextInputs.hurst),
      eta: String(nextInputs.eta),
      rho: String(nextInputs.rho),
      s0: String(nextInputs.s0),
      r: String(nextInputs.riskFree),
    });

    const source = new EventSource(`/api/rbergomi?${params.toString()}`);
    sourceRef.current = source;

    source.onmessage = ({ data }) => {
      const payload = JSON.parse(data);
      simulationDataRef.current.push(payload);
      if (!chartRef.current) return;
      payload.prices.forEach((price, index) => {
        chartRef.current.data.datasets[index]?.data.push({ x: payload.step, y: price });
      });
      syncHedgeChartScale(chartRef.current, Number(nextInputs.s0));
      chartRef.current.update("none");
    };

    source.onerror = () => {
      setIsRunning(false);
      setStatus("connection lost");
      source.close();
    };

    source.addEventListener("end", () => {
      setIsRunning(false);
      setCanDownload(true);
      setStatus("complete");
      source.close();
    });
  };

  const downloadCsv = () => {
    if (!simulationDataRef.current.length) return;
    const maxPaths = simulationDataRef.current[0].prices.length;
    const header = ["Step", ...Array.from({ length: maxPaths }, (_, index) => `Path_${index + 1}`)].join(",");
    const rows = simulationDataRef.current.map(({ step, prices }) => [step, ...prices].join(","));
    const blob = new Blob([[header, ...rows].join("\n")], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `rbergomi_simulation_${new Date().toISOString().slice(0, 19).replace(/:/g, "-")}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const fieldDefinitions = [
    { label: "paths", key: "nPaths", step: "1", min: 1, max: 100, inputMode: "numeric" },
    { label: "steps", key: "nSteps", step: "1", min: 10, max: 504, inputMode: "numeric" },
    { label: "xi", key: "xi", step: "0.01", min: 0.001, max: 1, inputMode: "decimal" },
    { label: "hurst", key: "hurst", step: "0.01", min: 0.01, max: 0.49, inputMode: "decimal" },
    { label: "eta", key: "eta", step: "0.1", min: 0.1, max: 5, inputMode: "decimal" },
    { label: "rho", key: "rho", step: "0.01", min: -0.99, max: 0.99, inputMode: "decimal" },
    { label: "s0", key: "s0", step: "1", min: 1, max: 1000, inputMode: "numeric" },
    { label: "r", key: "riskFree", step: "0.01", min: -1, max: 1, inputMode: "decimal" },
  ];

  const statusColor = status === "complete"
    ? "#6EE7F4"
    : status === "connection lost"
      ? "#f87171"
      : isRunning
        ? "rgba(110,231,244,0.82)"
        : "rgba(237,233,224,0.48)";

  return (
    <div style={{ marginTop: 16, display: "grid", gap: 16 }}>
      <div style={{
        padding: "16px",
        borderRadius: 12,
        border: "1px solid rgba(237,233,224,0.1)",
        background: "rgba(237,233,224,0.018)",
      }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12 }}>
          {fieldDefinitions.map(({ label, key, step, min, max, inputMode }) => (
            <label key={key} style={{ display: "grid", gap: 6, flex: "1 1 124px", minWidth: 112, maxWidth: 148 }}>
              <span style={{
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 10,
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                color: "rgba(237,233,224,0.5)",
              }}>
                {label}
              </span>
              <input
                type="number"
                step={step}
                min={min}
                max={max}
                inputMode={inputMode}
                value={inputs[key]}
                onChange={(event) => updateInput(key, event.target.value)}
                style={{
                  width: "100%",
                  height: 44,
                  padding: "0 14px",
                  borderRadius: 10,
                  border: "1px solid rgba(237,233,224,0.12)",
                  background: "rgba(237,233,224,0.03)",
                  color: "#EDE9E0",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 14,
                  fontVariantNumeric: "tabular-nums",
                  outline: "none",
                }}
              />
            </label>
          ))}
        </div>

        <div style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          flexWrap: "wrap",
          gap: 12,
          marginTop: 16,
        }}>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <button type="button" onClick={startSimulation} disabled={isRunning} style={{
              minWidth: 176,
              height: 44,
              padding: "0 18px",
              borderRadius: 999,
              border: "none",
              background: "#6EE7F4",
              color: "#0A0A0B",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 11,
              letterSpacing: "0.14em",
              textTransform: "uppercase",
              cursor: isRunning ? "default" : "pointer",
              opacity: isRunning ? 0.6 : 1,
            }}>
              {isRunning ? "Running" : "Run stream"}
            </button>
            <button type="button" onClick={downloadCsv} disabled={!canDownload} style={{
              minWidth: 176,
              height: 44,
              padding: "0 18px",
              borderRadius: 999,
              border: "1px solid rgba(237,233,224,0.14)",
              background: "transparent",
              color: "#EDE9E0",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 11,
              letterSpacing: "0.14em",
              textTransform: "uppercase",
              cursor: canDownload ? "pointer" : "default",
              opacity: canDownload ? 1 : 0.45,
            }}>
              Download csv
            </button>
          </div>

          <span style={{
            padding: "8px 12px",
            borderRadius: 999,
            border: "1px solid rgba(237,233,224,0.1)",
            background: "rgba(237,233,224,0.02)",
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 10,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            color: statusColor,
          }}>
            {status}
          </span>
        </div>
      </div>

      <div style={{ height: 280, borderRadius: 10, border: "1px solid rgba(237,233,224,0.1)", background: "rgba(4,4,5,0.6)", padding: 10 }}>
        <canvas ref={canvasRef} />
      </div>
    </div>
  );
}

function normalPdf(x) {
  return Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);
}

function normalCdf(x) {
  const sign = x < 0 ? -1 : 1;
  const a1 = 0.254829592;
  const a2 = -0.284496736;
  const a3 = 1.421413741;
  const a4 = -1.453152027;
  const a5 = 1.061405429;
  const p = 0.3275911;
  const abs = Math.abs(x) / Math.SQRT2;
  const t = 1 / (1 + p * abs);
  const y = 1 - (((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t) * Math.exp(-abs * abs);
  return 0.5 * (1 + sign * y);
}

function blackScholesMetrics({ S, K, T, r, q, sigma, type }) {
  if (!(S > 0) || !(K > 0) || !(T >= 0) || !(sigma >= 0)) return null;
  if (T === 0 || sigma === 0) {
    const intrinsicCall = Math.max(S - K, 0);
    const intrinsicPut = Math.max(K - S, 0);
    const price = type === "put" ? intrinsicPut : intrinsicCall;
    const delta = type === "put" ? (S < K ? -1 : 0) : (S > K ? 1 : 0);
    return { price, delta, gamma: 0, vega: 0, theta: 0, rho: 0 };
  }

  const sqrtT = Math.sqrt(T);
  const sigSqrtT = sigma * sqrtT;
  const d1 = (Math.log(S / K) + (r - q + 0.5 * sigma * sigma) * T) / sigSqrtT;
  const d2 = d1 - sigSqrtT;
  const discR = Math.exp(-r * T);
  const discQ = Math.exp(-q * T);
  const Nd1 = normalCdf(d1);
  const Nd2 = normalCdf(d2);
  const Nmd1 = normalCdf(-d1);
  const Nmd2 = normalCdf(-d2);
  const pdfD1 = normalPdf(d1);
  const gamma = (discQ * pdfD1) / (S * sigSqrtT);
  const vega = S * discQ * pdfD1 * sqrtT;

  if (type === "put") {
    return {
      price: K * discR * Nmd2 - S * discQ * Nmd1,
      delta: discQ * (Nd1 - 1),
      gamma,
      vega,
      theta: (-S * discQ * pdfD1 * sigma) / (2 * sqrtT) + r * K * discR * Nmd2 - q * S * discQ * Nmd1,
      rho: -K * T * discR * Nmd2,
    };
  }

  return {
    price: S * discQ * Nd1 - K * discR * Nd2,
    delta: discQ * Nd1,
    gamma,
    vega,
    theta: (-S * discQ * pdfD1 * sigma) / (2 * sqrtT) - r * K * discR * Nd2 + q * S * discQ * Nd1,
    rho: K * T * discR * Nd2,
  };
}

function formatMetric(value) {
  if (!Number.isFinite(value)) return "-";
  const abs = Math.abs(value);
  if (abs >= 1000) return value.toFixed(0);
  if (abs >= 100) return value.toFixed(2);
  if (abs >= 10) return value.toFixed(3);
  return value.toFixed(4);
}

function BlackScholesPlayground() {
  const canvasRef = React.useRef(null);
  const chartRef = React.useRef(null);
  const [inputs, setInputs] = React.useState({
    S: 100,
    K: 100,
    T: 1,
    sigma: 20,
    r: 5,
    q: 0,
    type: "call",
  });

  const metrics = React.useMemo(() => blackScholesMetrics({
    S: Number(inputs.S),
    K: Number(inputs.K),
    T: Number(inputs.T),
    sigma: Number(inputs.sigma) / 100,
    r: Number(inputs.r) / 100,
    q: Number(inputs.q) / 100,
    type: inputs.type,
  }), [inputs]);

  React.useEffect(() => {
    if (!canvasRef.current || typeof Chart === "undefined") return undefined;
    const chart = new Chart(canvasRef.current, {
      type: "line",
      data: { datasets: [{ data: [], borderColor: "#6EE7F4", borderWidth: 2, pointRadius: 0, tension: 0.18 }] },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: false,
        plugins: { legend: { display: false } },
        scales: {
          x: { grid: { color: "rgba(237,233,224,0.08)" }, ticks: { color: "rgba(237,233,224,0.55)" } },
          y: { grid: { color: "rgba(237,233,224,0.08)" }, ticks: { color: "rgba(237,233,224,0.55)" } },
        },
      },
    });
    chartRef.current = chart;
    return () => chart.destroy();
  }, []);

  React.useEffect(() => {
    if (!chartRef.current) return;
    const center = Number(inputs.S);
    const prices = [];
    for (let spot = Math.max(1, center * 0.5); spot <= center * 1.5; spot += Math.max(1, center * 0.025)) {
      const pointMetrics = blackScholesMetrics({
        S: spot,
        K: Number(inputs.K),
        T: Number(inputs.T),
        sigma: Number(inputs.sigma) / 100,
        r: Number(inputs.r) / 100,
        q: Number(inputs.q) / 100,
        type: inputs.type,
      });
      if (pointMetrics) prices.push({ x: spot, y: pointMetrics.price });
    }
    chartRef.current.data.datasets[0].data = prices;
    chartRef.current.update("none");
  }, [inputs]);

  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(104px, 1fr))", gap: 10 }}>
        {[
          ["spot", "S"],
          ["strike", "K"],
          ["tenor", "T"],
          ["vol %", "sigma"],
          ["rate %", "r"],
          ["div %", "q"],
        ].map(([label, key]) => (
          <label key={key} style={{ display: "grid", gap: 6 }}>
            <span style={{ fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(237,233,224,0.5)" }}>{label}</span>
            <input
              type="number"
              step="0.01"
              value={inputs[key]}
              onChange={(event) => setInputs((current) => ({ ...current, [key]: event.target.value }))}
              style={{ padding: "9px 10px", borderRadius: 8, border: "1px solid rgba(237,233,224,0.12)", background: "rgba(237,233,224,0.03)", color: "#EDE9E0" }}
            />
          </label>
        ))}
        <label style={{ display: "grid", gap: 6 }}>
          <span style={{ fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(237,233,224,0.5)" }}>type</span>
          <select
            value={inputs.type}
            onChange={(event) => setInputs((current) => ({ ...current, type: event.target.value }))}
            style={{ padding: "9px 10px", borderRadius: 8, border: "1px solid rgba(237,233,224,0.12)", background: "rgba(237,233,224,0.03)", color: "#EDE9E0" }}
          >
            <option value="call">Call</option>
            <option value="put">Put</option>
          </select>
        </label>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(110px, 1fr))", gap: 10, marginTop: 16 }}>
        {[
          ["price", metrics?.price],
          ["delta", metrics?.delta],
          ["gamma", metrics?.gamma],
          ["vega", metrics?.vega],
          ["theta", metrics?.theta],
          ["rho", metrics?.rho],
        ].map(([label, value]) => (
          <div key={label} style={{ padding: "10px 12px", borderRadius: 8, border: "1px solid rgba(237,233,224,0.1)", background: "rgba(237,233,224,0.02)" }}>
            <div style={{ fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 10, color: "rgba(237,233,224,0.45)", letterSpacing: "0.12em", textTransform: "uppercase" }}>{label}</div>
            <div style={{ marginTop: 6, color: "#6EE7F4", fontSize: 18, fontFamily: "'JetBrains Mono', ui-monospace, monospace" }}>{formatMetric(value)}</div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 16, height: 240, borderRadius: 10, border: "1px solid rgba(237,233,224,0.1)", background: "rgba(4,4,5,0.6)", padding: 10 }}>
        <canvas ref={canvasRef} />
      </div>
    </div>
  );
}

Object.assign(window, {
  DEFAULT_TOP_SKILLS,
  DEFAULT_SKILLS_GRAPH,
  DEFAULT_FULL_SKILLS_LIST,
  useCompanyRouteConfig,
  CompanyFitModal,
  SkillsExperienceMap,
  SkillsCatalog,
  HoopsProfileSummary,
  HedgeRLDemo,
  BlackScholesPlayground,
});
