// Правая панель деталей выбранного интервала + лента родословной (предки/потомки).
function StatusBadge({ 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 Field({ label, children, mono }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
      <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>{label}</span>
      <span className={mono ? "mono tnum" : ""} style={{ fontSize: 12.5, color: "var(--ink)" }}>{children}</span>
    </div>
  );
}

function Details({ iv, sc, group, byId, onSelectIv, onClose }) {
  if (!iv) {
    return (
      <div style={{ height: "100%", background: "var(--bg-1)", borderLeft: "1px solid var(--line)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 10, padding: 24, textAlign: "center" }}>
        <svg width="34" height="34" viewBox="0 0 24 24" fill="none" style={{ opacity: .3 }}><rect x="3" y="6" width="18" height="3.4" rx="1.5" stroke="var(--ink-2)" strokeWidth="1.6" /><rect x="3" y="13" width="11" height="3.4" rx="1.5" stroke="var(--ink-2)" strokeWidth="1.6" /></svg>
        <div style={{ fontSize: 12, color: "var(--ink-3)", maxWidth: 180 }}>Выберите план на таймлайне, чтобы увидеть его работы и цепочку ревизий.</div>
      </div>
    );
  }
  const lin = lineageOf(iv.id, byId);
  const dur = iv.end - iv.start;
  const col = TYPE_COLOR[sc.type];

  const chainRow = (id) => {
    const it = byId[id];
    const isSel = id === iv.id;
    return (
      <button key={id} onClick={() => onSelectIv(id)} style={{
        display: "flex", alignItems: "center", gap: 8, width: "100%", textAlign: "left",
        padding: "7px 9px", borderRadius: 6, border: `1px solid ${isSel ? "var(--accent)" : "var(--line-soft)"}`,
        background: isSel ? "oklch(0.82 0.13 200 / 0.12)" : "var(--bg-2)",
      }}>
        <span className="mono tnum" style={{ fontSize: 9.5, color: "var(--ink-3)", flex: "none" }}>{it.id}</span>
        <span style={{ flex: 1, fontSize: 11.5, color: isSel ? "var(--ink)" : "var(--ink-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.title}</span>
        <span className="mono" style={{ fontSize: 8.5, color: "var(--ink-3)", border: "1px solid var(--line)", borderRadius: 3, padding: "0 4px", flex: "none" }}>r{it.rev}</span>
      </button>
    );
  };

  return (
    <div style={{ height: "100%", background: "var(--bg-1)", borderLeft: "1px solid var(--line)", display: "flex", flexDirection: "column" }}>
      <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)" }}>{iv.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: 17, fontWeight: 700, marginTop: 8, lineHeight: 1.2 }}>{iv.title}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 9 }}>
          <StatusBadge status={iv.status} />
          <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-2)" }}>{sc.short} · {group.name}</span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: "14px 16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
        {/* Время */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="НАЧАЛО" mono>{fmtDateTime(iv.start)}</Field>
          <Field label="КОНЕЦ" mono>{fmtDateTime(iv.end)}</Field>
          <Field label="ДЛИТЕЛЬНОСТЬ" mono>{fmtDur(dur)}</Field>
          <Field label="РАБОТ В ПЛАНЕ" mono>{iv.works.length}</Field>
        </div>

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

        {/* Аппарат */}
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>АППАРАТ</span>
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <TypeDot type={sc.type} size={9} />
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{sc.name}</div>
              <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{D.TYPES[sc.type].label} · {sc.orbit}</div>
            </div>
          </div>
          <Field label="ИСТОЧНИК ПЛАНА">{iv.author}</Field>
        </div>

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

        {/* Работы внутри плана */}
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>РАБОТЫ В ПЛАНЕ</span>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)" }}>{iv.works.length}</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
            {iv.works.length === 0 && <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Работы не заданы.</div>}
            {iv.works.map((wk) => {
              const fill = workFill(wk.kind, sc.type);
              const isService = wk.kind === "service";
              return (
                <div key={wk.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 8px", borderRadius: 6, background: "var(--bg-2)" }}>
                  <span style={{ width: 9, height: 9, borderRadius: 2, flex: "none", background: isService ? "transparent" : fill, border: isService ? `1px dashed ${fill}` : "none" }} />
                  <span style={{ flex: 1, fontSize: 11.5, color: "var(--ink-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{wk.label}</span>
                  <span className="mono tnum" style={{ fontSize: 10, color: "var(--ink-3)", flex: "none" }}>{fmtTime(wk.start)}–{fmtTime(wk.end)}</span>
                </div>
              );
            })}
          </div>
        </div>

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

        {/* Родословная */}
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em" }}>РОДОСЛОВНАЯ ПЛАНА</span>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)" }}>{lin.chain.length} ревизий</span>
          </div>

          {lin.ancestors.length > 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 9.5, color: "var(--ink-3)" }}>◀ Предки</span>
              {lin.ancestors.map(chainRow)}
            </div>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
            <span style={{ fontSize: 9.5, color: "var(--accent)" }}>● Текущий</span>
            {chainRow(iv.id)}
          </div>

          {lin.descendants.length > 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 9.5, color: "var(--ink-3)" }}>▶ Потомки</span>
              {lin.descendants.map(chainRow)}
            </div>
          )}

          {lin.ancestors.length === 0 && lin.descendants.length === 0 && (
            <div style={{ fontSize: 11, color: "var(--ink-3)", padding: "4px 0" }}>Это единственная ревизия плана — без предков и потомков.</div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Details });
