/* Right-column entity detail pane (and lightweight markdown note renderer). */
{
  const { useMemo, useState } = React;

  const KIND_ORDER = { inheritance: 0, composition: 1, aggregation: 2, association: 3, dependency: 4 };

  function plainLabel(kind, direction) {
    if (kind === "inheritance") return direction === "out" ? "is a" : "subtype";
    if (kind === "composition") return direction === "out" ? "has" : "belongs to";
    if (kind === "aggregation") return direction === "out" ? "contains" : "is part of";
    if (kind === "dependency") return direction === "out" ? "uses" : "used by";
    return direction === "out" ? "links to" : "linked from";
  }

  function effectiveCard(r, side) {
    const explicit = side === "from" ? r.fromCard : r.toCard;
    if (explicit) return explicit;
    if (r.kind === "inheritance" || r.kind === "dependency") return null;
    return "1";
  }

  function CardPill({ r, direction }) {
    const focusedSide = direction === "out" ? "from" : "to";
    const otherSide   = direction === "out" ? "to"   : "from";
    const leftC  = effectiveCard(r, focusedSide);
    const rightC = effectiveCard(r, otherSide);
    if (!leftC && !rightC) {
      return (
        <div className="card-pill kindless">
          <span className="glyph">{r.kind === "inheritance" ? "is a" : "uses"}</span>
        </div>
      );
    }
    return (
      <div className={`card-pill k-${r.kind}`}>
        <span className="end self" title="this side">{leftC ?? "—"}</span>
        <span className="glyph">→</span>
        <span className="end other" title="the other side">{rightC ?? "—"}</span>
      </div>
    );
  }

  function NoteBlock({ note }) {
    const html = useMemo(() => note
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
      .replace(/`([^`]+)`/g, "<code>$1</code>"),
      [note]);
    return <div className="note" dangerouslySetInnerHTML={{ __html: html }} />;
  }

  function DetailPane({ model, focusedName, onSelect }) {
    const ent = focusedName ? model.entities.get(focusedName) : null;
    const [linkFilter, setLinkFilter] = useState("all");

    const links = useMemo(() => {
      if (!ent) return [];
      const out = (model.outRel.get(ent.name) || []).map(r => ({ ...r, direction: "out", other: r.to }));
      const inc = (model.inRel.get(ent.name)  || []).map(r => ({ ...r, direction: "in",  other: r.from }));
      const all = [...out, ...inc];
      all.sort((a, b) => {
        const ka = KIND_ORDER[a.kind] ?? 9, kb = KIND_ORDER[b.kind] ?? 9;
        if (ka !== kb) return ka - kb;
        if (a.direction !== b.direction) return a.direction === "out" ? -1 : 1;
        return a.other.localeCompare(b.other);
      });
      return all;
    }, [model, ent]);

    const visibleLinks = useMemo(
      () => linkFilter === "all" ? links : links.filter(l => l.direction === linkFilter),
      [links, linkFilter]
    );

    const counts = useMemo(() => ({
      out: links.filter(l => l.direction === "out").length,
      inc: links.filter(l => l.direction === "in").length,
    }), [links]);

    if (!ent) {
      return (
        <div className="panel">
          <div className="panel-head"><h2>Detail</h2></div>
          <div className="detail-empty">
            # select an entity to inspect<br/>
            <span style={{opacity: 0.6}}>or search above</span>
          </div>
        </div>
      );
    }

    return (
      <div className="panel">
        <div className="panel-head">
          <h2>Detail</h2>
          <div className="count">{ent.kind}</div>
        </div>
        <div className="panel-body">
          <div className="detail">
            <h1 className="ent-name">
              {ent.kind === "abstract"
                ? <span className="abstract">{ent.displayName}</span>
                : <span>{ent.displayName}</span>}
              {ent.kind === "interface" && <span className="interface-mark">«interface»</span>}
              {ent.kind === "enum" && <span className="interface-mark">«enum»</span>}
            </h1>
            {ent.stereotypes.length > 0 && (
              <div className="badge-row">
                {ent.stereotypes.map(s => (
                  <span key={s} className="badge" style={{ background: stereoBg(s), color: stereoFg(s) }}>
                    <span className="dot" style={{ background: "currentColor", opacity: 0.6 }}></span>
                    {s}
                  </span>
                ))}
              </div>
            )}

            {ent.note && (
              <>
                <div className="section-h">Doc</div>
                <NoteBlock note={ent.note} />
              </>
            )}

            {ent.kind === "enum" && ent.values.length > 0 && (
              <>
                <div className="section-h">Values <span className="count">{ent.values.length}</span></div>
                <div className="enum-vals">
                  {ent.values.map(v => <div className="val" key={v}>{v}</div>)}
                </div>
              </>
            )}

            {links.length > 0 && (
              <>
                <div className="section-h">
                  Connections <span className="count">{links.length}</span>
                  <span style={{ marginLeft: "auto", display: "inline-flex", gap: 4 }}>
                    <button className={`chip ${linkFilter==="all" ? "active":""}`} onClick={()=>setLinkFilter("all")}>all {links.length}</button>
                    <button className={`chip ${linkFilter==="out" ? "active":""}`} onClick={()=>setLinkFilter("out")}>outgoing {counts.out}</button>
                    <button className={`chip ${linkFilter==="in"  ? "active":""}`} onClick={()=>setLinkFilter("in")}>incoming {counts.inc}</button>
                  </span>
                </div>
                <div className="rel-list">
                  {visibleLinks.map((r, i) => (
                    <div className="rel" key={`r-${i}`}>
                      <CardPill r={r} direction={r.direction} />
                      <div className="rel-mid">
                        <div className="rel-line">
                          <span className="rel-verb">{plainLabel(r.kind, r.direction)}</span>
                          <a className="rel-target" onClick={() => onSelect(r.other)}>{r.other}</a>
                        </div>
                        {r.label && <div className="rel-edge-label">via <code>{r.label}</code></div>}
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  window.DetailPane = DetailPane;
}
