// Card + Column + Board — adapted to live data, with the redesigned
// "needs decision" affordance.

function PRChip({ pr }) {
  if (!pr) return null;
  const label = pr.status === "merged" ? `merged #${pr.number}` : `#${pr.number}`;
  return (
    <span className={"pr-chip " + pr.status} title={pr.title}>
      <window.Icon.PR />
      {label}
    </span>
  );
}

function BranchChip({ branch }) {
  if (!branch) return null;
  return (
    <span className="branch-chip" title={branch}>
      <window.Icon.Branch />
      {branch.length > 22 ? branch.slice(0, 21) + "…" : branch}
    </span>
  );
}

function agentVerb(task) {
  const last = (task.cot && task.cot[task.cot.length - 1]) || null;
  if (!last) return "working";
  if (last.kind === "tool") return `running ${last.tool || "tool"}`;
  if (last.kind === "wait") return "waiting";
  if (last.kind === "thought") return "thinking";
  if (last.kind === "output") return "wrapping up";
  if (last.kind === "decision") return "needs you";
  return "working";
}

function Card({ task, onClick, onConfirmDecision }) {
  const a = (window.AGENTS || {})[task.assignee] || null;
  const showActiveAgent = task.active && a && a.kind === "ai";
  const opts = task.decision_options || [];

  return (
    <div
      className={
        "card" +
        (task.active ? " active-glow" : "") +
        (task.needs_decision ? " needs-decision" : "")
      }
      onClick={onClick}
    >
      <div className="card-top">
        <span className="card-id">{task.id ? task.id.slice(0, 6) : ""}</span>
        <div className="card-spacer" />
        {task.active && <span className="live-dot" title="Agent working now" />}
      </div>
      <div className="card-title">{task.title}</div>

      {task.needs_decision && (
        <>
          <div className="decision-stripe">
            <span className="decision-icon"><window.Icon.Decision /></span>
            <div className="decision-text" style={{ whiteSpace: "pre-wrap" }}>
              <strong>Decision needed.</strong>{" "}
              {task.decision_prompt || "The agent paused and is waiting for you."}
            </div>
          </div>
          {opts.length > 0 && (
            <div className="decision-quick" onClick={(e) => e.stopPropagation()}>
              {opts.map((opt, i) => (
                <button key={i} className={i === 0 ? "confirm" : ""} onClick={() => onConfirmDecision && onConfirmDecision(task, i)}>
                  {String.fromCharCode(65 + i)} · {String(opt).slice(0, 24)}
                </button>
              ))}
            </div>
          )}
          {opts.length === 0 && (
            <div className="decision-quick" onClick={(e) => e.stopPropagation()}>
              <button className="confirm" onClick={() => onConfirmDecision && onConfirmDecision(task, 0)}>Approve</button>
              <button onClick={() => task.decision_request_id && window.api.respondInput(task.decision_request_id, { approved: false })}>Deny</button>
            </div>
          )}
        </>
      )}

      {typeof task.progress === "number" && task.progress > 0 && task.progress < 1 && (
        <div className="progress" title={Math.round(task.progress * 100) + "%"}>
          <div className="progress-fill" style={{ width: `${task.progress * 100}%` }} />
        </div>
      )}

      <div className="card-meta">
        {a ? (
          <div className="assignee">
            <window.Avatar who={task.assignee} size={18} />
            <span>{a.name}</span>
          </div>
        ) : (
          <span className="assignee" style={{ color: "var(--text-faint)" }}>unassigned</span>
        )}
        {task.pr && <PRChip pr={task.pr} />}
        {!task.pr && task.branch && <BranchChip branch={task.branch} />}
        {task.usage && task.usage.tokens_in + task.usage.tokens_out > 0 && (
          <span className="label-pill mono" title="tokens in/out">
            {(task.usage.tokens_in + task.usage.tokens_out).toLocaleString()} tok
          </span>
        )}
      </div>

      {showActiveAgent && (
        <div className="card-active-hint">
          <window.Icon.Sparkle /> {a.name} is {agentVerb(task)}
        </div>
      )}
    </div>
  );
}

function Column({ col, tasks, onOpenTask, onConfirmDecision, projectId }) {
  const needs = tasks.filter((t) => t.needs_decision).length;
  const addTask = async () => {
    if (!projectId) return;
    const agentOpts = Object.values(window.AGENTS || {})
      .filter((a) => a.kind === "ai")
      .map((a) => ({ value: a.id, label: a.name + (a.role ? ` · ${a.role}` : "") }));
    const v = await window.dialog.form({
      title: `New task in ${col.title}`,
      body: "The agent will pick this up automatically once the task is queued.",
      fields: [
        { name: "title", label: "Title", type: "text", required: true, placeholder: "What should the agent do?" },
        { name: "description", label: "Description (optional)", type: "textarea", placeholder: "Add context, links, or constraints.", rows: 3 },
        { name: "assignee", label: "Assignee", type: "agent", options: agentOpts, value: "" },
      ],
      submitLabel: "Create task",
    });
    if (v && v.title) {
      await window.api.createTask({
        project_id: projectId,
        title: v.title,
        description: v.description || "",
        assignee: v.assignee || null,
        column: col.id === "in_progress" || col.id === "queued" ? "queued" : col.id,
      });
    }
  };
  return (
    <div className="column">
      <div className="column-head">
        <span className="column-title">{col.title}</span>
        <span className="column-count">{tasks.length}</span>
        {needs > 0 && <span className="decision-count">{needs} needs you</span>}
        <div style={{ flex: 1 }} />
        <button className="column-add" title={`Add task to ${col.title}`} onClick={addTask}>
          <window.Icon.Plus />
        </button>
      </div>
      <div className="column-list">
        {tasks.map((t) => (
          <Card key={t.id} task={t} onClick={() => onOpenTask(t.id)} onConfirmDecision={onConfirmDecision} />
        ))}
        {tasks.length === 0 && (
          <div style={{ color: "var(--text-faint)", fontSize: 12, padding: "10px 4px" }}>
            Nothing here.
          </div>
        )}
      </div>
    </div>
  );
}

function Board({ project, filter, onOpenTask, onConfirmDecision }) {
  const tasks = (project && project.tasks) || [];
  const filtered = tasks.filter((t) => {
    if (filter.assignee && t.assignee !== filter.assignee) return false;
    if (filter.needsDecisionOnly && !t.needs_decision) return false;
    if (filter.activeOnly && !t.active) return false;
    return true;
  });
  return (
    <div className="board">
      {(window.COLUMNS || []).map((c) => (
        <Column
          key={c.id}
          col={c}
          tasks={filtered.filter((t) => (t.column || "in_progress") === c.id)}
          onOpenTask={onOpenTask}
          onConfirmDecision={onConfirmDecision}
          projectId={project && project.id !== "_empty" ? project.id : null}
        />
      ))}
    </div>
  );
}

window.Board = Board;
