// Правая контекстная панель редактора: инспектор выбранного включения,
// флоу добавления съёмки (цель+проход+режим) и сброса (станция+сеанс).
const { useState: useStateEP, useMemo: useMemoEP } = React;

function Sect({ title, right, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>{title}</span>
        {right}
      </div>
      {children}
    </div>
  );
}
function Btn({ children, onClick, kind, disabled, flex }) {
  const styles = {
    primary: { background: "var(--accent)", color: "var(--bg-0)", border: "1px solid var(--accent)" },
    danger: { background: "transparent", color: "var(--now)", border: "1px solid color-mix(in oklch, var(--now) 50%, var(--bg-0))" },
    ghost: { background: "var(--bg-2)", color: "var(--ink-1)", border: "1px solid var(--line)" },
  };
  return (
    <button onClick={onClick} disabled={disabled} style={{
      ...(styles[kind] || styles.ghost), padding: "7px 11px", borderRadius: 6, fontSize: 12, fontWeight: 600,
      opacity: disabled ? 0.4 : 1, cursor: disabled ? "not-allowed" : "pointer", flex: flex ? 1 : "none",
    }}>{children}</button>
  );
}
function passDur(p) { return fmtDur(p.end - p.start); }

// ---- Инспектор выбранного включения ----
function WorkInspector({ work, activeSc, conflicts, onUpdate, onDelete, onDuplicate, onClose }) {
  const col = kindColor(work.kind, activeSc.type);
  const confl = conflicts[work.id] || [];
  const modes = SENSOR_MODES[activeSc.type] || [];
  const stations = window.WorldGeo.GROUND_STATIONS;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <span style={{ width: 9, height: 9, borderRadius: 2, background: col }} />
            <span style={{ fontSize: 14, fontWeight: 700 }}>{kindLabel(work.kind)}</span>
            {work.isNew && <span className="mono" style={{ fontSize: 8, color: "var(--now)", border: "1px solid var(--now)", borderRadius: 3, padding: "0 3px" }}>NEW</span>}
          </span>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", fontSize: 17, padding: 0 }}>×</button>
        </div>
        <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 3 }}>{work.id}</div>
      </div>

      {confl.length > 0 && (
        <div style={{ background: "oklch(0.86 0.16 25 / 0.12)", border: "1px solid color-mix(in oklch, var(--now) 50%, transparent)", borderRadius: 6, padding: "8px 10px" }}>
          <div className="mono" style={{ fontSize: 9, color: "var(--now)", letterSpacing: ".06em", marginBottom: 4 }}>⚠ КОНФЛИКТ (сервис проверки)</div>
          {confl.map((c, i) => <div key={i} style={{ fontSize: 11, color: "var(--ink-1)" }}>{c}</div>)}
        </div>
      )}

      <Sect title="ВРЕМЯ">
        <TimeStepper label="начало" value={work.start} max={work.end - 60000} onChange={(v) => onUpdate(work.id, { start: v })} />
        <TimeStepper label="конец" value={work.end} min={work.start + 60000} onChange={(v) => onUpdate(work.id, { end: v })} />
        <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>длительность: {fmtDur(work.end - work.start)}</div>
      </Sect>

      {work.kind === "shoot" && (
        <Sect title="РЕЖИМ АППАРАТУРЫ">
          <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
            {modes.map((m) => (
              <button key={m.id} onClick={() => onUpdate(work.id, { modeId: m.id, label: m.label })}
                style={{ padding: "6px 10px", borderRadius: 6, fontSize: 11.5, fontWeight: 600,
                  border: `1px solid ${work.modeId === m.id ? "var(--accent)" : "var(--line)"}`,
                  background: work.modeId === m.id ? "oklch(0.82 0.13 200 / 0.14)" : "var(--bg-2)",
                  color: work.modeId === m.id ? "var(--ink)" : "var(--ink-2)" }}>{m.label}</button>
            ))}
          </div>
          {work.targetName && <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-2)" }}>цель: {work.targetName}</div>}
        </Sect>
      )}

      {work.kind === "downlink" && (
        <Sect title="СТАНЦИЯ ПРИЁМА">
          <select value={work.stationId || ""} onChange={(e) => onUpdate(work.id, { stationId: e.target.value })}
            style={{ width: "100%", padding: "7px 8px", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 6, color: "var(--ink)", fontFamily: "var(--mono)", fontSize: 12 }}>
            {stations.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </Sect>
      )}

      <div style={{ display: "flex", gap: 8 }}>
        <Btn kind="ghost" flex onClick={() => onDuplicate(work.id)}>Дублировать</Btn>
        <Btn kind="danger" flex onClick={() => onDelete(work.id)}>Удалить</Btn>
      </div>
    </div>
  );
}

// Подстройка времени степперами (±5 мин / ±1 ч) + моноширинный вывод даты/времени.
function TimeStepper({ label, value, onChange, min, max }) {
  const clamp = (v) => Math.max(min != null ? min : -Infinity, Math.min(max != null ? max : Infinity, v));
  const nudge = (deltaMs) => onChange(clamp(value + deltaMs));
  const M = 60000, H = 3600000;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <span className="mono" style={{ fontSize: 8.5, color: "var(--ink-3)" }}>{label}</span>
      <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
        <StepBtn onClick={() => nudge(-H)}>−ч</StepBtn>
        <StepBtn onClick={() => nudge(-5 * M)}>−5м</StepBtn>
        <span className="mono tnum" style={{ flex: 1, textAlign: "center", fontSize: 11.5, color: "var(--ink)", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: 5, padding: "5px 4px" }}>{fmtDateTime(value)}</span>
        <StepBtn onClick={() => nudge(5 * M)}>+5м</StepBtn>
        <StepBtn onClick={() => nudge(H)}>+ч</StepBtn>
      </div>
    </div>
  );
}
function StepBtn({ children, onClick }) {
  return <button onClick={onClick} style={{ flex: "none", padding: "5px 6px", borderRadius: 5, border: "1px solid var(--line)", background: "var(--bg-2)", color: "var(--ink-1)", fontFamily: "var(--mono)", fontSize: 10, fontWeight: 600 }}>{children}</button>;
}

// ---- Флоу добавления СЪЁМКИ ----
function ShootPanel({ activeSc, target, passes, selectedPass, setSelectedPass, modeId, setModeId, onAdd, onClose, onClearTarget }) {
  const modes = SENSOR_MODES[activeSc.type] || [];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <PanelHead title="Новая съёмка" onClose={onClose} />
      <Sect title="1 · ЦЕЛЬ СЪЁМКИ" right={target && <button onClick={onClearTarget} style={{ background: "none", border: "none", color: "var(--ink-3)", fontSize: 10 }}>сбросить</button>}>
        {!target ? (
          <div style={{ fontSize: 11.5, color: "var(--ink-2)", lineHeight: 1.5, background: "var(--bg-2)", borderRadius: 6, padding: "9px 11px", border: "1px dashed var(--line)" }}>
            Кликните точку на карте слева — запросим расписание видимости этой точки аппаратом {activeSc.short}.
          </div>
        ) : (
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--bg-2)", borderRadius: 6, padding: "8px 10px" }}>
            <span style={{ width: 9, height: 9, borderRadius: 9, border: "2px solid var(--now)", flex: "none" }} />
            <span style={{ flex: 1, fontSize: 12, fontWeight: 600 }}>{target.name}</span>
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{target.lat.toFixed(2)}, {target.lon.toFixed(2)}</span>
          </div>
        )}
      </Sect>

      {target && (
        <Sect title="2 · ОКНО ВИДИМОСТИ (ПРОХОД)">
          {passes.length === 0 ? (
            <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>В окне планирования проходов над целью нет.</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 4, maxHeight: 188, overflowY: "auto" }}>
              {passes.map((ps, i) => {
                const sel = selectedPass && selectedPass.start === ps.start;
                return (
                  <button key={i} onClick={() => setSelectedPass(ps)} style={{
                    display: "flex", alignItems: "center", gap: 8, padding: "7px 9px", borderRadius: 6, textAlign: "left",
                    border: `1px solid ${sel ? "var(--accent)" : "var(--line-soft)"}`, background: sel ? "oklch(0.82 0.13 200 / 0.12)" : "var(--bg-2)" }}>
                    <span className="mono tnum" style={{ fontSize: 11, color: "var(--ink-1)", flex: 1 }}>{fmtDate(ps.start)} {fmtTime(ps.start)}</span>
                    <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)" }}>{passDur(ps)}</span>
                    <QualityDot q={ps.quality} />
                  </button>
                );
              })}
            </div>
          )}
        </Sect>
      )}

      {target && selectedPass && (
        <Sect title="3 · РЕЖИМ СЪЁМКИ">
          <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
            {modes.map((m) => (
              <button key={m.id} onClick={() => setModeId(m.id)} style={{ padding: "6px 10px", borderRadius: 6, fontSize: 11.5, fontWeight: 600,
                border: `1px solid ${modeId === m.id ? "var(--accent)" : "var(--line)"}`, background: modeId === m.id ? "oklch(0.82 0.13 200 / 0.14)" : "var(--bg-2)", color: modeId === m.id ? "var(--ink)" : "var(--ink-2)" }}>{m.label}</button>
            ))}
          </div>
        </Sect>
      )}

      <Btn kind="primary" disabled={!target || !selectedPass || !modeId} onClick={onAdd}>+ Добавить съёмку в план</Btn>
    </div>
  );
}

// ---- Флоу добавления СБРОСА ----
function DownlinkPanel({ activeSc, stationOptions, selected, setSelected, onAdd, onClose }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <PanelHead title="Новый сброс на НКПОР" onClose={onClose} />
      <div style={{ fontSize: 11.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
        Расписание сеансов связи аппарата {activeSc.short} со станциями приёма. Выберите станцию и сеанс.
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10, maxHeight: 460, overflowY: "auto" }}>
        {stationOptions.map((so) => (
          <div key={so.station.id} style={{ border: "1px solid var(--line-soft)", borderRadius: 8, overflow: "hidden", flexShrink: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 7, padding: "7px 10px", background: "var(--bg-2)" }}>
              <svg width="11" height="11" viewBox="0 0 24 24"><path d="M0,-6 L5,4 L-5,4 Z" transform="translate(12 13)" fill="var(--accent)" /></svg>
              <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600 }}>{so.station.name}</span>
              <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)" }}>{so.passes.length} сеанс.</span>
            </div>
            {so.passes.length === 0 ? (
              <div style={{ fontSize: 10.5, color: "var(--ink-3)", padding: "6px 10px" }}>нет сеансов в окне</div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column" }}>
                {so.passes.slice(0, 5).map((ps, i) => {
                  const sel = selected && selected.station.id === so.station.id && selected.pass.start === ps.start;
                  return (
                    <button key={i} onClick={() => setSelected({ station: so.station, pass: ps })} style={{
                      display: "flex", alignItems: "center", gap: 8, padding: "6px 10px", textAlign: "left",
                      borderTop: "1px solid var(--line-soft)", background: sel ? "oklch(0.82 0.13 200 / 0.14)" : "transparent" }}>
                      <span className="mono tnum" style={{ fontSize: 10.5, color: "var(--ink-1)", flex: 1 }}>{fmtDate(ps.start)} {fmtTime(ps.start)}–{fmtTime(ps.end)}</span>
                      <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)" }}>{passDur(ps)}</span>
                      {sel && <span style={{ color: "var(--accent)", fontSize: 12 }}>✓</span>}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        ))}
      </div>
      <Btn kind="primary" disabled={!selected} onClick={onAdd}>+ Добавить сброс в план</Btn>
    </div>
  );
}

function PanelHead({ title, onClose }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <span style={{ fontSize: 14, fontWeight: 700 }}>{title}</span>
      <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", fontSize: 17, padding: 0 }}>×</button>
    </div>
  );
}
function QualityDot({ q }) {
  const c = q > 0.6 ? "var(--t-optical)" : q > 0.3 ? "var(--t-radar)" : "var(--ink-3)";
  return <span title={`качество прохода ${(q * 100) | 0}%`} style={{ width: 7, height: 7, borderRadius: 9, background: c, flex: "none" }} />;
}

Object.assign(window, { WorkInspector, ShootPanel, DownlinkPanel });
