// Панель деталей плана на странице «Карта»: сводка, наземные параметры,
// работы (со «съёмка/сброс»), ссылка обратно на таймлайн.
function MapStatusBadge({ status }) {
  const map = {
    executed: { t: "ВЫПОЛНЕН", c: "var(--ink-2)", bg: "var(--bg-3)" },
    active: { t: "АКТИВЕН", c: "var(--now)", bg: "oklch(0.86 0.16 25 / 0.16)" },
    planned: { t: "ЗАПЛАНИРОВАН", c: "var(--accent)", bg: "oklch(0.82 0.13 200 / 0.14)" },
  };
  const s = map[status] || map.planned;
  return <span className="mono" style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: ".06em", color: s.c, background: s.bg, padding: "2px 7px", borderRadius: 4 }}>{s.t}</span>;
}

function MapDetails({ plan, sc, params, byId, onSelectPlan, onClose, planPage }) {
  const col = TYPE_COLOR[sc.type];
  const shoots = plan.works.filter(w => w.kind === "shoot");
  const downs = plan.works.filter(w => w.kind === "downlink");
  const STATIONS = window.WorldGeo.GROUND_STATIONS;

  // станции, задействованные в сбросах
  const usedStations = [];
  for (const d of downs) {
    const pts = trackPoints(params, d.start, d.end, 10);
    const mid = pts[Math.floor(pts.length / 2)];
    const ns = nearestStation(mid.lat, mid.lon, STATIONS);
    if (ns.st && !usedStations.find(x => x.id === ns.st.id)) usedStations.push(ns.st);
  }

  return (
    <div style={{ background: "var(--bg-1)", borderLeft: "1px solid var(--line)", display: "flex", flexDirection: "column", minHeight: 0 }}>
      <div style={{ padding: "14px 16px 12px", borderBottom: "1px solid var(--line-soft)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: col, boxShadow: `0 0 8px ${col}`, flex: "none" }} />
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{plan.id}</span>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", fontSize: 18, lineHeight: 1, padding: 0 }}>×</button>
        </div>
        <div style={{ fontSize: 16, fontWeight: 700, marginTop: 8, lineHeight: 1.2 }}>{plan.title}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 9 }}>
          <MapStatusBadge status={plan.status} />
          <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-2)" }}>{sc.short} · {sc.orbit}</span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: "14px 16px 20px", display: "flex", flexDirection: "column", gap: 15 }}>
        {/* наземные параметры */}
        <div>
          <div className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em", marginBottom: 8 }}>НАЗЕМНЫЕ ПАРАМЕТРЫ</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <KV label="ВЫСОТА ОРБИТЫ">{params.h} км</KV>
            <KV label="ПЕРИОД ВИТКА">{(params.T / 60).toFixed(1)} мин</KV>
            <KV label="ПОЛОСА ОБЗОРА">{Math.round(params.swathKm)} км</KV>
            <KV label="НАКЛОНЕНИЕ">{(params.incl * RAD).toFixed(1)}°</KV>
          </div>
        </div>

        <div style={{ height: 1, background: "var(--line-soft)" }} />

        {/* съёмка */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 8 }}>
            <span style={{ width: 10, height: 8, background: col, borderRadius: 2, flex: "none" }} />
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>КОНТУРЫ СЪЁМКИ</span>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", marginLeft: "auto" }}>{shoots.length}</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
            {shoots.length === 0 && <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Съёмочных маршрутов нет.</div>}
            {shoots.map(w => (
              <div key={w.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 8px", borderRadius: 6, background: "var(--bg-2)" }}>
                <span style={{ flex: 1, fontSize: 11.5, color: "var(--ink-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{w.label}</span>
                <span className="mono tnum" style={{ fontSize: 10, color: "var(--ink-3)" }}>{fmtTime(w.start)}–{fmtTime(w.end)}</span>
              </div>
            ))}
          </div>
        </div>

        {/* сброс */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 8 }}>
            <span style={{ width: 12, height: 3, background: "var(--accent)", borderRadius: 2, flex: "none", boxShadow: "0 0 5px var(--accent)" }} />
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>УЧАСТКИ СБРОСА</span>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", marginLeft: "auto" }}>{downs.length}</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
            {downs.length === 0 && <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Сбросов нет.</div>}
            {downs.map(w => {
              const pts = trackPoints(params, w.start, w.end, 10);
              const mid = pts[Math.floor(pts.length / 2)];
              const ns = nearestStation(mid.lat, mid.lon, STATIONS);
              return (
                <div key={w.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 8px", borderRadius: 6, background: "var(--bg-2)" }}>
                  <span style={{ flex: 1, fontSize: 11.5, color: "var(--ink-1)" }}>→ {ns.st.name}</span>
                  <span className="mono tnum" style={{ fontSize: 10, color: "var(--ink-3)" }}>{fmtTime(w.start)}–{fmtTime(w.end)}</span>
                </div>
              );
            })}
          </div>
        </div>

        {usedStations.length > 0 && (
          <div style={{ fontSize: 10.5, color: "var(--ink-3)", lineHeight: 1.5 }}>
            Задействованы станции: <span style={{ color: "var(--ink-1)" }}>{usedStations.map(s => s.name).join(", ")}</span>
          </div>
        )}
      </div>

      <div style={{ padding: "12px 16px", borderTop: "1px solid var(--line-soft)" }}>
        <a href={`${planPage}?plan=${plan.id}`} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, padding: "9px 0", borderRadius: 7, border: "1px solid var(--line)", background: "var(--bg-2)", color: "var(--ink-1)", fontSize: 12, fontWeight: 600, textDecoration: "none" }}>
          ← Открыть в таймлайне планов
        </a>
      </div>
    </div>
  );
}

function KV({ label, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
      <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".06em" }}>{label}</span>
      <span className="mono tnum" style={{ fontSize: 12.5, color: "var(--ink)" }}>{children}</span>
    </div>
  );
}

Object.assign(window, { MapDetails });
