// Partitura — right-side events panel.
// Filters events by visible time window AND by selected row key.
// Selection key format:
//   - "agent:<agentId>"
//   - "module:<moduleName>"
//   - "module:<moduleName>/agent:<agentId>"

function EventsPanel({
  width,
  events,             // visible-events union from all rows
  rows,               // current rows array (for resolving label/avatar)
  selectedKey,        // string|null
  setSelectedKey,
  visRange,           // [startMin, endMin]
  mode,               // "agents" | "modules"
  period,             // "day" | "week" | "month" | "year"
  selectedSeg,        // { seg, rowKey } | null
  onClearSeg,
  highlightEventKey,
  agents,             // TEAM
  stickyTop = 96,
}) {
  const listRef = React.useRef(null);

  const isDay = period === "day";

  // Module lookup for an event (resolve via owner segment's module)
  const evModule = (ev) => {
    const segs = window.PT_AGENT_SEGMENTS || {};
    const owner = (segs[ev.agent] || []).find((s) => s.seq === ev.seq);
    return owner ? owner.module : null;
  };

  // Parse selection key
  const sel = React.useMemo(() => {
    if (!selectedKey) return { kind: "none" };
    if (selectedKey.startsWith("agent:")) {
      return { kind: "agent", agentId: selectedKey.slice("agent:".length) };
    }
    if (selectedKey.startsWith("module:")) {
      const tail = selectedKey.slice("module:".length);
      const i = tail.indexOf("/agent:");
      if (i >= 0) {
        return { kind: "module-agent", moduleName: tail.slice(0, i), agentId: tail.slice(i + "/agent:".length) };
      }
      return { kind: "module", moduleName: tail };
    }
    return { kind: "none" };
  }, [selectedKey]);

  // Filter
  const inWindow = (ev) => !isDay || (ev.t >= visRange[0] && ev.t <= visRange[1]);
  let filtered = events.filter(inWindow);
  if (sel.kind === "agent") {
    filtered = filtered.filter((ev) => ev.agent === sel.agentId);
  } else if (sel.kind === "module") {
    filtered = filtered.filter((ev) => evModule(ev) === sel.moduleName);
  } else if (sel.kind === "module-agent") {
    filtered = filtered.filter((ev) => ev.agent === sel.agentId && evModule(ev) === sel.moduleName);
  }
  filtered.sort((a, b) => a.t - b.t);

  // Scroll selected event into view
  React.useEffect(() => {
    if (!highlightEventKey || !listRef.current) return;
    const el = listRef.current.querySelector(`[data-ev-key="${highlightEventKey}"]`);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
  }, [highlightEventKey]);

  // Resolve display info for the header
  const headerInfo = React.useMemo(() => {
    if (sel.kind === "none") return null;
    if (sel.kind === "agent") {
      const a = (agents || []).find((x) => x.id === sel.agentId);
      return a ? { title: a.name, sub: a.roleLabel, avatar: a.avatar, kind: "agent" } : null;
    }
    if (sel.kind === "module") {
      return { title: sel.moduleName, sub: "модуль", color: window.moduleColor(sel.moduleName), kind: "module" };
    }
    if (sel.kind === "module-agent") {
      const a = (agents || []).find((x) => x.id === sel.agentId);
      return a ? {
        title: a.name,
        sub: `модуль ${sel.moduleName}`,
        avatar: a.avatar,
        color: window.moduleColor(sel.moduleName),
        kind: "module-agent",
      } : null;
    }
    return null;
  }, [sel, agents]);

  return (
    <aside className="pt-panel" style={{ width, flex: `0 0 ${width}px`, top: stickyTop, maxHeight: `calc(100vh - ${stickyTop}px)` }}>
      <div className="pt-panel-hd">
        <div className="pt-panel-title">
          {headerInfo ? (
            <div className="pt-panel-selected">
              {headerInfo.kind === "module" ? (
                <div className="pt-panel-mod-badge" style={{
                  background: `${headerInfo.color}22`,
                  borderColor: headerInfo.color,
                  color: headerInfo.color,
                }}>{headerInfo.title[0].toUpperCase()}</div>
              ) : (
                <div className="pt-panel-avatar" style={{ backgroundImage: `url(${headerInfo.avatar})` }} />
              )}
              <div>
                <div className="pt-panel-name">{headerInfo.title}</div>
                <div className="pt-panel-sub">{headerInfo.sub}</div>
              </div>
              <button className="pt-clear-btn" onClick={() => setSelectedKey(null)} title="Сбросить выбор">×</button>
            </div>
          ) : (
            <>
              <div className="pt-panel-name">Все события</div>
              <div className="pt-panel-sub">
                {isDay ? "клик по треку фильтрует панель" : "период: " + window.periodDef(period).label.toLowerCase()}
              </div>
            </>
          )}
        </div>

        <div className="pt-panel-meta">
          {isDay ? (
            <span className="pt-window">окно <span className="mono">{fmtHM(visRange[0])} — {fmtHM(visRange[1])}</span></span>
          ) : (
            <span className="pt-window">{window.periodDef(period).days} дн.</span>
          )}
          <span className="pt-count">
            <strong>{filtered.length}</strong>
            <span className="pt-count-lbl">соб.</span>
          </span>
        </div>

        {filtered.length > 0 && <PanelBreakdown events={filtered} />}
      </div>

      {selectedSeg && (
        <SelectedSegBlock seg={selectedSeg.seg} onClear={onClearSeg} />
      )}

      <div className="pt-panel-list" ref={listRef}>
        {filtered.length === 0 ? (
          <PanelEmpty hasSelection={sel.kind !== "none"} />
        ) : (
          filtered.map((ev) => {
            const evKey = `${ev.t}_${ev.agent}_${ev.kind}_${ev.seq}`;
            const isHl = highlightEventKey === evKey;
            return (
              <PtEventRow key={evKey} ev={ev} evKey={evKey} isHighlight={isHl}
                showAgent={sel.kind === "module" || sel.kind === "none"}
                agents={agents} />
            );
          })
        )}
      </div>
    </aside>
  );
}

function PanelBreakdown({ events }) {
  const counts = {};
  events.forEach((e) => { counts[e.kind] = (counts[e.kind] || 0) + 1; });
  const order = window.EVENT_KINDS_ORDER || [];
  return (
    <div className="pt-breakdown">
      {order.filter((k) => counts[k]).map((k) => (
        <span key={k} className="pt-breakdown-item" title={window.EVENT_LABELS[k]}>
          <EventIcon kind={k} sev="warning" size={11} />
          <span className="mono">{counts[k]}</span>
        </span>
      ))}
    </div>
  );
}

function SelectedSegBlock({ seg, onClear }) {
  const style = window.STATE_STYLES[seg.state];
  return (
    <div className="pt-seg-card">
      <div className="pt-seg-card-hd">
        <span className="pt-seg-card-lbl">выбран фрагмент</span>
        <button className="pt-clear-btn pt-clear-btn-sm" onClick={onClear} title="Снять выбор">×</button>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 4, flexWrap: "wrap" }}>
        <span style={{
          padding: "2px 7px", borderRadius: 3, fontSize: 10, fontWeight: 600,
          textTransform: "uppercase", letterSpacing: "0.05em",
          color: style.color, background: style.bg,
          border: `1px solid ${style.border}`,
        }}>{style.label}</span>
        <span className="mono" style={{ fontSize: 11, color: "var(--accent)", fontWeight: 600 }}>PB-{seg.seq}</span>
        <span style={{
          fontSize: 10, fontFamily: "var(--font-mono)",
          color: window.moduleColor(seg.module),
          padding: "1px 6px",
          background: "transparent",
          border: `1px solid ${window.moduleColor(seg.module)}66`,
          borderRadius: 3,
        }}>{seg.module}</span>
      </div>
      <div className="pt-seg-title">{seg.title}</div>
      <div className="pt-seg-meta mono">
        {fmtHM(seg.start)} — {fmtHM(seg.end)}
        <span className="pt-sep">·</span>
        {Math.round(seg.end - seg.start)} мин
      </div>
    </div>
  );
}

function PtEventRow({ ev, evKey, isHighlight, showAgent, agents }) {
  const agent = ev.agent ? (agents || []).find((a) => a.id === ev.agent) : null;
  return (
    <div className={"pt-ev-row" + (isHighlight ? " is-highlight" : "")} data-ev-key={evKey}>
      <div className="pt-ev-icon">
        <EventIcon kind={ev.kind} sev={ev.sev} size={14} />
      </div>
      <div className="pt-ev-bd">
        <div className="pt-ev-meta">
          <span className="mono pt-ev-time">{fmtHM(ev.t)}</span>
          <span className="mono pt-ev-seq">PB-{ev.seq}</span>
          {showAgent && agent && (
            <span className="pt-ev-agent" title={agent.name}>
              <span className="pt-ev-avatar" style={{ backgroundImage: `url(${agent.avatar})` }} />
              {agent.name}
            </span>
          )}
          {ev.kind === "alert" && ev.sev && (
            <span className={"pt-ev-sev pt-ev-sev-" + ev.sev}>{ev.sev}</span>
          )}
        </div>
        <div className="pt-ev-text">{ev.text}</div>
      </div>
    </div>
  );
}

function PanelEmpty({ hasSelection }) {
  return (
    <div className="pt-empty">
      <div className="pt-empty-glyph">∅</div>
      <div className="pt-empty-msg">
        {hasSelection ? "Нет событий для выбранного трека в этом окне." : "В видимом окне нет событий."}
      </div>
    </div>
  );
}

window.EventsPanel = EventsPanel;
