import blessed from "blessed";
import { EventEmitter } from "events";
class TaskBoard extends EventEmitter {
  container;
  columns;
  tasks;
  selectedTask = null;
  currentColumn = "todo";
  columnConfig = [
    { id: "backlog", title: "Backlog", color: "gray" },
    { id: "todo", title: "To Do", color: "cyan" },
    { id: "in_progress", title: "In Progress", color: "yellow" },
    { id: "review", title: "Review", color: "magenta" },
    { id: "done", title: "Done", color: "green" }
  ];
  constructor(container) {
    super();
    this.container = container;
    this.columns = /* @__PURE__ */ new Map();
    this.tasks = /* @__PURE__ */ new Map();
    this.initializeUI();
  }
  initializeUI() {
    const columnWidth = Math.floor(100 / this.columnConfig.length);
    this.columnConfig.forEach((column, index) => {
      const columnBox = blessed.box({
        parent: this.container,
        left: `${index * columnWidth}%`,
        top: 0,
        width: `${columnWidth}%`,
        height: "100%",
        border: {
          type: "line"
        },
        style: {
          border: {
            fg: column.color
          }
        },
        label: ` ${column.title} `
      });
      const taskList = blessed.list({
        parent: columnBox,
        top: 0,
        left: 0,
        width: "100%-2",
        height: "100%-2",
        style: {
          selected: {
            bg: column.color,
            fg: "black",
            bold: true
          },
          item: {
            fg: "white"
          }
        },
        mouse: true,
        keys: true,
        vi: true,
        scrollable: true,
        tags: true
      });
      taskList.on("select", (item, index2) => {
        const tasksInColumn = this.getTasksInColumn(column.id);
        if (tasksInColumn[index2]) {
          this.selectTask(tasksInColumn[index2].id);
        }
      });
      this.columns.set(column.id, taskList);
    });
    this.setupKeyboardNavigation();
  }
  setupKeyboardNavigation() {
    const container = this.container;
    container.key(["left", "h"], () => {
      this.navigateColumn(-1);
    });
    container.key(["right", "l"], () => {
      this.navigateColumn(1);
    });
    container.key(["S-left"], () => {
      this.moveTaskToColumn(-1);
    });
    container.key(["S-right"], () => {
      this.moveTaskToColumn(1);
    });
    container.key(["enter"], () => {
      if (this.selectedTask) {
        this.showTaskCompletionMenu(this.tasks.get(this.selectedTask));
      }
    });
    container.key(["n"], () => {
      this.createNewTask();
    });
    container.key(["d"], () => {
      if (this.selectedTask) {
        this.markTaskDone(this.selectedTask);
      }
    });
    container.key(["a"], () => {
      if (this.selectedTask) {
        this.assignTask(this.selectedTask);
      }
    });
    container.key(["u"], () => {
      if (this.selectedTask) {
        this.showStatusUpdateDialog(this.selectedTask);
      }
    });
    container.key(["c"], () => {
      if (this.selectedTask) {
        this.startTaskWithClaude(this.selectedTask);
      }
    });
    container.key(["s"], () => {
      this.syncWithLinear();
    });
  }
  getTasksInColumn(columnId) {
    return Array.from(this.tasks.values()).filter((task) => this.getTaskColumn(task) === columnId).sort((a, b) => (b.priority || 0) - (a.priority || 0));
  }
  getTaskColumn(task) {
    const stateMapping = {
      // Raw Linear API states
      backlog: "backlog",
      unstarted: "todo",
      started: "in_progress",
      completed: "done",
      canceled: "done",
      cancelled: "done",
      // Formatted display states from data service
      Backlog: "backlog",
      "To Do": "todo",
      "In Progress": "in_progress",
      Done: "done",
      Canceled: "done",
      // Legacy mappings
      todo: "todo",
      in_progress: "in_progress",
      in_review: "review",
      done: "done"
    };
    const state = task.state || "todo";
    return stateMapping[state] || stateMapping[state.toLowerCase()] || "todo";
  }
  formatTaskItem(task) {
    const priority = this.getPriorityIcon(task.priority);
    const estimate = task.estimate ? `[${task.estimate}]` : "";
    let assignee;
    if (typeof task.assignee === "string") {
      assignee = `@${task.assignee}`;
    } else if (task.assignee?.name) {
      assignee = `@${task.assignee.name}`;
    } else {
      assignee = "{gray-fg}unassigned{/}";
    }
    const labels = task.labels?.map((l) => `{cyan-fg}#${l}{/}`).join(" ") || "";
    let taskStr = `${priority} {bold}${task.identifier}{/}: ${task.title}
`;
    if (task.description && task.description.trim()) {
      const descPreview = task.description.split("\n")[0].substring(0, 60).trim();
      taskStr += `  {gray-fg}${descPreview}${task.description.length > 60 ? "..." : ""}{/}
`;
    }
    taskStr += `  {gray-fg}${assignee} ${estimate} ${labels}{/}`;
    if (task.progress !== void 0) {
      const progressBar = this.createProgressBar(task.progress);
      taskStr += `
  ${progressBar}`;
    }
    if (task.dueDate) {
      const daysUntilDue = this.getDaysUntilDue(task.dueDate);
      if (daysUntilDue < 0) {
        taskStr += ` {red-fg}\u26A0 Overdue{/}`;
      } else if (daysUntilDue <= 1) {
        taskStr += ` {yellow-fg}\u26A0 Due soon{/}`;
      }
    }
    return taskStr;
  }
  getPriorityIcon(priority) {
    if (!priority) return "\u25CB";
    switch (priority) {
      case 0:
        return "{red-fg}\u{1F534}{/}";
      // Urgent
      case 1:
        return "{yellow-fg}\u{1F7E1}{/}";
      // High
      case 2:
        return "{green-fg}\u{1F7E2}{/}";
      // Medium
      case 3:
        return "{blue-fg}\u{1F535}{/}";
      // Low
      default:
        return "\u25CB";
    }
  }
  createProgressBar(progress) {
    const width = 10;
    const filled = Math.round(progress * width);
    const empty = width - filled;
    const color = progress >= 1 ? "green" : progress >= 0.5 ? "yellow" : "red";
    return `{${color}-fg}${"\u2588".repeat(filled)}{/}{gray-fg}${"\u2591".repeat(empty)}{/} ${Math.round(progress * 100)}%`;
  }
  getDaysUntilDue(dueDate) {
    const due = new Date(dueDate);
    const now = /* @__PURE__ */ new Date();
    const diffTime = due.getTime() - now.getTime();
    return Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
  }
  update(tasks) {
    this.tasks.clear();
    tasks.forEach((task) => {
      this.tasks.set(task.id, task);
    });
    this.columnConfig.forEach((column) => {
      const columnTasks = this.getTasksInColumn(column.id);
      const items = columnTasks.map((task) => this.formatTaskItem(task));
      const list = this.columns.get(column.id);
      if (list) {
        list.setItems(items);
        const parent = list.parent;
        if (parent && typeof parent.setLabel === "function") {
          parent.setLabel(` ${column.title} (${columnTasks.length}) `);
        }
      }
    });
    this.container.screen.render();
  }
  navigateColumn(direction) {
    const columnIds = this.columnConfig.map((c) => c.id);
    const currentIndex = columnIds.indexOf(this.currentColumn);
    const newIndex = Math.max(
      0,
      Math.min(columnIds.length - 1, currentIndex + direction)
    );
    this.currentColumn = columnIds[newIndex];
    this.columns.get(this.currentColumn)?.focus();
    this.container.screen.render();
  }
  moveTaskToColumn(direction) {
    if (!this.selectedTask) return;
    const task = this.tasks.get(this.selectedTask);
    if (!task) return;
    const columnIds = this.columnConfig.map((c) => c.id);
    const currentColumnIndex = columnIds.indexOf(this.getTaskColumn(task));
    const newColumnIndex = Math.max(
      0,
      Math.min(columnIds.length - 1, currentColumnIndex + direction)
    );
    const newColumn = columnIds[newColumnIndex];
    this.emit("task:move", {
      taskId: task.id,
      fromColumn: columnIds[currentColumnIndex],
      toColumn: newColumn
    });
    const stateMapping = {
      backlog: "backlog",
      todo: "unstarted",
      in_progress: "started",
      review: "in_review",
      done: "completed"
    };
    task.state = stateMapping[newColumn] || task.state;
    this.update(Array.from(this.tasks.values()));
  }
  selectTask(taskId) {
    this.selectedTask = taskId;
    const task = this.tasks.get(taskId);
    if (task) {
      this.emit("task:selected", task);
    }
  }
  showTaskDetails(task) {
    const details = blessed.box({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "70%",
      height: "70%",
      content: this.formatTaskDetails(task),
      tags: true,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "green"
        }
      },
      scrollable: true,
      keys: true,
      vi: true,
      mouse: true,
      hidden: false,
      label: ` Task: ${task.identifier} - ${task.title} `
    });
    details.key(["escape", "q"], () => {
      details.destroy();
      this.container.screen.render();
    });
    details.focus();
    this.container.screen.render();
  }
  formatTaskDetails(task) {
    let details = `{bold}ID:{/} ${task.identifier}
`;
    details += `{bold}Title:{/} ${task.title}
`;
    details += `{bold}State:{/} ${task.state}
`;
    details += `{bold}Priority:{/} ${this.getPriorityIcon(task.priority)} ${task.priority || "None"}
`;
    if (task.assignee) {
      if (typeof task.assignee === "string") {
        details += `{bold}Assignee:{/} ${task.assignee}
`;
      } else {
        details += `{bold}Assignee:{/} ${task.assignee.name} (${task.assignee.email})
`;
      }
    }
    if (task.estimate) {
      details += `{bold}Estimate:{/} ${task.estimate} points
`;
    }
    if (task.dueDate) {
      const daysUntil = this.getDaysUntilDue(task.dueDate);
      const dueColor = daysUntil < 0 ? "red" : daysUntil <= 1 ? "yellow" : "white";
      details += `{bold}Due Date:{/} {${dueColor}-fg}${new Date(task.dueDate).toLocaleDateString()}{/}
`;
    }
    if (task.labels && task.labels.length > 0) {
      details += `{bold}Labels:{/} ${task.labels.map((l) => `{cyan-fg}#${l}{/}`).join(" ")}
`;
    }
    if (task.description) {
      details += `
{bold}Description:{/}
${task.description}
`;
    }
    if (task.comments && task.comments.length > 0) {
      details += `
{bold}Comments ({${task.comments.length}}):{/}
`;
      task.comments.slice(-5).forEach((comment) => {
        details += `
{gray-fg}${comment.author} - ${new Date(comment.createdAt).toLocaleString()}{/}
`;
        details += `${comment.body}
`;
      });
    }
    if (task.subtasks && task.subtasks.length > 0) {
      details += `
{bold}Subtasks:{/}
`;
      task.subtasks.forEach((subtask) => {
        const check = subtask.completed ? "\u2713" : "\u25CB";
        details += `  ${check} ${subtask.title}
`;
      });
    }
    details += `
{bold}Actions:{/}
`;
    details += `  [d] Mark Done | [a] Assign | [c] Comment | [e] Edit
`;
    return details;
  }
  createNewTask() {
    const form = blessed.form({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "50%",
      height: 14,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "cyan"
        }
      },
      label: " Create New Task ",
      keys: true
    });
    const titleLabel = blessed.text({
      parent: form,
      content: "Title:",
      top: 1,
      left: 2
    });
    const titleInput = blessed.textbox({
      parent: form,
      name: "title",
      top: 1,
      left: 10,
      width: "100%-12",
      height: 1,
      inputOnFocus: true,
      style: {
        focus: {
          fg: "white",
          bg: "blue"
        }
      }
    });
    const descLabel = blessed.text({
      parent: form,
      content: "Desc:",
      top: 3,
      left: 2
    });
    const descInput = blessed.textarea({
      parent: form,
      name: "description",
      top: 3,
      left: 10,
      width: "100%-12",
      height: 4,
      inputOnFocus: true,
      style: {
        focus: {
          fg: "white",
          bg: "blue"
        }
      }
    });
    const submitBtn = blessed.button({
      parent: form,
      content: " Create ",
      top: 9,
      left: "center",
      shrink: true,
      style: {
        focus: {
          bg: "green",
          fg: "white"
        }
      }
    });
    submitBtn.on("press", () => {
      const title = titleInput.getValue();
      const description = descInput.getValue();
      if (title) {
        this.emit("task:create", { title, description });
      }
      form.destroy();
      this.container.screen.render();
    });
    form.key(["escape"], () => {
      form.destroy();
      this.container.screen.render();
    });
    titleInput.focus();
    this.container.screen.render();
  }
  markTaskDone(taskId) {
    const task = this.tasks.get(taskId);
    if (task) {
      this.emit("task:update", {
        taskId: task.id,
        updates: { state: "completed" }
      });
      task.state = "completed";
      this.update(Array.from(this.tasks.values()));
    }
  }
  assignTask(taskId) {
    this.emit("task:assign", { taskId });
  }
  focus() {
    const column = this.columns.get(this.currentColumn);
    if (column) {
      column.focus();
    }
  }
  hasFocus() {
    return Array.from(this.columns.values()).some(
      (col) => col === this.container.screen.focused
    );
  }
  showStatusUpdateDialog(taskId) {
    const task = this.tasks.get(taskId);
    if (!task) return;
    const dialog = blessed.list({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "50%",
      height: 12,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "yellow"
        },
        selected: {
          bg: "blue",
          fg: "white"
        }
      },
      label: ` Update Status: ${task.title.substring(0, 40)}... `,
      items: [
        "1. Backlog",
        "2. Todo",
        "3. In Progress",
        "4. In Review",
        "5. Done",
        "6. Canceled",
        "",
        "ESC to cancel"
      ],
      keys: true,
      vi: true,
      mouse: true
    });
    dialog.on("select", (item, index) => {
      const statusMap = [
        "backlog",
        "todo",
        "in_progress",
        "review",
        "completed",
        "cancelled"
      ];
      if (index < statusMap.length) {
        this.updateTaskStatus(taskId, statusMap[index]);
      }
      dialog.destroy();
      this.container.screen.render();
    });
    dialog.key(["escape"], () => {
      dialog.destroy();
      this.container.screen.render();
    });
    dialog.focus();
    this.container.screen.render();
  }
  async updateTaskStatus(taskId, newStatus) {
    const task = this.tasks.get(taskId);
    if (!task) return;
    task.state = this.mapStatusToLinearState(newStatus);
    this.update(Array.from(this.tasks.values()));
    this.emit("task:status:update", {
      taskId,
      oldStatus: task.state,
      newStatus,
      linearId: task.identifier
    });
    const notification = blessed.message({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "50%",
      height: 3,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "green"
        }
      },
      content: `Task status updated to: ${newStatus}`
    });
    setTimeout(() => {
      notification.destroy();
      this.container.screen.render();
    }, 1500);
    this.container.screen.render();
  }
  async startTaskWithClaude(taskId) {
    const task = this.tasks.get(taskId);
    if (!task) return;
    try {
      const { exec } = await import("child_process");
      const fs = await import("fs/promises");
      const os = await import("os");
      const path = await import("path");
      const contextDir = path.join(
        os.homedir(),
        ".stackmemory",
        "task-contexts"
      );
      await fs.mkdir(contextDir, { recursive: true });
      const contextFile = path.join(
        contextDir,
        `${task.identifier}-context.md`
      );
      const contextContent = `# Task: ${task.identifier} - ${task.title}

## Description
${task.description || "No description provided"}

## Status
Current: ${task.state}
Priority: ${this.getPriorityLabel(task.priority)}

## Linear Task ID
${task.identifier}

## Quick Commands
- Update status: stackmemory task:update "${task.identifier}" --status <status>
- Add comment: stackmemory task:comment "${task.identifier}" --message "<comment>"
- View details: stackmemory task:show "${task.identifier}"

---
This task has been loaded from Linear. The context above provides the task details.
Start working on this task below:
`;
      await fs.writeFile(contextFile, contextContent);
      const command = `claude-sm --task "${task.identifier}: ${task.title}" --context "${contextFile}"`;
      const notification = blessed.message({
        parent: this.container.screen,
        top: "center",
        left: "center",
        width: "60%",
        height: 5,
        border: {
          type: "line"
        },
        style: {
          border: {
            fg: "cyan"
          }
        },
        content: `Launching Claude for task:
${task.identifier}: ${task.title}

Command: ${command}`
      });
      this.container.screen.render();
      exec(command, (error, stdout, stderr) => {
        if (error) {
          const errorMsg = blessed.message({
            parent: this.container.screen,
            top: "center",
            left: "center",
            width: "50%",
            height: 4,
            border: {
              type: "line"
            },
            style: {
              border: {
                fg: "red"
              }
            },
            content: `Failed to launch Claude: ${error.message}`
          });
          setTimeout(() => {
            errorMsg.destroy();
            this.container.screen.render();
          }, 3e3);
        }
      });
      setTimeout(() => {
        notification.destroy();
        this.container.screen.render();
      }, 2e3);
      this.emit("task:launch:claude", {
        taskId,
        command,
        task,
        contextFile
      });
    } catch (error) {
      const errorMsg = blessed.message({
        parent: this.container.screen,
        top: "center",
        left: "center",
        width: "50%",
        height: 4,
        border: {
          type: "line"
        },
        style: {
          border: {
            fg: "red"
          }
        },
        content: `Error: ${error.message}`
      });
      setTimeout(() => {
        errorMsg.destroy();
        this.container.screen.render();
      }, 3e3);
      this.container.screen.render();
    }
  }
  showTaskCompletionMenu(task) {
    const menuBox = blessed.box({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "70%",
      height: "80%",
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "cyan"
        }
      },
      label: ` Task Completion Menu: ${task.identifier} `,
      keys: true,
      mouse: true
    });
    const header = blessed.text({
      parent: menuBox,
      top: 1,
      left: 2,
      width: "100%-4",
      height: 5,
      content: `{bold}${task.identifier}: ${task.title}{/}

{gray-fg}${(task.description || "No description").substring(0, 200)}{/}`,
      tags: true,
      wrap: true
    });
    const statusDisplay = blessed.text({
      parent: menuBox,
      top: 7,
      left: 2,
      content: `{bold}Current Status:{/} ${this.formatStatus(task.state)}`,
      tags: true
    });
    const menu = blessed.list({
      parent: menuBox,
      top: 9,
      left: 2,
      width: "100%-4",
      height: 12,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "gray"
        },
        selected: {
          bg: "blue",
          fg: "white"
        }
      },
      label: " Quick Actions ",
      items: [
        "1. \u2705 Mark as Done",
        "2. \u{1F504} Change Status",
        "3. \u{1F3AF} Update Priority",
        "4. \u{1F464} Assign to Someone",
        "5. \u{1F4AC} Add Comment",
        "6. \u{1F4DD} Edit Description",
        "7. \u{1F680} Start with Claude",
        "8. \u{1F50D} View Full Details",
        "9. \u274C Cancel Task"
      ],
      keys: true,
      vi: true,
      mouse: true
    });
    const metadata = blessed.text({
      parent: menuBox,
      bottom: 3,
      left: 2,
      width: "100%-4",
      height: 4,
      content: this.formatTaskMetadata(task),
      tags: true
    });
    const instructions = blessed.text({
      parent: menuBox,
      bottom: 1,
      left: 2,
      content: "{gray-fg}Use arrows/numbers to select \u2022 Enter to execute \u2022 ESC to close{/}",
      tags: true
    });
    menu.on("select", (item, index) => {
      menuBox.destroy();
      switch (index) {
        case 0:
          this.updateTaskStatus(task.id, "completed");
          this.showNotification(`\u2705 Task ${task.identifier} marked as done`);
          break;
        case 1:
          this.showStatusUpdateDialog(task.id);
          break;
        case 2:
          this.showPriorityUpdateDialog(task);
          break;
        case 3:
          this.showAssignDialog(task);
          break;
        case 4:
          this.showCommentDialog(task);
          break;
        case 5:
          this.showEditDescriptionDialog(task);
          break;
        case 6:
          this.startTaskWithClaude(task.id);
          break;
        case 7:
          this.showTaskDetails(task);
          break;
        case 8:
          this.updateTaskStatus(task.id, "canceled");
          this.showNotification(`\u274C Task ${task.identifier} canceled`);
          break;
      }
      this.container.screen.render();
    });
    menu.key(["1", "2", "3", "4", "5", "6", "7", "8", "9"], (ch) => {
      const index = parseInt(ch, 10) - 1;
      if (index < menu.items.length) {
        menu.select(index);
        menu.emit("select", menu.items[index], index);
      }
    });
    menuBox.key(["escape", "q"], () => {
      menuBox.destroy();
      this.container.screen.render();
    });
    menu.focus();
    this.container.screen.render();
  }
  formatStatus(state) {
    const statusColors = {
      backlog: "{gray-fg}\u{1F4CB} Backlog{/}",
      unstarted: "{yellow-fg}\u23F8\uFE0F Todo{/}",
      started: "{blue-fg}\u25B6\uFE0F In Progress{/}",
      completed: "{green-fg}\u2705 Done{/}",
      canceled: "{red-fg}\u274C Canceled{/}"
    };
    return statusColors[state.toLowerCase()] || state;
  }
  formatTaskMetadata(task) {
    let meta = "";
    if (task.assignee) {
      const name = typeof task.assignee === "string" ? task.assignee : task.assignee.name;
      meta += `{bold}Assignee:{/} ${name}  `;
    }
    if (task.priority !== void 0) {
      meta += `{bold}Priority:{/} ${this.getPriorityLabel(task.priority)}  `;
    }
    if (task.estimate) {
      meta += `{bold}Points:{/} ${task.estimate}  `;
    }
    if (task.dueDate) {
      const daysUntil = this.getDaysUntilDue(task.dueDate);
      const color = daysUntil < 0 ? "red" : daysUntil <= 1 ? "yellow" : "white";
      meta += `{bold}Due:{/} {${color}-fg}${new Date(task.dueDate).toLocaleDateString()}{/}`;
    }
    return meta;
  }
  getPriorityLabel(priority) {
    if (priority === void 0 || priority === null) return "None";
    const labels = ["Urgent", "High", "Medium", "Low", "None"];
    return labels[priority] || "None";
  }
  showPriorityUpdateDialog(task) {
    const dialog = blessed.list({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "40%",
      height: 9,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "magenta"
        },
        selected: {
          bg: "magenta",
          fg: "white"
        }
      },
      label: ` Set Priority: ${task.identifier} `,
      items: [
        "\u{1F534} Urgent (P0)",
        "\u{1F7E1} High (P1)",
        "\u{1F7E2} Medium (P2)",
        "\u{1F535} Low (P3)",
        "\u26AA None"
      ],
      keys: true,
      vi: true
    });
    dialog.on("select", (item, index) => {
      const priority = index < 4 ? index : void 0;
      this.emit("task:update", {
        taskId: task.id,
        updates: { priority }
      });
      dialog.destroy();
      this.showNotification(`\u{1F3AF} Priority updated for ${task.identifier}`);
      this.container.screen.render();
    });
    dialog.key(["escape"], () => {
      dialog.destroy();
      this.container.screen.render();
    });
    dialog.focus();
    this.container.screen.render();
  }
  showAssignDialog(task) {
    this.showNotification("Assignment dialog coming soon!");
  }
  showCommentDialog(task) {
    const form = blessed.form({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "60%",
      height: 10,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "green"
        }
      },
      label: ` Add Comment to ${task.identifier} `,
      keys: true
    });
    const commentInput = blessed.textarea({
      parent: form,
      top: 1,
      left: 1,
      width: "100%-2",
      height: 5,
      inputOnFocus: true,
      style: {
        focus: {
          fg: "white",
          bg: "blue"
        }
      }
    });
    const submitBtn = blessed.button({
      parent: form,
      content: " Add Comment ",
      bottom: 1,
      left: "center",
      shrink: true,
      style: {
        focus: {
          bg: "green",
          fg: "white"
        }
      }
    });
    submitBtn.on("press", () => {
      const comment = commentInput.getValue();
      if (comment) {
        this.emit("task:comment", { taskId: task.id, comment });
        this.showNotification(`\u{1F4AC} Comment added to ${task.identifier}`);
      }
      form.destroy();
      this.container.screen.render();
    });
    form.key(["escape"], () => {
      form.destroy();
      this.container.screen.render();
    });
    commentInput.focus();
    this.container.screen.render();
  }
  showEditDescriptionDialog(task) {
    const form = blessed.form({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "70%",
      height: 15,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "cyan"
        }
      },
      label: ` Edit Description: ${task.identifier} `,
      keys: true
    });
    const descInput = blessed.textarea({
      parent: form,
      top: 1,
      left: 1,
      width: "100%-2",
      height: 10,
      inputOnFocus: true,
      content: task.description || "",
      style: {
        focus: {
          fg: "white",
          bg: "blue"
        }
      }
    });
    const submitBtn = blessed.button({
      parent: form,
      content: " Save Description ",
      bottom: 1,
      left: "center",
      shrink: true,
      style: {
        focus: {
          bg: "cyan",
          fg: "white"
        }
      }
    });
    submitBtn.on("press", () => {
      const description = descInput.getValue();
      this.emit("task:update", {
        taskId: task.id,
        updates: { description }
      });
      this.showNotification(`\u{1F4DD} Description updated for ${task.identifier}`);
      form.destroy();
      this.container.screen.render();
    });
    form.key(["escape"], () => {
      form.destroy();
      this.container.screen.render();
    });
    descInput.focus();
    this.container.screen.render();
  }
  showNotification(message) {
    const notification = blessed.box({
      parent: this.container.screen,
      top: 1,
      right: 1,
      width: message.length + 4,
      height: 3,
      content: ` ${message} `,
      style: {
        fg: "white",
        bg: "blue"
      },
      border: {
        type: "line",
        fg: "cyan"
      }
    });
    this.container.screen.render();
    setTimeout(() => {
      notification.destroy();
      this.container.screen.render();
    }, 3e3);
  }
  async syncWithLinear() {
    try {
      const notification = blessed.box({
        parent: this.container.screen,
        top: "center",
        left: "center",
        width: "40%",
        height: 5,
        border: {
          type: "line"
        },
        style: {
          border: {
            fg: "cyan"
          }
        },
        content: "{center}Syncing with Linear...{/center}",
        tags: true
      });
      this.container.screen.render();
      const { exec } = await import("child_process");
      const util = await import("util");
      const execAsync = util.promisify(exec);
      await execAsync("cd /Users/jwu/Dev/stackmemory && npm run linear:sync");
      notification.setContent(
        "{center}\u2713 Sync complete! Refreshing...{/center}"
      );
      notification.style.border.fg = "green";
      setTimeout(() => {
        notification.destroy();
        this.emit("tasks:refresh");
        this.container.screen.render();
      }, 1e3);
    } catch (error) {
      const errorMsg = blessed.message({
        parent: this.container.screen,
        top: "center",
        left: "center",
        width: "50%",
        height: 4,
        border: {
          type: "line"
        },
        style: {
          border: {
            fg: "red"
          }
        },
        content: `Sync failed: ${error.message}`
      });
      setTimeout(() => {
        errorMsg.destroy();
        this.container.screen.render();
      }, 3e3);
      this.container.screen.render();
    }
  }
  mapStatusToLinearState(status) {
    const mapping = {
      backlog: "Backlog",
      todo: "Todo",
      in_progress: "In Progress",
      review: "In Review",
      completed: "Done",
      cancelled: "Canceled"
    };
    return mapping[status] || "Backlog";
  }
}
export {
  TaskBoard
};
//# sourceMappingURL=task-board.js.map
