// ─── TASKS — Table View ────────────────────────────────────
const TasksScreen = () => {
  const [groupBy, setGroupBy] = React.useState("status");
  const [filterTag, setFilterTag] = React.useState("all");
  const [filterAssignee, setFilterAssignee] = React.useState("all");
  const [sortBy, setSortBy] = React.useState("due");

  let tasks = [...window.TASKS];
  if (filterTag !== "all") tasks = tasks.filter(t => t.tag === filterTag);
  if (filterAssignee !== "all") tasks = tasks.filter(t => t.assignees.includes(filterAssignee));

  // sort within groups
  tasks.sort((a, b) => {
    if (sortBy === "due") return a.due.localeCompare(b.due);
    if (sortBy === "prio") {
      const order = { high: 0, med: 1, low: 2 };
      return order[a.prio] - order[b.prio];
    }
    if (sortBy === "id") return a.id.localeCompare(b.id);
    return 0;
  });

  // group
  const groups = {};
  if (groupBy === "status") {
    window.KB_COLUMNS.forEach(c => { groups[c.title] = []; });
    tasks.forEach(t => {
      const col = window.KB_COLUMNS.find(c => c.id === t.col);
      if (col) groups[col.title].push(t);
    });
  } else if (groupBy === "tag") {
    ["art","code","design","audio","narrative"].forEach(t => groups[t.toUpperCase()] = []);
    tasks.forEach(t => groups[t.tag.toUpperCase()].push(t));
  } else if (groupBy === "assignee") {
    window.TEAM.forEach(m => groups[m.name] = []);
    tasks.forEach(t => t.assignees.forEach(a => {
      const m = window.TEAM.find(x => x.id === a);
      if (m) groups[m.name].push(t);
    }));
  } else {
    groups["All tasks"] = tasks;
  }

  return (
    <div className="content-pad" data-screen-label="04 Tasks">
      <div className="page-head">
        <div>
          <div className="page-title display">Tasks</div>
          <div className="page-sub">Detailed list view · {window.TASKS.length} tasks · linked to wiki entries</div>
        </div>
        <div className="right">
          <button className="btn ghost small"><Icon name="link" size={12}/> Linked items</button>
          <button className="btn primary"><Icon name="plus" size={13}/> New task</button>
        </div>
      </div>

      <div className="tasks-toolbar">
        <span className="muted small" style={{ marginRight: 4 }}>Group:</span>
        {["status", "tag", "assignee", "none"].map(g => (
          <button key={g} className={`filter-btn ${groupBy === g ? "is-on" : ""}`} onClick={() => setGroupBy(g)}>{g}</button>
        ))}
        <div style={{ width: 12 }}/>
        <span className="muted small" style={{ marginRight: 4 }}>Tag:</span>
        {["all","art","code","design","audio","narrative"].map(t => (
          <button key={t} className={`filter-btn ${filterTag === t ? "is-on" : ""}`} onClick={() => setFilterTag(t)}>
            {t !== "all" && <span className="dot" style={{ width: 7, height: 7, borderRadius: 50, background: `var(--st-${t})` }}/>}
            {t}
          </button>
        ))}
        <div style={{ width: 12 }}/>
        <span className="muted small" style={{ marginRight: 4 }}>Assignee:</span>
        <button className={`filter-btn ${filterAssignee === "all" ? "is-on" : ""}`} onClick={() => setFilterAssignee("all")}>all</button>
        {window.TEAM.map(m => (
          <button key={m.id} className={`filter-btn ${filterAssignee === m.id ? "is-on" : ""}`} onClick={() => setFilterAssignee(m.id)}>
            <Avatar id={m.id} size={16}/> {m.name.split(" ")[0]}
          </button>
        ))}
        <div className="spacer"/>
        <span className="muted small" style={{ marginRight: 4 }}>Sort:</span>
        <select
          value={sortBy}
          onChange={e => setSortBy(e.target.value)}
          className="filter-btn"
          style={{ paddingRight: 22 }}
        >
          <option value="due">Due date</option>
          <option value="prio">Priority</option>
          <option value="id">ID</option>
        </select>
      </div>

      <table className="task-table">
        <thead>
          <tr>
            <th style={{ width: 28 }}/>
            <th style={{ width: 88 }}>ID</th>
            <th>Title</th>
            <th style={{ width: 100 }}>Tag</th>
            <th style={{ width: 70 }}>Prio</th>
            <th style={{ width: 80 }}>Due</th>
            <th style={{ width: 110 }}>Assignees</th>
            <th style={{ width: 100 }}>Status</th>
          </tr>
        </thead>
        <tbody>
          {Object.entries(groups).map(([gname, rows]) => {
            if (rows.length === 0) return null;
            return (
              <React.Fragment key={gname}>
                {groupBy !== "none" && (
                  <tr className="group-head">
                    <td colSpan="8">
                      <span>{gname}</span>
                      <span className="muted" style={{ marginLeft: 8 }}>{rows.length}</span>
                    </td>
                  </tr>
                )}
                {rows.map(t => (
                  <tr key={t.id} className="t-row">
                    <td><StatusDot status={t.col}/></td>
                    <td className="t-id">{t.id}</td>
                    <td className="t-title">
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <span>{t.title}</span>
                        {t.desc.match(/SYS-\d+|LORE-\d+|TECH-\d+/) && (
                          <span className="chip" style={{ background: "transparent", borderColor: "var(--line)" }}>
                            <Icon name="link" size={10}/>{t.desc.match(/SYS-\d+|LORE-\d+|TECH-\d+/)[0]}
                          </span>
                        )}
                      </div>
                    </td>
                    <td><TagChip tag={t.tag}/></td>
                    <td><PrioDot p={t.prio}/> <span className="small muted" style={{ marginLeft: 4, textTransform: "capitalize" }}>{t.prio}</span></td>
                    <td className="muted tnum">{t.due}</td>
                    <td>
                      <div style={{ display: "flex" }}>
                        {t.assignees.map(a => <Avatar key={a} id={a} size={20}/>)}
                      </div>
                    </td>
                    <td>
                      <span className="chip">
                        <StatusDot status={t.col}/>
                        {(window.KB_COLUMNS.find(c => c.id === t.col) || {}).title}
                      </span>
                    </td>
                  </tr>
                ))}
              </React.Fragment>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

window.TasksScreen = TasksScreen;
