// Страница «Карта»: вкладки, левые контролы (охват/слои/выбор КА), детали, ?plan=.
const { useState: useStateMA, useMemo: useMemoMA, useEffect: useEffectMA } = React;

const HOUR_MS = 3600000, DAY_MS = 86400000;
const PLAN_PAGE = "План КА — Mission Ops.html";

function MapApp() {
  const byId = useMemoMA(() => { const m = {}; D.plans.forEach(p => m[p.id] = p); return m; }, []);
  const scById = useMemoMA(() => { const m = {}; D.spacecraft.forEach(s => m[s.id] = s); return m; }, []);
  const ivBySc = useMemoMA(() => { const m = {}; D.plans.forEach(p => (m[p.scId] = m[p.scId] || []).push(p)); return m; }, []);
  const paramsBy = useMemoMA(() => { const m = {}; D.spacecraft.forEach(s => m[s.id] = orbitParams(s)); return m; }, []);

  // начальное состояние из URL
  const urlParams = new URLSearchParams(location.search);
  const urlPlan = urlParams.get("plan");
  const urlSc = urlParams.get("sc");
  const initPlan = urlPlan && byId[urlPlan] ? urlPlan : null;
  const initSc = initPlan ? byId[initPlan].scId : (urlSc && scById[urlSc] ? urlSc : D.spacecraft[0].id);

  const [scope, setScope] = useStateMA(initPlan || urlSc ? "one" : "one");
  const [selSc, setSelSc] = useStateMA(initSc);
  const [selPlan, setSelPlan] = useStateMA(initPlan);
  const [search, setSearch] = useStateMA("");
  const [layers, setLayers] = useStateMA({ tracks: true, swath: true, shoot: true, downlink: true, stations: true, terminator: true });
  const [basemap, setBasemap] = useStateMA("dark");

  const sc = scById[selSc];
  const plan = selPlan ? byId[selPlan] : null;

  // окно времени
  const win = useMemoMA(() => {
    if (plan) return { t0: plan.start, t1: Math.min(plan.end, plan.start + 3 * DAY_MS) };
    return { t0: D.NOW - 3 * HOUR_MS, t1: D.NOW + 9 * HOUR_MS };
  }, [plan]);

  // список КА в охвате
  const scList = useMemoMA(() => {
    if (scope === "one") return [sc];
    if (scope === "group") return D.spacecraft.filter(s => s.groupId === sc.groupId);
    return D.spacecraft;
  }, [scope, sc]);

  const toggleLayer = (k) => setLayers(l => ({ ...l, [k]: !l[k] }));

  const onSelectSc = (id) => { setSelSc(id); setSelPlan(null); if (scope === "all") setScope("group"); };
  const onSelectPlan = (id) => { const p = byId[id]; setSelSc(p.scId); setSelPlan(id); setScope("one"); };

  // фильтр выбора КА
  const q = search.trim().toLowerCase();
  const scResults = useMemoMA(() => D.spacecraft.filter(s => !q || s.name.toLowerCase().includes(q) || s.short.toLowerCase().includes(q)), [q]);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100vh" }}>
      <TopTabs active="map" planHref={PLAN_PAGE} />

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: `288px 1fr ${plan ? "330px" : "0px"}`, minHeight: 0, transition: "grid-template-columns .18s" }}>
        {/* ЛЕВЫЕ КОНТРОЛЫ */}
        <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.5, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 7 }}>ПОДЛОЖКА</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: "6px 0", borderRadius: 5, border: "none", fontSize: 11.5, fontWeight: 600, background: basemap === id ? "var(--bg-3)" : "transparent", color: basemap === id ? "var(--ink)" : "var(--ink-3)" }}>{lab}</button>
              ))}
            </div>
          </div>

          {/* охват */}
          <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--line-soft)" }}>
            <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 7 }}>ОХВАТ</div>
            <div style={{ display: "flex", gap: 3, background: "var(--bg-0)", borderRadius: 7, padding: 3, border: "1px solid var(--line)" }}>
              {[["one", "1 КА"], ["group", "Группа"], ["all", "Все"]].map(([id, lab]) => (
                <button key={id} onClick={() => setScope(id)} style={{ flex: 1, padding: "6px 0", borderRadius: 5, border: "none", fontSize: 11.5, fontWeight: 600, background: scope === id ? "var(--bg-3)" : "transparent", color: scope === id ? "var(--ink)" : "var(--ink-3)" }}>{lab}</button>
              ))}
            </div>
            <div style={{ marginTop: 8, fontSize: 11, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 6 }}>
              <TypeDot type={sc.type} size={8} />
              <span className="mono">{sc.short}</span>
              <span style={{ color: "var(--ink-3)" }}>· {D.GROUP_DEFS.find(g => g.id === sc.groupId).name}</span>
            </div>
          </div>

          {/* окно времени */}
          <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--line-soft)" }}>
            <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 5 }}>ОКНО ВРЕМЕНИ</div>
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-1)" }}>{fmtDateTime(win.t0)} → {fmtDateTime(win.t1)}</div>
            <div style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 3 }}>{plan ? `план ${plan.id}` : "сутки вокруг «сейчас»"}</div>
          </div>

          {/* слои */}
          <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--line-soft)" }}>
            <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 7 }}>СЛОИ</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <LayerRow on={layers.tracks} onClick={() => toggleLayer("tracks")} swatch={<LineSwatch />} label="Трассы КА" />
              <LayerRow on={layers.swath} onClick={() => toggleLayer("swath")} swatch={<BandSwatch />} label="Полосы обзора (swath)" />
              <LayerRow on={layers.shoot} onClick={() => toggleLayer("shoot")} swatch={<PolySwatch />} label="Контуры маршрутов съёмки" />
              <LayerRow on={layers.downlink} onClick={() => toggleLayer("downlink")} swatch={<DownSwatch />} label="Участки сброса" />
              <LayerRow on={layers.stations} onClick={() => toggleLayer("stations")} swatch={<StationSwatch />} label="Станции приёма (НКПОР)" />
              <LayerRow on={layers.terminator} onClick={() => toggleLayer("terminator")} swatch={<NightSwatch />} label="Терминатор день/ночь" />
            </div>
          </div>

          {/* выбор КА */}
          <div style={{ padding: "10px 14px 6px" }}>
            <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)", letterSpacing: ".1em", marginBottom: 6 }}>АППАРАТ В ФОКУСЕ</div>
            <div style={{ position: "relative" }}>
              <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Поиск КА…"
                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, outline: "none" }} />
            </div>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: "4px 8px 12px" }}>
            {scResults.map((s) => (
              <div key={s.id} onClick={() => onSelectSc(s.id)}
                style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 8px", borderRadius: 6, cursor: "pointer", background: s.id === selSc ? "var(--bg-3)" : "transparent" }}>
                <TypeDot type={s.type} size={7} />
                <span className="mono" style={{ flex: 1, fontSize: 11, color: s.id === selSc ? "var(--ink)" : "var(--ink-1)" }}>{s.short}</span>
                <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)" }}>{(ivBySc[s.id] || []).length} пл.</span>
              </div>
            ))}
          </div>
        </div>

        {/* КАРТА */}
        <div style={{ position: "relative", minWidth: 0 }}>
          <MapView scList={scList} selectedPlan={plan} window={win} now={D.NOW} layers={layers}
            onSelectSc={onSelectSc} paramsBy={paramsBy} scById={scById} basemap={basemap} />
          {/* плашка масштаба/охвата */}
          <div style={{ position: "absolute", left: 12, top: 12, display: "flex", gap: 8, alignItems: "center", background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: 7, padding: "6px 10px" }}>
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>ОХВАТ:</span>
            <span style={{ fontSize: 11.5, fontWeight: 600 }}>{scope === "one" ? "1 КА" : scope === "group" ? "Группа" : "Все"}</span>
            <span style={{ width: 1, height: 14, background: "var(--line)" }} />
            <span className="mono tnum" style={{ fontSize: 11.5, color: "var(--ink-1)" }}>{scList.length} КА</span>
          </div>
        </div>

        {/* ДЕТАЛИ ПЛАНА */}
        {plan && <MapDetails plan={plan} sc={scById[plan.scId]} params={paramsBy[plan.scId]} byId={byId} onSelectPlan={onSelectPlan} onClose={() => setSelPlan(null)} planPage={PLAN_PAGE} />}
      </div>
    </div>
  );
}

function LayerRow({ on, onClick, swatch, label }) {
  return (
    <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 6px", borderRadius: 6, border: "1px solid transparent", background: on ? "var(--bg-2)" : "transparent", opacity: on ? 1 : 0.4, textAlign: "left" }}>
      <span style={{ width: 18, flex: "none", display: "grid", placeItems: "center" }}>{swatch}</span>
      <span style={{ flex: 1, fontSize: 11.5, color: "var(--ink-1)" }}>{label}</span>
      <span style={{ width: 14, height: 14, borderRadius: 4, flex: "none", 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>
    </button>
  );
}
const LineSwatch = () => <svg width="18" height="10"><path d="M0 8 Q6 0 12 5 T18 3" stroke="var(--t-optical)" strokeWidth="1.4" fill="none" /></svg>;
const BandSwatch = () => <svg width="18" height="10"><path d="M0 8 Q6 0 12 5 T18 3" stroke="var(--t-optical)" strokeWidth="5" fill="none" opacity="0.25" /></svg>;
const PolySwatch = () => <svg width="18" height="10"><rect x="2" y="2" width="14" height="6" fill="color-mix(in oklch, var(--t-optical) 30%, transparent)" stroke="var(--t-optical)" strokeWidth="1" /></svg>;
const DownSwatch = () => <svg width="18" height="10"><path d="M1 5 H17" stroke="var(--accent)" strokeWidth="3" strokeLinecap="round" /></svg>;
const StationSwatch = () => <svg width="18" height="10"><path d="M9 1 L13 8 L5 8 Z" fill="rgba(180,200,210,0.9)" /></svg>;
const NightSwatch = () => <svg width="18" height="10"><rect x="0" y="0" width="9" height="10" fill="rgba(4,8,12,0.6)" /><rect x="9" y="0" width="9" height="10" fill="#15291f" /></svg>;

ReactDOM.createRoot(document.getElementById("root")).render(<MapApp />);
