/* global window, React */

function highlightJSON(code) {
  return code
    .replace(/("(?:[^"\\]|\\.)*")(\s*:)/g, '<span class="tok-key">$1</span>$2')
    .replace(/:\s*("(?:[^"\\]|\\.)*")/g, ': <span class="tok-str">$1</span>')
    .replace(/(:\s*)(-?\d+\.?\d*)/g, '$1<span class="tok-num">$2</span>')
    .replace(/(:\s*)(true|false|null)/g, '$1<span class="tok-kw">$2</span>');
}

function ResponsePane({ response }) {
  const copy = () => { try { navigator.clipboard.writeText(response); } catch (e) {} };
  return React.createElement("div", { style: { padding: "10px 12px 0" } },
    React.createElement("div", { className: "lang-tabs" },
      React.createElement("button", { className: "lang-tab", "aria-selected": true }, "Response"),
      React.createElement("button", { className: "icon-btn", onClick: copy, title: "Copy",
        style: { marginLeft: "auto", width: 24, height: 24 } },
        React.createElement(window.Icons.Copy, { size: 12 }))
    ),
    React.createElement("pre", {
      className: "code-block scroll",
      style: { maxHeight: 260 },
      dangerouslySetInnerHTML: { __html: highlightJSON(response) },
    })
  );
}

function ChipRow({ items, color }) {
  return React.createElement("div", { style: { display: "flex", flexWrap: "wrap", gap: 4 } },
    items.map(t => React.createElement("span", {
      key: t,
      style: {
        fontSize: 10.5, padding: "3px 8px", borderRadius: 999,
        color: color || "var(--text-2)",
        background: color ? `color-mix(in oklab, ${color} 12%, transparent)` : "var(--glass-ground)",
        border: color ? `1px solid color-mix(in oklab, ${color} 30%, transparent)` : "1px solid var(--hairline)",
        fontWeight: 500,
      }
    }, t))
  );
}

// ── Section — reusable accordion shell (RAIL_REDESIGN.md §5) ─
function Section({ title, count, defaultOpen = false, children }) {
  const { useState } = React;
  const [open, setOpen] = useState(defaultOpen);
  return React.createElement("div", {
    className: "acc-section", "data-open": open ? "true" : "false",
  },
    React.createElement("button", {
      type: "button",
      className: "acc-header",
      "aria-expanded": open ? "true" : "false",
      onClick: () => setOpen(!open),
    },
      React.createElement("svg", { className: "acc-caret", viewBox: "0 0 10 10" },
        React.createElement("path", { d: "M2 3 L5 7 L8 3", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" })
      ),
      React.createElement("span", { className: "acc-title" }, title),
      count != null && React.createElement("span", { className: "acc-count" }, count)
    ),
    React.createElement("div", { className: "acc-body" },
      React.createElement("div", { className: "acc-body-inner" }, children)
    )
  );
}

// ── KindChip — small pill used in inspector rows ─────────────
function KindChip({ kindId }) {
  const { ENTITY_KINDS, NODES } = window.CIQ;
  const node = NODES.find(n => n.id === kindId);
  const dom = node && ENTITY_KINDS[node.kind];
  const color = dom ? dom.color : "var(--text-3)";
  return React.createElement("span", {
    className: "kind-chip",
    style: {
      color,
      background: `color-mix(in oklab, ${color} 14%, transparent)`,
      borderColor: `color-mix(in oklab, ${color} 32%, transparent)`,
    },
  }, node ? node.name : kindId);
}

// ── EntityInspector — Phase 4 step 5 (INSPECTOR_SCHEMA.md) ───
function EntityInspector({ node, onSelectNode, onSelectShape, onSelectQ, selectedRouteShape, onSelectEndpoint }) {
  const { ENTITY_KINDS, QUESTIONS, ENDPOINTS } = window.CIQ;
  const routes = window.CIQ_routes;
  const k = ENTITY_KINDS[node.kind];
  // Fields section intentionally omitted — listing the per-kind field
  // schema gave away too much ontology design (the literal database
  // column shapes a competitor could lift). Buyers see the existence
  // of structured data via Sources + Used-by-endpoints + Neighbors,
  // not the schema itself. License first, then access.

  // Length-1 grouped by tier
  const neighbors = routes.neighbors(node.id);
  const tiers = {
    direct: neighbors.filter(n => n.type === "direct"),
    inferred: neighbors.filter(n => n.type === "inferred"),
    predicted: neighbors.filter(n => n.type === "predicted"),
  };

  // Length 2 + 3, grouped by family
  const l2 = routes.length2Shapes(node.id);
  const l3 = routes.length3Shapes(node.id);
  const l2Groups = routes.groupShapesByFamily(l2);
  const l3Groups = routes.groupShapesByFamily(l3);

  // Appears in — curated questions touching this kind
  const appearsIn = routes.questionsForKind(node.id);
  // Endpoints that read this kind — the modularity sell.
  const allEndpointsForNode = (ENDPOINTS || [])
    .filter(ep => Array.isArray(ep.reads) && ep.reads.includes(node.id));
  const [showAllEndpoints, setShowAllEndpoints] = React.useState(false);
  const endpointsForNode = showAllEndpoints
    ? allEndpointsForNode
    : allEndpointsForNode.slice(0, 3);
  const hiddenEndpointCount = allEndpointsForNode.length - endpointsForNode.length;
  const MODULE_COLORS = { PartnerIQ:"#a78bfa", CompeteIQ:"#f59e0b", WhiteSpaceIQ:"#58efe0" };

  return React.createElement("div", { className: "scroll", style: { flex: 1, minHeight: 0 } },
    // Section 1 — Header. Just the kind chip + the name. No counts
    // (graph is ever-changing — counts mislead and need maintenance).
    // No sources row (revealed too much; a competitor could lift the
    // exact source database list).
    React.createElement("div", { style: { padding: "14px 14px 14px", borderBottom: "1px solid var(--hairline)" } },
      React.createElement("div", { className: "entity-kind", style: {
        display: "inline-block",
        color: k.color,
        background: `color-mix(in oklab, ${k.color} 15%, transparent)`,
        borderColor: `color-mix(in oklab, ${k.color} 35%, transparent)`,
        fontSize: 9.5,
        padding: "2px 8px",
      }}, k.label),
      React.createElement("h1", {
        style: {
          fontFamily: "var(--font-display)",
          fontSize: 18, fontWeight: 600,
          color: "var(--text-1)",
          margin: "8px 0 0",
          lineHeight: 1.2,
        }
      }, node.name)
    ),

    // Section 2 — Used by these endpoints (the modularity sell, promoted)
    // Note: a Fields section was previously here showing the per-kind
    // field schema (id, name, modality, phase, …). Removed deliberately —
    // it leaked ontology design that should stay behind licensing.
    allEndpointsForNode.length > 0 && React.createElement(Section, {
      title: "Used by these endpoints",
      count: allEndpointsForNode.length,
      defaultOpen: true,
    },
      React.createElement("div", {
        style: { fontSize: 11, color: "var(--text-3)", lineHeight: 1.5, marginBottom: 10, padding: "0 2px" },
      }, "Endpoints that read this kind. Compose your own by mixing schema nodes and edges."),
      React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
        endpointsForNode.map(ep => {
          const modColor = MODULE_COLORS[ep.module] || "var(--text-3)";
          return React.createElement("button", {
            key: ep.id,
            type: "button",
            onClick: () => onSelectEndpoint && onSelectEndpoint(ep),
            style: {
              textAlign: "left",
              padding: "9px 11px",
              borderRadius: 8,
              background: "transparent",
              border: "1px solid var(--hairline)",
              cursor: "pointer",
              transition: "background 120ms, border-color 120ms",
              display: "flex",
              flexDirection: "column",
              gap: 5,
            },
          },
            React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6 } },
              React.createElement("span", { className: `api-method ${ep.method.toLowerCase()}` }, ep.method),
              React.createElement("span", { className: "api-endpoint", style: { fontSize: 11.5 } }, ep.path),
              React.createElement("span", {
                style: {
                  marginLeft: "auto",
                  fontSize: 9.5, padding: "1px 7px", borderRadius: 999,
                  color: modColor,
                  background: `color-mix(in oklab, ${modColor} 14%, transparent)`,
                  border: `1px solid color-mix(in oklab, ${modColor} 30%, transparent)`,
                  fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em",
                },
              }, ep.module)
            ),
            React.createElement("div", {
              style: { fontSize: 11.5, color: "var(--text-2)", lineHeight: 1.45 },
            }, ep.summary)
          );
        }),
        // Show all N → expansion when there are more endpoints than top-3
        hiddenEndpointCount > 0 && !showAllEndpoints && React.createElement("button", {
          type: "button",
          onClick: (ev) => { ev.stopPropagation(); setShowAllEndpoints(true); },
          style: {
            marginTop: 6,
            padding: "7px 10px",
            fontSize: 11,
            color: "var(--accent)",
            background: "transparent",
            border: "1px dashed var(--hairline-strong)",
            borderRadius: 8,
            cursor: "pointer",
            fontWeight: 500,
            textAlign: "center",
            width: "100%",
          },
        }, `Show all ${allEndpointsForNode.length} endpoints →`),
        showAllEndpoints && allEndpointsForNode.length > 3 && React.createElement("button", {
          type: "button",
          onClick: (ev) => { ev.stopPropagation(); setShowAllEndpoints(false); },
          style: {
            marginTop: 6,
            padding: "5px 10px",
            fontSize: 10.5,
            color: "var(--text-3)",
            background: "transparent",
            border: "none",
            cursor: "pointer",
            textAlign: "center",
            width: "100%",
          },
        }, "Show less")
      )
    ),

    // Section 4 — Appears in these questions (curated traversals)
    appearsIn.length > 0 && React.createElement(Section, { title: "Appears in these questions", count: appearsIn.length, defaultOpen: true },
      appearsIn.map(q => {
        const path = q.path || q.subgraphNodes || [];
        const fam = window.CIQ_routes.family(path);
        const famColor = window.CIQ_routes.familyColor(fam);
        const modColor = MODULE_COLORS[q.module] || "var(--text-3)";
        return React.createElement("div", {
          key: q.id,
          className: "insp-shape",
          onClick: () => onSelectQ && onSelectQ(q),
        },
          React.createElement("div", { style: { fontSize: 11.5, color: "var(--text-1)", lineHeight: 1.4, marginBottom: 4 } }, q.q),
          React.createElement("div", { className: "meta-row" },
            React.createElement("span", {
              style: {
                fontSize: 9.5, padding: "1px 7px", borderRadius: 999,
                color: modColor,
                background: `color-mix(in oklab, ${modColor} 14%, transparent)`,
                border: `1px solid color-mix(in oklab, ${modColor} 30%, transparent)`,
                fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em",
              }
            }, q.module),
            React.createElement("span", { style: { fontSize: 10, color: "var(--text-3)" } }, q.group),
            React.createElement("span", {
              style: {
                marginLeft: "auto",
                fontSize: 9.5, padding: "1px 6px", borderRadius: 4,
                color: famColor,
                background: `color-mix(in oklab, ${famColor} 12%, transparent)`,
                border: `1px solid color-mix(in oklab, ${famColor} 28%, transparent)`,
                fontWeight: 600, letterSpacing: "0.04em",
              }
            }, fam)
          )
        );
      })
    ),

    // Section 5 — Direct Neighbors (connectivity detail, demoted from slot 3)
    neighbors.length > 0 && React.createElement(Section, { title: "Direct neighbors", count: neighbors.length, defaultOpen: false },
      ["direct","inferred","predicted"].map(tier => {
        const items = tiers[tier];
        if (!items.length) return null;
        return React.createElement("div", { key: tier, className: "insp-tier-group" },
          React.createElement("div", { className: "insp-tier-header" },
            React.createElement("span", { className: "insp-tier-dot", "data-tier": tier }),
            tier,
            React.createElement("span", { className: "insp-tier-count" }, items.length)
          ),
          items.map((n, i) => React.createElement("div", {
            key: i,
            className: "insp-row",
            onClick: () => onSelectNode && onSelectNode(n.neighbor),
          },
            React.createElement("span", { className: "dir" }, n.dir === "out" ? "→" : "←"),
            React.createElement(KindChip, { kindId: n.neighbor }),
            React.createElement("span", { className: "label-mono" }, n.label),
            React.createElement("span", { className: "conf-num" }, n.weight.toFixed(2))
          ))
        );
      })
    ),

    // Section 6 — Routes by length (engineer-tier traversal detail)
    (l2.length > 0 || l3.length > 0) && React.createElement(Section, {
      title: "Routes by length",
      count: l2.length + l3.length,
    },
      l2.length > 0 && React.createElement(Section, { title: "Length 2", count: l2.length },
        React.createElement(ShapeFamilyList, {
          groups: l2Groups, length: 2,
          onSelectShape, selectedRouteShape,
        })
      ),
      l3.length > 0 && React.createElement(Section, { title: "Length 3", count: l3.length },
        React.createElement(ShapeFamilyList, {
          groups: l3Groups, length: 3,
          onSelectShape, selectedRouteShape,
        })
      )
    )
  );
}

// ── ShapeFamilyList — renders L2/L3 shapes grouped by family ──
function ShapeFamilyList({ groups, length, onSelectShape, selectedRouteShape }) {
  const { useState } = React;
  // expanded family ids — one per family, scoped to this length
  const [expanded, setExpanded] = useState({});
  const TOP_N = 12; // INSPECTOR_SCHEMA.md §6.4 — per family per length

  return React.createElement(React.Fragment, null,
    groups.map(g => {
      const showAll = expanded[g.family];
      const visible = showAll ? g.shapes : g.shapes.slice(0, TOP_N);
      const hidden = g.shapes.length - visible.length;
      return React.createElement("div", { key: g.family, className: "insp-family-group" },
        React.createElement("div", { className: "insp-family-header" },
          React.createElement("span", { className: "insp-family-swatch", style: { background: g.color } }),
          g.family,
          React.createElement("span", { className: "insp-family-count" }, g.shapes.length)
        ),
        visible.map((s, i) => {
          const sel = selectedRouteShape &&
                      selectedRouteShape.length === length &&
                      selectedRouteShape.path.join(">") === s.path.join(">");
          return React.createElement("div", {
            key: i,
            className: "insp-shape",
            "data-selected": sel ? "true" : "false",
            onClick: () => onSelectShape && onSelectShape({ length, path: s.path, family: s.family }),
          },
            React.createElement("div", { className: "path-row" },
              s.path.map((p, j) => React.createElement(React.Fragment, { key: j },
                React.createElement(KindChip, { kindId: p }),
                j < s.path.length - 1 && React.createElement("span", { className: "path-arrow" }, "→")
              ))
            ),
            React.createElement("div", { className: "meta-row" },
              React.createElement("span", { className: "insp-tier-dot", "data-tier": s.weakestTier, style: { display: "inline-block" } }),
              React.createElement("span", null, s.weakestTier),
              React.createElement("span", { style: { marginLeft: 4 } }, "·"),
              React.createElement("span", null, "count ", s.count),
              React.createElement("span", { style: { marginLeft: "auto" } },
                React.createElement("span", { className: "conf-num" }, s.avgConf.toFixed(2))
              )
            )
          );
        }),
        hidden > 0 && React.createElement("button", {
          type: "button",
          className: "insp-show-all",
          onClick: (ev) => { ev.stopPropagation(); setExpanded({ ...expanded, [g.family]: true }); },
        }, `Show all ${g.shapes.length} →`)
      );
    })
  );
}

function RequestPane({ requestBody }) {
  const copy = () => { try { navigator.clipboard.writeText(requestBody); } catch (e) {} };
  return React.createElement("div", { style: { padding: "10px 12px 0" } },
    React.createElement("div", { className: "lang-tabs" },
      React.createElement("button", { className: "lang-tab", "aria-selected": true }, "Request body"),
      React.createElement("button", { className: "icon-btn", onClick: copy, title: "Copy",
        style: { marginLeft: "auto", width: 24, height: 24 } },
        React.createElement(window.Icons.Copy, { size: 12 }))
    ),
    React.createElement("pre", {
      className: "code-block scroll",
      style: { maxHeight: 220 },
      dangerouslySetInnerHTML: { __html: highlightJSON(requestBody) },
    })
  );
}

function EndpointInspector({ endpoint, onSelectQ, onApiAccess }) {
  const { ENTITY_KINDS, NODES, QUESTIONS, MODULE_INFO } = window.CIQ;
  const MODULE_COLORS = { PartnerIQ:"#a78bfa", CompeteIQ:"#f59e0b", WhiteSpaceIQ:"#58efe0" };
  const moduleColor = MODULE_COLORS[endpoint.module];
  const moduleInfo = MODULE_INFO && MODULE_INFO[endpoint.module];
  const moduleTooltip = moduleInfo ? `${moduleInfo.tagline} ${moduleInfo.description}` : endpoint.module;
  const poweredQuestions = (endpoint.questionIds || [])
    .map(qid => QUESTIONS.find(x => x.id === qid))
    .filter(Boolean);

  return React.createElement("div", { className: "scroll", style: { flex: 1, minHeight: 0, display: "flex", flexDirection: "column" } },
    React.createElement("div", { className: "entity-hero" },
      React.createElement("div", { className: "entity-kind", title: moduleTooltip, style: {
        color: moduleColor,
        background: `color-mix(in oklab, ${moduleColor} 15%, transparent)`,
        borderColor: `color-mix(in oklab, ${moduleColor} 35%, transparent)`,
        cursor: "help",
      }}, endpoint.module),
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginTop: 8 } },
        React.createElement("span", { className: `api-method ${endpoint.method.toLowerCase()}` }, endpoint.method),
        React.createElement("span", { className: "api-endpoint", style: { fontSize: 13.5 } }, endpoint.path)
      ),
      React.createElement("h1", { className: "entity-name", style: { fontSize: 16, marginTop: 8 } }, endpoint.summary),
      endpoint.description && React.createElement("p", { className: "entity-desc" }, endpoint.description),
      // Spec-preview banner — makes it unambiguous this isn't a try-it surface.
      // 22% bg (bumped from 14%) so the banner reads as a deliberate
      // surface block on light cream canvas instead of fading into it.
      React.createElement("div", {
        style: {
          marginTop: 12,
          padding: "8px 10px",
          borderRadius: 8,
          background: "color-mix(in oklab, var(--text-3) 22%, transparent)",
          border: "1px solid var(--hairline-strong)",
          display: "flex",
          alignItems: "flex-start",
          gap: 8,
          fontSize: 11,
          color: "var(--text-2)",
          lineHeight: 1.5,
        },
      },
        React.createElement("span", {
          style: {
            fontSize: 9, fontWeight: 700, letterSpacing: "0.08em",
            padding: "2px 6px", borderRadius: 4,
            color: moduleColor,
            background: `color-mix(in oklab, ${moduleColor} 18%, transparent)`,
            border: `1px solid color-mix(in oklab, ${moduleColor} 35%, transparent)`,
            textTransform: "uppercase", flexShrink: 0,
          },
        }, "Spec preview"),
        React.createElement("span", null, "Sample request and response shown below. API access is gated — request credentials to run live queries.")
      )
    ),

    endpoint.reads && endpoint.reads.length > 0 && React.createElement("div", { className: "rail-section" },
      React.createElement("div", { className: "rail-section-title" }, "Reads node types",
        React.createElement("span", { className: "count" }, endpoint.reads.length)),
      React.createElement(ChipRow, {
        items: endpoint.reads.map(id => {
          const n = NODES.find(x => x.id === id);
          return n ? n.name : id;
        }),
      })
    ),

    endpoint.traverses && endpoint.traverses.length > 0 && React.createElement("div", { className: "rail-section" },
      React.createElement("div", { className: "rail-section-title" }, "Traverses edges",
        React.createElement("span", { className: "count" }, endpoint.traverses.length)),
      React.createElement(ChipRow, { items: endpoint.traverses, color: "var(--accent)" })
    ),

    endpoint.params && endpoint.params.length > 0 && React.createElement("div", { className: "rail-section" },
      React.createElement("div", { className: "rail-section-title" }, "Parameters",
        React.createElement("span", { className: "count" }, endpoint.params.length)),
      React.createElement("dl", { className: "kv-list" },
        endpoint.params.flatMap(p => [
          React.createElement("dt", { key: p.name + "k" }, p.name,
            React.createElement("div", { style: { fontSize: 9.5, color: "var(--text-4)", textTransform: "uppercase", letterSpacing: "0.06em", marginTop: 2 } }, p.type)),
          React.createElement("dd", { key: p.name + "v",
            style: { fontFamily: "var(--font-sans)", fontSize: 11.5, color: "var(--text-2)", lineHeight: 1.45 } }, p.desc),
        ])
      )
    ),

    endpoint.requestBody && React.createElement(RequestPane, { requestBody: endpoint.requestBody }),

    endpoint.response && React.createElement(ResponsePane, { response: endpoint.response }),

    poweredQuestions.length > 0 && React.createElement("div", { className: "rail-section" },
      React.createElement("div", { className: "rail-section-title" }, "Powers these questions",
        React.createElement("span", { className: "count" }, poweredQuestions.length)),
      React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
        poweredQuestions.map(q => React.createElement("button", {
          key: q.id,
          onClick: () => onSelectQ && onSelectQ(q),
          style: {
            textAlign: "left",
            padding: "8px 10px",
            borderRadius: 8,
            background: "transparent",
            border: "1px solid var(--hairline)",
            cursor: "pointer",
            fontSize: 11.5,
            color: "var(--text-2)",
            lineHeight: 1.45,
          },
        },
          React.createElement("div", { style: { fontSize: 9.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4, fontWeight: 600 } }, q.group),
          q.q
        ))
      )
    ),

    // ── Get API access CTA ─────────────────────────────────
    React.createElement("div", {
      style: {
        marginTop: "auto",
        padding: "14px 14px 16px",
        borderTop: "1px solid var(--hairline)",
        background: `linear-gradient(180deg, transparent, color-mix(in oklab, ${moduleColor} 6%, transparent))`,
      },
    },
      React.createElement("div", { style: { fontSize: 11.5, color: "var(--text-2)", marginBottom: 10, lineHeight: 1.45 } },
        "Run this endpoint against the live graph."),
      React.createElement("button", {
        type: "button",
        onClick: () => onApiAccess && onApiAccess(endpoint),
        style: {
          width: "100%",
          padding: "10px 14px",
          borderRadius: 10,
          background: moduleColor,
          color: "#0a0a0a",
          fontWeight: 600,
          fontSize: 12,
          letterSpacing: "0.01em",
          border: "1px solid " + moduleColor,
          boxShadow: `0 6px 18px color-mix(in oklab, ${moduleColor} 28%, transparent), inset 0 1px 0 rgba(255,255,255,0.3)`,
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 8,
        },
      }, "Get API access →")
    )
  );
}

function QuestionInspector({ question, onSelectEndpoint, onApiAccess }) {
  const { ENDPOINTS, NODES } = window.CIQ;
  const ep = ENDPOINTS.find(e => e.id === question.apiId);
  const MODULE_COLORS = { PartnerIQ:"#a78bfa", CompeteIQ:"#f59e0b", WhiteSpaceIQ:"#58efe0" };
  const moduleColor = MODULE_COLORS[question.module] || "var(--text-3)";
  const bodyJson = question.apiBody ? JSON.stringify(question.apiBody, null, 2) : null;

  const subNodes = question.subgraphNodes || question.path || [];
  const subEdges = question.subgraphEdges || [];

  return React.createElement("div", { className: "scroll", style: { flex: 1, minHeight: 0, display: "flex", flexDirection: "column" } },
    // Header — module chip + question text + group label
    React.createElement("div", { style: { padding: "12px 14px 14px", borderBottom: "1px solid var(--hairline)" } },
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 10 } },
        React.createElement("div", { className: "entity-kind", style: {
          display: "inline-block",
          color: moduleColor,
          background: `color-mix(in oklab, ${moduleColor} 15%, transparent)`,
          borderColor: `color-mix(in oklab, ${moduleColor} 35%, transparent)`,
          fontSize: 9.5,
          padding: "2px 8px",
        }}, question.module),
        React.createElement("span", {
          style: { fontSize: 9.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 },
        }, question.group)
      ),
      React.createElement("div", { style: { fontSize: 14, lineHeight: 1.4, color: "var(--text-1)", fontWeight: 500 } }, question.q)
    ),

    // Powers — promoted to top, this is the conversion thread
    ep && React.createElement(Section, { title: "Powered by", count: 1, defaultOpen: true },
      React.createElement("button", {
        type: "button",
        onClick: () => onSelectEndpoint && onSelectEndpoint(ep),
        style: {
          textAlign: "left",
          padding: "9px 11px",
          borderRadius: 8,
          background: "transparent",
          border: "1px solid var(--hairline)",
          cursor: "pointer",
          width: "100%",
          display: "flex",
          flexDirection: "column",
          gap: 5,
        },
      },
        React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6 } },
          React.createElement("span", { className: `api-method ${ep.method.toLowerCase()}` }, ep.method),
          React.createElement("span", { className: "api-endpoint", style: { fontSize: 11.5 } }, ep.path),
          React.createElement("span", {
            style: {
              marginLeft: "auto",
              fontSize: 9.5, padding: "1px 7px", borderRadius: 999,
              color: moduleColor,
              background: `color-mix(in oklab, ${moduleColor} 14%, transparent)`,
              border: `1px solid color-mix(in oklab, ${moduleColor} 30%, transparent)`,
              fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em",
            },
          }, question.module)
        ),
        React.createElement("div", {
          style: { fontSize: 11.5, color: "var(--text-2)", lineHeight: 1.45 },
        }, ep.summary)
      )
    ),
    // Subgraph — entity + edge breakdown for the curated path
    subNodes.length > 0 && React.createElement(Section, { title: "Subgraph", count: subNodes.length, defaultOpen: true },
      React.createElement("div", { style: { fontSize: 10, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 } }, "Nodes"),
      React.createElement("div", { style: { display: "flex", flexWrap: "wrap", gap: 4, marginBottom: subEdges.length ? 12 : 0 } },
        subNodes.map(nid => {
          const n = NODES.find(x => x.id === nid);
          const c = n ? n.color : "var(--text-3)";
          return React.createElement("span", { key: nid, style: {
            fontSize: 10.5, padding: "3px 8px", borderRadius: 999,
            color: c, background: `color-mix(in oklab, ${c} 12%, transparent)`,
            border: `1px solid color-mix(in oklab, ${c} 30%, transparent)`,
            fontWeight: 500,
          }}, n ? n.name : nid);
        })
      ),
      subEdges.length > 0 && React.createElement(React.Fragment, null,
        React.createElement("div", { style: { fontSize: 10, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 } }, "Edges"),
        React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 5 } },
          subEdges.map((e, i) => {
            const s = NODES.find(n => n.id === e.s);
            const t = NODES.find(n => n.id === e.t);
            return React.createElement("div", { key: i, style: {
              display: "flex", alignItems: "center", gap: 6,
              fontSize: 11, fontFamily: "var(--font-mono)",
              padding: "4px 8px",
              background: e.role === "anchor" ? "var(--accent-tint)" : "var(--glass-ground)",
              border: "1px solid var(--hairline)",
              borderRadius: 6,
            } },
              React.createElement("span", { style: {
                fontSize: 8.5, padding: "1px 5px", borderRadius: 3,
                color: e.role === "anchor" ? "var(--accent-bright)" : "var(--text-3)",
                background: e.role === "anchor" ? "color-mix(in oklab, var(--accent-bright) 18%, transparent)" : "transparent",
                border: e.role === "anchor" ? "none" : "1px solid var(--hairline)",
                textTransform: "uppercase", letterSpacing: "0.04em", fontWeight: 600,
                fontFamily: "var(--font-sans)",
              }}, e.role || "edge"),
              React.createElement("span", { style: { color: "var(--text-2)" } }, s ? s.name : e.s),
              React.createElement("span", { style: { color: "var(--text-4)" } }, "—"),
              React.createElement("span", { style: { color: "var(--accent)" } }, e.label),
              React.createElement("span", { style: { color: "var(--text-4)" } }, "→"),
              React.createElement("span", { style: { color: "var(--text-2)" } }, t ? t.name : e.t)
            );
          })
        )
      )
    ),

    // Sample request body — collapsed; engineer affordance, not buyer-first
    bodyJson && React.createElement(Section, { title: "Sample request body", defaultOpen: false },
      React.createElement("pre", {
        className: "code-block scroll",
        style: { maxHeight: 220, margin: 0 },
        dangerouslySetInnerHTML: { __html: highlightJSON(bodyJson) },
      })
    ),

    // Cypher — collapsed; only opens for engineers who want to see the
    // raw traversal. Default-closed so a buyer doesn't see DB syntax.
    question.cypher && React.createElement(Section, { title: "Cypher query", defaultOpen: false },
      React.createElement("pre", {
        className: "code-block scroll",
        style: { maxHeight: 320, whiteSpace: "pre", margin: 0 },
      }, question.cypher)
    ),

    // ── Get API access CTA — match EndpointInspector pattern ──
    React.createElement("div", {
      style: {
        marginTop: "auto",
        padding: "14px 14px 16px",
        borderTop: "1px solid var(--hairline)",
        background: `linear-gradient(180deg, transparent, color-mix(in oklab, ${moduleColor} 6%, transparent))`,
      },
    },
      React.createElement("div", { style: { fontSize: 11.5, color: "var(--text-2)", marginBottom: 10, lineHeight: 1.45 } },
        "Run this question against the live graph."),
      React.createElement("button", {
        type: "button",
        onClick: () => onApiAccess && onApiAccess(ep || null),
        style: {
          width: "100%",
          padding: "10px 14px",
          borderRadius: 10,
          background: moduleColor,
          color: "#0a0a0a",
          fontWeight: 600,
          fontSize: 12,
          letterSpacing: "0.01em",
          border: "1px solid " + moduleColor,
          boxShadow: `0 6px 18px color-mix(in oklab, ${moduleColor} 28%, transparent), inset 0 1px 0 rgba(255,255,255,0.3)`,
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 8,
        },
      }, "Get API access →")
    )
  );
}

function RightRail({
  collapsed, onToggle,
  selectedNode, selectedEndpoint, selectedQ,
  hopIndex, onSetHop,
  onSelectNode, onSelectShape, onSelectQ, onSelectEndpoint, selectedRouteShape,
  onApiAccess,
}) {
  if (collapsed) {
    return React.createElement("aside", { className: "rail rail-right rail-collapsed glass-1" },
      React.createElement("button", { className: "icon-btn", onClick: onToggle, title: "Expand" },
        React.createElement(window.Icons.ChevL, null)),
      React.createElement("div", { className: "vlabel" }, "Inspector")
    );
  }

  let activeMode = "empty";
  if (selectedQ) activeMode = "question";
  else if (selectedEndpoint) activeMode = "endpoint";
  else if (selectedNode) activeMode = "entity";

  // data-active-mode is read by CSS to switch between desktop side
  // panel and mobile bottom sheet behavior.
  return React.createElement("aside", {
    className: "rail rail-right glass-1",
    "data-active-mode": activeMode,
  },
    React.createElement("div", { style: { display: "flex", justifyContent: "flex-end", padding: "8px 8px 0" } },
      React.createElement("button", { className: "icon-btn", onClick: onToggle, title: "Close",
        style: { width: 24, height: 24 } }, React.createElement(window.Icons.ChevR, null))
    ),
    activeMode === "empty"    && React.createElement(EmptyState, null),
    activeMode === "entity"   && React.createElement(EntityInspector, {
      node: selectedNode,
      onSelectNode, onSelectShape, onSelectQ, onSelectEndpoint,
      selectedRouteShape,
    }),
    activeMode === "endpoint" && React.createElement(EndpointInspector, { endpoint: selectedEndpoint, onSelectQ, onApiAccess }),
    activeMode === "question" && React.createElement(QuestionInspector, { question: selectedQ, hopIndex, onSetHop, onSelectEndpoint, onApiAccess })
  );
}

function EmptyState() {
  // Clean centered empty state. Three subtle hints — no feature cards,
  // no curation. The exploration affordances live in the canvas, the
  // left rail's API tab, and the topbar search.
  return React.createElement("div", {
    style: {
      padding: "32px 24px",
      textAlign: "center",
      color: "var(--text-3)",
      display: "flex", flexDirection: "column",
      alignItems: "center",
      gap: 14,
    },
  },
    React.createElement("div", {
      style: {
        width: 56, height: 56,
        borderRadius: 16,
        background: "radial-gradient(circle at 30% 30%, var(--accent-tint), transparent 70%)",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: "var(--accent)",
        border: "1px solid var(--glass-border-strong)",
      },
    }, React.createElement(window.Icons.Compass, { size: 24 })),
    React.createElement("div", {
      style: { fontSize: 14, fontWeight: 600, color: "var(--text-1)" },
    }, "Pick a thread"),
    React.createElement("div", {
      style: { fontSize: 11.5, lineHeight: 1.55, maxWidth: 240 },
    },
      "Click a node on the canvas, an endpoint in the left rail, or a question via ⌘K. This panel becomes the inspector for whatever you pick."
    )
  );
}

window.RightRail = RightRail;
