// Левая панель: поиск, фильтр по типам (легенда), дерево групп → КА с чекбоксами.
const { useState: useStateSB } = React;

function TypeDot({ type, size = 9 }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: 2, flex: "none",
      background: TYPE_COLOR[type], display: "inline-block",
      boxShadow: `0 0 6px ${TYPE_COLOR[type]}`,
    }} />
  );
}

function Check({ on, onClick, dim }) {
  return (
    <button onClick={onClick} aria-label="toggle" style={{
      width: 16, height: 16, flex: "none", borderRadius: 4,
      border: `1.5px solid ${on ? "var(--accent)" : "var(--line)"}`,
      background: on ? "var(--accent)" : "transparent",
      opacity: dim ? 0.4 : 1,
      display: "grid", placeItems: "center", padding: 0, transition: "all .12s",
    }}>
      {on && (
        <svg width="10" height="10" viewBox="0 0 10 10"><path d="M1.5 5.2 4 7.6 8.6 2.4" stroke="var(--bg-0)" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
      )}
    </button>
  );
}

function Sidebar(props) {
  const { groups, scByGroup, typeFilter, setTypeFilter, groupShown, toggleGroup,
    scHidden, toggleSc, search, setSearch, counts, selectedSc, onPickSc } = props;
  const [open, setOpen] = useStateSB(() => {
    const o = {}; D.GROUP_DEFS.forEach((g) => (o[g.id] = true)); return o;
  });

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", background: "var(--bg-1)", borderRight: "1px solid var(--line)" }}>
      {/* Заголовок */}
      <div style={{ padding: "14px 14px 10px", borderBottom: "1px solid var(--line-soft)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: 22, height: 22, borderRadius: 5, background: "var(--accent)", display: "grid", placeItems: "center", boxShadow: "0 0 12px var(--accent)" }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" fill="var(--bg-0)" /><ellipse cx="12" cy="12" rx="10" ry="4.3" stroke="var(--bg-0)" strokeWidth="1.7" transform="rotate(28 12 12)" /></svg>
          </div>
          <div>
            <div style={{ fontWeight: 700, letterSpacing: ".02em", fontSize: 13 }}>ПЛАН КА</div>
            <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".08em" }}>MISSION OPS · ДЗЗ</div>
          </div>
        </div>
      </div>

      {/* Поиск */}
      <div style={{ padding: "10px 12px 8px" }}>
        <div style={{ position: "relative" }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" style={{ position: "absolute", left: 9, top: 9, opacity: .5 }}><circle cx="11" cy="11" r="7" stroke="var(--ink-2)" strokeWidth="2" /><path d="m20 20-3.5-3.5" stroke="var(--ink-2)" strokeWidth="2" strokeLinecap="round" /></svg>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Поиск КА…"
            style={{ width: "100%", padding: "7px 8px 7px 28px", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 6, color: "var(--ink)", fontFamily: "var(--mono)", fontSize: 12, outline: "none" }} />
          {search && <button onClick={() => setSearch("")} style={{ position: "absolute", right: 6, top: 6, background: "none", border: "none", color: "var(--ink-3)", fontSize: 14, padding: 2 }}>×</button>}
        </div>
      </div>

      {/* Легенда / фильтр по типам */}
      <div style={{ padding: "4px 12px 10px", borderBottom: "1px solid var(--line-soft)" }}>
        <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 6 }}>АППАРАТУРА</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
          {D.typeOrder.map((t) => {
            const on = typeFilter[t];
            return (
              <button key={t} onClick={() => setTypeFilter({ ...typeFilter, [t]: !on })}
                style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 7px", borderRadius: 6, border: "1px solid transparent", background: on ? "var(--bg-2)" : "transparent", opacity: on ? 1 : 0.45, textAlign: "left" }}>
                <TypeDot type={t} />
                <span style={{ flex: 1, fontSize: 12 }}>{D.TYPES[t].label}</span>
                <span className="mono tnum" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{counts.byType[t] || 0}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Дерево групп → КА */}
      <div style={{ flex: 1, overflowY: "auto", padding: "8px 8px 16px" }}>
        <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".1em", margin: "2px 6px 6px" }}>ГРУППЫ / КА</div>
        {groups.map((g) => {
          const list = scByGroup[g.id] || [];
          const isOpen = open[g.id];
          const shownCount = list.filter((sc) => !scHidden.has(sc.id)).length;
          return (
            <div key={g.id} style={{ marginBottom: 2 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "5px 6px", borderRadius: 6, background: "var(--bg-2)" }}>
                <button onClick={() => setOpen({ ...open, [g.id]: !isOpen })} style={{ background: "none", border: "none", padding: 0, width: 14, height: 14, display: "grid", placeItems: "center", color: "var(--ink-2)" }}>
                  <svg width="9" height="9" viewBox="0 0 10 10" style={{ transform: isOpen ? "rotate(90deg)" : "none", transition: "transform .12s" }}><path d="M3 1.5 7 5 3 8.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </button>
                <Check on={groupShown[g.id]} onClick={() => toggleGroup(g.id)} />
                <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{g.code}</span>
                <span style={{ flex: 1, fontSize: 12, fontWeight: 600, color: groupShown[g.id] ? "var(--ink)" : "var(--ink-3)" }}>{g.name}</span>
                <span className="mono tnum" style={{ fontSize: 10, color: "var(--ink-3)" }}>{shownCount}/{list.length}</span>
              </div>
              {isOpen && (
                <div style={{ marginLeft: 14, borderLeft: "1px solid var(--line-soft)", paddingLeft: 4, marginTop: 2 }}>
                  {list.map((sc) => {
                    const vis = !scHidden.has(sc.id);
                    const sel = selectedSc === sc.id;
                    return (
                      <div key={sc.id} onClick={() => onPickSc(sc.id)}
                        style={{ display: "flex", alignItems: "center", gap: 7, padding: "4px 7px", borderRadius: 6, cursor: "pointer", background: sel ? "var(--bg-3)" : "transparent" }}>
                        <Check on={vis} dim={!groupShown[g.id]} onClick={(e) => { e.stopPropagation(); toggleSc(sc.id); }} />
                        <TypeDot type={sc.type} size={7} />
                        <span className="mono" style={{ flex: 1, fontSize: 11, color: vis && groupShown[g.id] ? "var(--ink-1)" : "var(--ink-3)" }}>{sc.short}</span>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, TypeDot });
