// kanban-page.jsx — Канбан-режим задач

function KanbanPage({ tasks, onOpenTask, onToggle, setTasks, onAddTask, onNewVisit }) {
  const team = window.DATA.TEAM;
  const objects = window.DATA.OBJECTS;
  const [filterAssignee, setFilterAssignee] = React.useState("all");
  const [filterObj, setFilterObj] = React.useState("all");

  let filtered = tasks;
  if (filterAssignee !== "all") filtered = filtered.filter(t => t.assignee === filterAssignee);
  if (filterObj !== "all") filtered = filtered.filter(t => t.obj === filterObj);

  const columns = [
    { id: "todo", label: "To Do",      color: "var(--ink-3)",       tone: "neutral" },
    { id: "live", label: "У роботі",   color: "var(--c-green-deep)", tone: "live" },
    { id: "late", label: "Прострочено",color: "var(--late)",        tone: "warn" },
    { id: "done", label: "Виконано",   color: "var(--c-green)",     tone: "live" },
  ];

  const byStatus = {};
  columns.forEach(c => byStatus[c.id] = filtered.filter(t => t.status === c.id));

  const moveTask = (taskId, newStatus) => {
    setTasks(prev => prev.map(t => t.id === taskId ? { ...t, status: newStatus } : t));
  };

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Канбан</h1>
        <div className="page-sub">
          <span>{filtered.length} {window.plural(filtered.length, "задача", "задачі", "задач")}</span>
          {filterAssignee !== "all" && <>
            <span className="dot"></span>
            <span>фільтр: {team.find(p => p.id === filterAssignee)?.name}</span>
          </>}
          {filterObj !== "all" && <>
            <span className="dot"></span>
            <span>об'єкт: {objects.find(o => o.id === filterObj)?.code}</span>
          </>}
        </div>
      </div>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${filterAssignee === "all" ? "is-active" : ""}`} onClick={() => setFilterAssignee("all")}>
            Уся команда
          </button>
          {team.map(p => (
            <button
              key={p.id}
              className={`filter-pill-item ${filterAssignee === p.id ? "is-active" : ""}`}
              onClick={() => setFilterAssignee(p.id)}
            >
              <span className="av" style={{width: 22, height: 22, fontSize: 9.5, border: "none"}}>{p.initials[0]}</span>
              {p.initials}
            </button>
          ))}
        </div>

        <select
          className="select-pill"
          value={filterObj}
          onChange={(e) => setFilterObj(e.target.value)}
          style={{marginLeft: "auto"}}
        >
          <option value="all">Усі об'єкти</option>
          {objects.map(o => (
            <option key={o.id} value={o.id}>{o.code} · {o.name}</option>
          ))}
        </select>
        {onNewVisit && <button className="btn btn-sm" onClick={onNewVisit} style={{marginLeft: 10, whiteSpace: "nowrap"}}>
          <window.Ico name="mapPin" size={15} /> Запланувати виїзд
        </button>}
      </div>

      <div className="kanban-board">
        {columns.map(col => {
          const list = byStatus[col.id];
          const total = list.reduce((s, t) => s + parseFloat(String(t.est || "0")) || 0, 0);
          return (
            <div key={col.id} className="kanban-col">
              <div className="kanban-col-head">
                <span className="kanban-col-title" style={{color: col.color}}>{col.label}</span>
                <span className="kanban-col-count">{list.length}</span>
              </div>
              <div className="kanban-col-list">
                {list.length === 0
                  ? <div className="kanban-empty">—</div>
                  : list.map(task => (
                    <KanbanCard
                      key={task.id}
                      task={task}
                      onOpen={() => onOpenTask(task)}
                      onMove={(newStatus) => moveTask(task.id, newStatus)}
                      columns={columns}
                    />
                  ))
                }
              </div>
              <button className="kanban-add" onClick={() => onAddTask && onAddTask({ status: col.id, objId: filterObj !== "all" ? filterObj : "" })}>
                <window.Icon.Plus /> Додати задачу
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function KanbanCard({ task, onOpen, onMove, columns }) {
  const obj = window.getObject(task.obj);
  const ids = task.assignees && task.assignees.length ? task.assignees : (task.assignee ? [task.assignee] : []);
  const people = ids.map(id => window.getTeam(id)).filter(Boolean);
  const cls = task.status === "late" ? "is-late" : task.status === "live" ? "is-live" : task.status === "done" ? "is-done" : "";

  return (
    <div className={`kanban-card ${cls}`} onClick={onOpen}>
      <div className="kanban-card-title">{task.title}</div>
      <div className="kanban-card-meta">
        {task.kind === "visit" && window.VisitTypeBadge && <window.VisitTypeBadge typeId={task.visit?.typeId} small={true} />}
        {obj && <span className="td-mono" style={{fontSize: 10.5, color: "var(--ink-3)"}}>{obj.code}</span>}
        {task.section && <>
          <span className="dot" style={{width: 3, height: 3, borderRadius: "50%", background: "var(--ink-4)", display: "inline-block"}}></span>
          <span style={{fontSize: 11, color: "var(--ink-3)"}}>{task.section}</span>
        </>}
      </div>
      <div className="kanban-card-foot">
        {task.est && <span style={{fontSize: 11, color: "var(--ink-2)", fontVariantNumeric: "tabular-nums", display: "inline-flex", alignItems: "center", gap: 4}}><window.Ico name="clock" size={13} /> {task.est}</span>}
        {people.length > 0 && <div className="kanban-avatars" style={{marginLeft: "auto"}}>
          {people.slice(0, 3).map((p, i) => (
            <div key={i} className="team-avatar" style={{width: 24, height: 24, fontSize: 9}} title={p.name}>{p.initials}</div>
          ))}
          {people.length > 3 && <div className="team-avatar team-avatar-more" style={{width: 24, height: 24, fontSize: 9}}>+{people.length - 3}</div>}
        </div>}
      </div>
      {/* Status quick-move */}
      <div className="kanban-card-actions">
        {columns.filter(c => c.id !== task.status).map(c => (
          <button
            key={c.id}
            onClick={(e) => { e.stopPropagation(); onMove(c.id); }}
            title={"→ " + c.label}
          >
            <window.Ico name={c.id === "todo" ? "circle" : c.id === "live" ? "play" : c.id === "late" ? "alert" : "check"} size={13} />
          </button>
        ))}
      </div>
    </div>
  );
}

window.KanbanPage = KanbanPage;
