// Тулбар и левая панель редактора.
const { useState: useStateER } = React;

function EditorToolbar(props) {
  const { activeSc, scById, activeScId, onPickSc, planId, plan, onPickPlan, planById,
    undo, redo, canUndo, canRedo, runCheck, checking, conflictCount, applyDraft, addedCount, zoom, panBy, win, setRightMode } = props;
  const craftPlans = D.plans.filter((p) => p.scId === activeScId);

  return (
    <div style={{ height: 52, flex: "none", display: "flex", alignItems: "center", gap: 8, padding: "0 12px", borderBottom: "1px solid var(--line)", background: "var(--bg-1)", overflow: "hidden" }}>
      {/* выбор КА */}
      <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
        <TypeDot type={activeSc.type} size={9} />
        <select value={activeScId} onChange={(e) => onPickSc(e.target.value)}
          style={{ padding: "6px 8px", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 6, color: "var(--ink)", fontFamily: "var(--mono)", fontSize: 12, fontWeight: 600, maxWidth: 180 }}>
          {D.GROUP_DEFS.map((g) => (
            <optgroup key={g.id} label={g.name}>
              {D.spacecraft.filter((s) => s.groupId === g.id).map((s) => <option key={s.id} value={s.id}>{s.short}</option>)}
            </optgroup>
          ))}
        </select>
      </div>
      {/* выбор плана */}
      <select value={planId || ""} onChange={(e) => onPickPlan(e.target.value)}
        style={{ padding: "6px 8px", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 6, color: "var(--ink-1)", fontFamily: "var(--mono)", fontSize: 11.5, maxWidth: 140 }}>
        {craftPlans.map((pl) => <option key={pl.id} value={pl.id}>{pl.id} · r{pl.rev}</option>)}
      </select>

      {/* добавить включение */}
      <div style={{ display: "flex", gap: 6, marginLeft: 4 }}>
        <button onClick={() => setRightMode("shoot")} style={addBtn(props.rightMode === "shoot")}>
          <span style={{ fontSize: 14, lineHeight: 1 }}>＋</span> Съёмка
        </button>
        <button onClick={() => setRightMode("downlink")} style={addBtn(props.rightMode === "downlink", "var(--accent)")}>
          <span style={{ fontSize: 14, lineHeight: 1 }}>＋</span> Сброс
        </button>
      </div>

      <div style={{ flex: 1 }} />

      {/* зум / пан окна */}
      <div style={{ display: "flex", alignItems: "center", gap: 2, background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 7, padding: 2 }}>
        <IconBtn onClick={() => panBy(-0.25)} title="назад">◀</IconBtn>
        <IconBtn onClick={() => zoom(1.4)} title="отдалить">−</IconBtn>
        <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", padding: "0 4px", minWidth: 64, textAlign: "center" }}>{fmtDur(win.t1 - win.t0)}</span>
        <IconBtn onClick={() => zoom(0.7)} title="приблизить">＋</IconBtn>
        <IconBtn onClick={() => panBy(0.25)} title="вперёд">▶</IconBtn>
      </div>

      {/* undo / redo */}
      <div style={{ display: "flex", gap: 2 }}>
        <IconBtn onClick={undo} disabled={!canUndo} title="отменить">↶</IconBtn>
        <IconBtn onClick={redo} disabled={!canRedo} title="вернуть">↷</IconBtn>
      </div>

      {/* проверка */}
      <button onClick={runCheck} disabled={checking} style={{
        display: "flex", alignItems: "center", gap: 6, padding: "7px 11px", borderRadius: 6, fontSize: 11.5, fontWeight: 600,
        border: "1px solid var(--line)", background: "var(--bg-2)", color: conflictCount ? "var(--now)" : "var(--ink-1)" }}>
        {checking ? "Проверка…" : conflictCount ? `⚠ ${conflictCount}` : "✓ Проверить"}
      </button>

      <button onClick={applyDraft} disabled={!addedCount && !canUndo} style={{
        padding: "7px 13px", borderRadius: 6, fontSize: 12, fontWeight: 700,
        border: "1px solid var(--accent)", background: "var(--accent)", color: "var(--bg-0)",
        opacity: (!addedCount && !canUndo) ? 0.45 : 1 }}>
        Применить{addedCount ? ` · +${addedCount}` : ""}
      </button>
    </div>
  );
}
function addBtn(active, col) {
  return {
    display: "flex", alignItems: "center", gap: 5, padding: "7px 11px", borderRadius: 6, fontSize: 11.5, fontWeight: 600,
    border: `1px solid ${active ? (col || "var(--t-optical)") : "var(--line)"}`,
    background: active ? (col ? "oklch(0.82 0.13 200 / 0.16)" : "oklch(0.80 0.14 158 / 0.14)") : "var(--bg-2)",
    color: "var(--ink-1)",
  };
}
function IconBtn({ children, onClick, disabled, title }) {
  return (
    <button onClick={onClick} disabled={disabled} title={title} style={{
      width: 28, height: 28, borderRadius: 5, border: "none", background: "transparent",
      color: disabled ? "var(--ink-3)" : "var(--ink-1)", fontSize: 13, opacity: disabled ? 0.4 : 1,
      display: "grid", placeItems: "center", cursor: disabled ? "default" : "pointer" }}>{children}</button>
  );
}

function EditorRail(props) {
  const { activeSc, plan, draft, conflictCount, ctxList, ctxScope, setCtxScope, ctxSearch, setCtxSearch,
    otherShown, toggleOther, scById, setRightMode, basemap, setBasemap } = props;
  const group = D.GROUP_DEFS.find((g) => g.id === activeSc.groupId);
  const nShoot = draft.filter((w) => w.kind === "shoot").length;
  const nDown = draft.filter((w) => w.kind === "downlink").length;

  return (
    <div style={{ background: "var(--bg-1)", borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", minHeight: 0 }}>
      {/* активный КА */}
      <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--line-soft)" }}>
        <div className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 7 }}>РЕДАКТИРУЕТСЯ</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <TypeDot type={activeSc.type} size={10} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700 }}>{activeSc.name}</div>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{D.TYPES[activeSc.type].label} · {group.name}</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 14, marginTop: 10 }}>
          <RailStat label="ВКЛЮЧЕНИЙ" v={draft.length} />
          <RailStat label="СЪЁМКА" v={nShoot} c="var(--t-optical)" />
          <RailStat label="СБРОС" v={nDown} c="var(--accent)" />
          <RailStat label="КОНФЛ." v={conflictCount} c={conflictCount ? "var(--now)" : null} />
        </div>
      </div>

      {/* подложка карты */}
      <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--line-soft)" }}>
        <div className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 6 }}>ПОДЛОЖКА КАРТЫ</div>
        <div style={{ display: "flex", gap: 3, background: "var(--bg-0)", borderRadius: 7, padding: 3, border: "1px solid var(--line)" }}>
          {[["dark", "Тёмная"], ["osm", "Светлая"], ["schema", "Схема"]].map(([id, lab]) => (
            <button key={id} onClick={() => setBasemap(id)} style={{ flex: 1, padding: "5px 0", borderRadius: 5, border: "none", fontSize: 11, fontWeight: 600, background: basemap === id ? "var(--bg-3)" : "transparent", color: basemap === id ? "var(--ink)" : "var(--ink-3)" }}>{lab}</button>
          ))}
        </div>
      </div>

      {/* контекст: другие КА */}
      <div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
        <div style={{ padding: "11px 14px 8px" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".1em" }}>ДРУГИЕ КА · КОНТЕКСТ</span>
            <span className="mono" style={{ fontSize: 9, color: "var(--accent)" }}>{otherShown.size} вкл.</span>
          </div>
          <div style={{ display: "flex", gap: 3, background: "var(--bg-0)", borderRadius: 7, padding: 3, border: "1px solid var(--line)", marginBottom: 8 }}>
            {[["group", "Своя группа"], ["all", "Все"]].map(([id, lab]) => (
              <button key={id} onClick={() => setCtxScope(id)} style={{ flex: 1, padding: "5px 0", borderRadius: 5, border: "none", fontSize: 11, fontWeight: 600, background: ctxScope === id ? "var(--bg-3)" : "transparent", color: ctxScope === id ? "var(--ink)" : "var(--ink-3)" }}>{lab}</button>
            ))}
          </div>
          {ctxScope === "all" && (
            <input value={ctxSearch} onChange={(e) => setCtxSearch(e.target.value)} placeholder="Поиск КА…"
              style={{ width: "100%", padding: "6px 8px", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 6, color: "var(--ink)", fontFamily: "var(--mono)", fontSize: 11.5, marginBottom: 4 }} />
          )}
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "0 8px 14px" }}>
          {ctxList.map((s) => {
            const on = otherShown.has(s.id);
            return (
              <button key={s.id} onClick={() => toggleOther(s.id)} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "5px 7px", borderRadius: 6, border: "none", background: on ? "var(--bg-2)" : "transparent", textAlign: "left" }}>
                <span style={{ width: 15, height: 15, flex: "none", borderRadius: 4, border: `1.5px solid ${on ? "var(--accent)" : "var(--line)"}`, background: on ? "var(--accent)" : "transparent", display: "grid", placeItems: "center" }}>
                  {on && <svg width="9" height="9" 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>}
                </span>
                <TypeDot type={s.type} size={7} />
                <span className="mono" style={{ flex: 1, fontSize: 11, color: on ? "var(--ink-1)" : "var(--ink-3)" }}>{s.short}</span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}
function RailStat({ label, v, c }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
      <span className="mono tnum" style={{ fontSize: 16, fontWeight: 600, color: c || "var(--ink)" }}>{v}</span>
      <span className="mono" style={{ fontSize: 7.5, color: "var(--ink-3)", letterSpacing: ".06em" }}>{label}</span>
    </div>
  );
}

Object.assign(window, { EditorToolbar, EditorRail });
