export const SwayNotificationCenter = async ({ project, client, $, directory, worktree }) => {
  console.log("SwayNC notification plugin initialized");
  
  return {
    event: async ({ event }) => {
      if (event.type === "session.idle") {
        const pid = process.pid;
        const dir = directory || worktree || "unknown";
        const iconPath = `${process.env.HOME}/.config/opencode/opencode.png`;
        
        try {
          const clientsJson = await $`hyprctl clients -j`.text();
          const clients = JSON.parse(clientsJson);
          
          const opencodeWindow = clients.find(c => 
            c.pid === pid || 
            (c.title && c.title.toLowerCase().includes("opencode"))
          );
          
          const windowAddress = opencodeWindow?.address || "";
          
          const notifyCmd = [
            "notify-send",
            "-a", "OpenCode",
            "-u", "normal",
            "-i", iconPath,
            "-h", `string:x-opencode-window:${windowAddress}`,
            "-h", `string:x-opencode-dir:${dir}`,
            "-A", `focus=Focus Window`,
            "OpenCode Ready",
            `Waiting for input\nDirectory: ${dir}`
          ];
          
          if (windowAddress) {
            // Run notify-send as detached background process
            import("child_process").then(({ spawn }) => {
              const child = spawn(notifyCmd[0], notifyCmd.slice(1), {
                detached: true,
                stdio: 'ignore'
              });
              child.unref();
              
              // Handle the response in the background
              let output = '';
              if (child.stdout) {
                child.stdout.on('data', (data) => {
                  output += data.toString();
                });
                child.on('close', () => {
                  if (output.trim() === "focus" && windowAddress) {
                    $`hyprctl dispatch focuswindow address:${windowAddress}`.catch(() => {});
                  }
                });
              }
            }).catch(() => {});
          } else {
            // Run without action button, no need to wait
            $`${notifyCmd.filter(arg => !arg.startsWith('focus'))}`.catch(() => {});
          }
        } catch (error) {
          console.error("Notification error:", error);
          
          await $`notify-send -a "OpenCode" -u normal -i ${iconPath} "OpenCode Ready" "Waiting for input in ${dir}"`;
        }
      }
    },
  };
};
