// nav-island.jsx — Pick chip + right-side flyout filter.
//
// PickChip: compact clickable row rendered inside the left domain-panel.
// PickFlyout: appears to the RIGHT of the domain-panel when a chip is active,
//             showing that pick's taxonomy subtree with checkboxes.
// Only one flyout open at a time; click the same chip again, click ×, or hit ESC closes.
//
// Three checkbox states (same as before):
//   checked        : path not in excludedPaths AND no ancestor in excludedPaths
//   self-off       : path itself is in excludedPaths
//   disabled-faded : an ancestor is in excludedPaths

const { useEffect: useEffectNI } = React;

const NI_SLOT_SWATCH = [
  "linear-gradient(135deg,#5E6AD2,#7C8CFF)",
  "linear-gradient(135deg,#2FAE8F,#6BC9B1)",
  "linear-gradient(135deg,#C68A28,#F2B45A)",
];

function pickLabelNI(p) {
  const cl = window.kgCleanLabel ? window.kgCleanLabel(p.tile_id) : null;
  if (cl) return cl.zh || cl.en;
  return p.label_zh || p.label_en || p.tile_id;
}

function pathLabelNI(path) {
  const cl = window.kgCleanLabel ? window.kgCleanLabel(path) : null;
  if (cl && (cl.zh || cl.en)) return cl.zh || cl.en;
  const seg = (path || "").split(".").pop() || "";
  return seg.split("_").map(w => w ? w[0].toUpperCase() + w.slice(1) : "").join(" ");
}

function PickChip({ pick, slot, count, active, onClick }) {
  return (
    <div
      className={"pick-chip" + (active ? " active" : "")}
      onClick={onClick}
      title={pick.tile_id}
    >
      <span
        className="swatch"
        style={{ background: NI_SLOT_SWATCH[slot] || NI_SLOT_SWATCH[0] }}
      />
      <span className="name">{pickLabelNI(pick)}</span>
      <span className="count">{count}</span>
      <span className="caret">{active ? "›" : ""}</span>
    </div>
  );
}

function PickFlyout({ pick, slot, rows, excludedPaths, onExcludedChange, onClose }) {
  // Close on ESC
  useEffectNI(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);

  const rootDepth = (pick.tile_id || "").split(".").length;

  function toggleRow(path) {
    const next = new Set(excludedPaths);
    if (next.has(path)) next.delete(path);
    else next.add(path);
    onExcludedChange(next);
  }
  function hideAll() {
    const next = new Set(excludedPaths);
    next.add(pick.tile_id);
    onExcludedChange(next);
  }
  function showAll() {
    const next = new Set();
    for (const p of excludedPaths) {
      if (p !== pick.tile_id && !p.startsWith(pick.tile_id + ".")) next.add(p);
    }
    onExcludedChange(next);
  }

  return (
    <div className="pick-flyout">
      <div className="pick-flyout-head">
        <span
          className="swatch"
          style={{ background: NI_SLOT_SWATCH[slot] || NI_SLOT_SWATCH[0] }}
        />
        <strong>{pickLabelNI(pick)}</strong>
        <span className="path">{pick.tile_id}</span>
        <button onClick={onClose} title="关闭">×</button>
      </div>

      <div className="pick-flyout-actions">
        <button onClick={showAll}>全选</button>
        <button onClick={hideAll}>全清</button>
        <span className="hint">取消勾选 → 该子树立即从图中隐藏</span>
      </div>

      {!rows ? (
        <div className="pick-flyout-empty">加载分类树…</div>
      ) : rows.length === 0 ? (
        <div className="pick-flyout-empty">该领域下无更深的分类节点</div>
      ) : (
        <div className="pick-flyout-rows">
          {rows.map(r => {
            const ancestorOff = window.graphAdapter.isAncestorExcluded(r.path, excludedPaths);
            const selfOff = excludedPaths.has(r.path);
            const checked = !ancestorOff && !selfOff;
            const depth = r.path.split(".").length;
            const indent = Math.max(0, depth - rootDepth) * 12;
            return (
              <label
                key={r.path}
                className={"pick-flyout-row" + (ancestorOff ? " disabled" : "") + (selfOff ? " self-off" : "")}
                style={{ paddingLeft: 14 + indent }}
                title={r.path}
                onClick={(e) => {
                  if (ancestorOff) return;
                  e.preventDefault();
                  toggleRow(r.path);
                }}
              >
                <span className={"chk" + (checked ? " on" : "")}/>
                <span className="lbl">{pathLabelNI(r.path)}</span>
                <span className="cnt">{r.node_count}</span>
              </label>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.PickChip = PickChip;
window.PickFlyout = PickFlyout;
