// Page 6 — Tasks History (timeline)

function TasksPage() {
  const [moduleFilter, setModuleFilter] = useState("all");
  const [agentFilter, setAgentFilter] = useState("all");
  const [periodFilter, setPeriodFilter] = useState("week");
  const [problemsOnly, setProblemsOnly] = useState(false);
  const [selected, setSelected] = useState(49); // PB-49 selected by default

  const modules = useMemo(() => {
    const s = new Set(TASKS.map(t => t.module));
    return Array.from(s);
  }, []);

  const filtered = useMemo(() => {
    const now = NOW.getTime();
    const cutoff =
      periodFilter === "day"   ? now - 24 * 3600 * 1000 :
      periodFilter === "week"  ? now - 7 * 24 * 3600 * 1000 :
      periodFilter === "month" ? now - 30 * 24 * 3600 * 1000 :
      0;
    return TASKS.filter(t => {
      if (cutoff && new Date(t.createdAt).getTime() < cutoff) return false;
      if (moduleFilter !== "all" && t.module !== moduleFilter) return false;
      if (agentFilter !== "all" && !t.agents.includes(agentFilter)) return false;
      if (problemsOnly && t.status === "ok") return false;
      return true;
    });
  }, [moduleFilter, agentFilter, periodFilter, problemsOnly]);

  const sortedByCreated = [...filtered].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));

  const selectedTask = TASKS.find(t => t.seq === selected) || filtered[0];

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">История задач</h1>
          <div className="page-sub">Жизненный цикл задач Plane. Кружки — задачи, цвет — наличие алертов.</div>
        </div>
      </div>

      {/* Filters */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ padding: "12px 16px", display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <FilterGroup label="Период">
            {["day","week","month","all"].map(p => (
              <button key={p} className={`tab ${periodFilter === p ? "active" : ""}`} onClick={() => setPeriodFilter(p)}>
                {{day:"День", week:"Неделя", month:"Месяц", all:"Всё"}[p]}
              </button>
            ))}
          </FilterGroup>
          <Sep />
          <FilterGroup label="Модуль">
            <select className="input mono" style={{ fontSize: 12 }} value={moduleFilter} onChange={(e) => setModuleFilter(e.target.value)}>
              <option value="all">все модули</option>
              {modules.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
          </FilterGroup>
          <Sep />
          <FilterGroup label="Агент">
            <select className="input" style={{ fontSize: 12 }} value={agentFilter} onChange={(e) => setAgentFilter(e.target.value)}>
              <option value="all">все агенты</option>
              {TEAM.map(t => <option key={t.id} value={t.id}>{t.name} ({t.role})</option>)}
            </select>
          </FilterGroup>
          <Sep />
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, cursor: "pointer" }}>
            <label className="toggle">
              <input type="checkbox" checked={problemsOnly} onChange={(e) => setProblemsOnly(e.target.checked)} />
              <span className="track" /><span className="thumb" />
            </label>
            Только проблемные
          </label>
          <div className="ml-auto muted" style={{ fontSize: 12 }}>В выборке: <span className="mono">{filtered.length}</span> / {TASKS.length}</div>
        </div>
      </div>

      {/* Timeline strip */}
      <div className="card" style={{ marginBottom: 16, overflow: "hidden" }}>
        <div className="card-hd">
          <h3>Timeline · {periodFilter === "day" ? "за сутки" : periodFilter === "week" ? "за неделю" : periodFilter === "month" ? "за месяц" : "за всё время"}</h3>
          <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 11 }}>
            <Legend color="var(--ok)" label="без инцидентов" />
            <Legend color="var(--info)" label="info" />
            <Legend color="var(--warn)" label="warning" />
            <Legend color="var(--crit)" label="critical" />
            <Legend color="#52525b" label="открыта" />
          </div>
        </div>
        <div style={{ padding: "20px 24px", overflowX: "auto" }}>
          <TaskTimeline tasks={sortedByCreated} selected={selected} onSelect={setSelected} />
        </div>
      </div>

      {/* Detail */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 16 }}>
        <div className="card">
          <div className="card-hd"><h3>Задачи в выборке</h3></div>
          <div style={{ maxHeight: 480, overflowY: "auto" }}>
            <table className="tbl">
              <tbody>
                {filtered.slice().reverse().map(t => (
                  <tr key={t.seq} className="clickable" onClick={() => setSelected(t.seq)} style={{
                    background: selected === t.seq ? "var(--surface-hi)" : "transparent",
                  }}>
                    <td style={{ width: 24, padding: "10px 6px 10px 14px" }}>
                      <span className="dot" style={{ background: statusColor(t.status) }} />
                    </td>
                    <td style={{ width: 64, padding: "10px 6px" }}>
                      <span className="mono" style={{ fontSize: 12, color: "var(--accent)" }}>PB-{t.seq}</span>
                    </td>
                    <td style={{ padding: "10px 6px" }}>
                      <div className="truncate" style={{ maxWidth: 320 }}>{t.title}</div>
                      <div style={{ display: "flex", gap: 4, marginTop: 4 }}>
                        <ModuleTag name={t.module} small />
                        <span className="mono muted" style={{ fontSize: 10, marginLeft: "auto" }}>{fmtDate(t.createdAt)}</span>
                      </div>
                    </td>
                    <td style={{ width: 56, padding: "10px 14px 10px 6px" }}>
                      <span className={`pill ${t.state === "Done" ? "ok" : "info"}`} style={{ fontSize: 10 }}>
                        {t.state}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {selectedTask && <TaskDetail task={selectedTask} />}
      </div>
    </div>
  );
}

function FilterGroup({ label, children }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <span className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</span>
      <div style={{ display: "flex", gap: 2 }}>{children}</div>
    </div>
  );
}
function Sep() { return <div style={{ width: 1, height: 18, background: "var(--border-soft)" }} />; }
function Legend({ color, label }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--text-muted)" }}>
      <span className="dot" style={{ background: color }} />
      {label}
    </span>
  );
}

function statusColor(s) {
  return s === "ok" ? "var(--ok)" :
         s === "info" ? "var(--info)" :
         s === "warn" ? "var(--warn)" :
         s === "crit" ? "var(--crit)" :
         "#52525b";
}

function TaskTimeline({ tasks, selected, onSelect }) {
  if (tasks.length === 0) return <div className="muted">Нет задач в выборке.</div>;

  // Group by date
  const groups = {};
  tasks.forEach(t => {
    const day = t.createdAt.slice(0, 10);
    (groups[day] = groups[day] || []).push(t);
  });
  const days = Object.keys(groups).sort();

  return (
    <div style={{ display: "flex", gap: 24, alignItems: "flex-end", minHeight: 110 }}>
      {days.map((d) => (
        <div key={d} style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "0 0 auto" }}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, justifyContent: "center", maxWidth: 240, marginBottom: 8 }}>
            {groups[d].map((t) => (
              <TimelineBubble key={t.seq} task={t} selected={selected === t.seq} onSelect={() => onSelect(t.seq)} />
            ))}
          </div>
          <div className="mono muted" style={{ fontSize: 11, paddingTop: 6, borderTop: "1px solid var(--border-soft)", paddingLeft: 12, paddingRight: 12 }}>
            {new Date(d).toLocaleDateString("ru-RU", { day: "2-digit", month: "short" })}
          </div>
        </div>
      ))}
    </div>
  );
}

function TimelineBubble({ task, selected, onSelect }) {
  const color = statusColor(task.status === "open" ? "open" : task.status);
  const size = task.status === "crit" ? 28 : task.status === "warn" ? 24 : 20;
  return (
    <button
      onClick={onSelect}
      title={`PB-${task.seq} · ${task.title}`}
      style={{
        width: size, height: size, borderRadius: "50%",
        background: color,
        border: selected ? "2px solid white" : "2px solid transparent",
        boxShadow: selected ? "0 0 0 2px var(--accent)" : "none",
        cursor: "pointer", padding: 0,
        opacity: task.state === "Done" ? 1 : 0.85,
        position: "relative",
      }}
    >
      <span style={{
        position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 9, fontFamily: "var(--font-mono)", color: "rgba(255,255,255,0.75)", fontWeight: 600,
        pointerEvents: "none",
      }}>{task.seq}</span>
    </button>
  );
}

function TaskDetail({ task }) {
  // Mock state transitions
  const transitions = useMemo(() => {
    const created = new Date(task.createdAt);
    const closed = task.closedAt ? new Date(task.closedAt) : null;
    const span = closed ? closed - created : NOW - created;
    const t = (ratio) => new Date(created.getTime() + span * ratio).toISOString();
    if (task.state === "Done") {
      return [
        { state: "Backlog", at: task.createdAt, by: task.agents[0] },
        { state: "Todo", at: t(0.1), by: task.agents[0] },
        { state: "In Progress", at: t(0.25), by: task.agents[1] || task.agents[0] },
        { state: "In Review", at: t(0.7), by: task.agents[2] || task.agents[0] },
        { state: "Done", at: task.closedAt, by: task.agents[2] || task.agents[0] },
      ];
    }
    return [
      { state: "Backlog", at: task.createdAt, by: task.agents[0] },
      { state: "Todo", at: t(0.3), by: task.agents[0] },
      { state: "In Progress", at: t(0.7), by: task.agents[1] || task.agents[0] },
    ];
  }, [task.seq]);

  const taskAlerts = ALERTS.filter(a => a.seq === task.seq);
  const taskEvents = EVENTS.filter(e => e.seq === task.seq);

  return (
    <div className="card">
      <div className="card-hd">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span className="dot" style={{ background: statusColor(task.status === "open" ? "open" : task.status), width: 12, height: 12 }} />
          <h3>PB-{task.seq} · {task.title}</h3>
        </div>
        <button className="btn btn-primary">Открыть в Plane ↗</button>
      </div>
      <div className="card-bd">
        <div style={{ display: "flex", gap: 16, fontSize: 12, color: "var(--text-muted)", marginBottom: 16 }}>
          <span>Создана: <span className="mono">{fmtDateTime(task.createdAt)}</span></span>
          {task.closedAt && <span>Закрыта: <span className="mono">{fmtDateTime(task.closedAt)}</span></span>}
          <ModuleTag name={task.module} small />
          <span className="ml-auto pill neutral" style={{ fontSize: 10 }}>state: {task.state}</span>
        </div>

        <div style={{ marginBottom: 16 }}>
          <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Переходы состояний</div>
          <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
            {transitions.map((tr, i) => (
              <React.Fragment key={i}>
                <div style={{ flex: 1, textAlign: "center" }}>
                  <div style={{
                    padding: "6px 8px", borderRadius: 6,
                    background: i === transitions.length - 1 && task.state === "Done" ? "rgba(34,197,94,0.12)" : "var(--bg-elev)",
                    border: "1px solid var(--border-soft)",
                    fontSize: 12, fontWeight: 500,
                    color: i === transitions.length - 1 && task.state === "Done" ? "var(--ok)" : "var(--text)",
                  }}>{tr.state}</div>
                  <div className="mono muted" style={{ fontSize: 10, marginTop: 4 }}>{fmtTime(tr.at)}</div>
                </div>
                {i < transitions.length - 1 && (
                  <div style={{ color: "var(--text-muted)", fontSize: 12 }}>›</div>
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Кто работал</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {task.agents.map(aid => {
                const a = teamById(aid);
                if (!a) return null;
                return (
                  <div key={aid} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Avatar agentId={aid} size={22} />
                    <span style={{ fontSize: 12 }}>{a.name}</span>
                    <span className="muted" style={{ fontSize: 11 }}>{a.roleLabel}</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Сработавшие алерты</div>
            {taskAlerts.length === 0 ? (
              <div style={{ fontSize: 12, color: "var(--ok)" }}>● Без инцидентов</div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {taskAlerts.map(a => (
                  <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                    <SeverityChip severity={a.severity} />
                    <span className="dim">{a.ruleTitle}</span>
                    <span className="mono muted" style={{ marginLeft: "auto", fontSize: 10 }}>{fmtTime(a.ts)}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {taskEvents.length > 0 && (
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>События</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {taskEvents.map((ev, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "62px 18px 1fr auto", gap: 8, alignItems: "center", padding: "4px 0", fontSize: 12, color: "var(--text-dim)" }}>
                  <span className="mono muted" style={{ fontSize: 11 }}>{fmtTime(ev.ts)}</span>
                  <span style={{ color: kindColor(ev.kind) }}><KindIcon kind={ev.kind} /></span>
                  <span>{ev.text}</span>
                  <span className="mono muted" style={{ fontSize: 10, textTransform: "uppercase" }}>{kindLabel(ev.kind)}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.TasksPage = TasksPage;
