#include "browser_client.h"
#include "version.h"
#include "clipboard.h"
#include "fb_renderer.h"
#include "sixel_renderer.h"
#include "input_handler.h"
#include "tab_manager.h"
#include "profile_config.h"
#include "include/wrapper/cef_closure_task.h"
#include <chrono>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <thread>
#include <chrono>
#include <unistd.h>
#include <cmath>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.h>
#include <algorithm>

#define PEAK_DOWNLOAD_DIR "/root/Downloads"

#define LOGB(msg)                                                              \
  do {                                                                         \
    if (g_log_fd >= 0) {                                                       \
      std::ostringstream _oss;                                                 \
      _oss << msg << std::endl;                                                \
      const std::string &_s = _oss.str();                                      \
      write(g_log_fd, _s.data(), _s.size());                                   \
    }                                                                          \
  } while (0)

extern int g_log_fd;

// Helper function to get JS file path relative to executable
static std::string GetJsFilePath(const std::string& filename) {
  char exe_path[1024];
  ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
  if (len != -1) {
    exe_path[len] = '\0';
    std::string exe_dir = std::string(exe_path);
    size_t last_slash = exe_dir.find_last_of('/');
    if (last_slash != std::string::npos) {
      exe_dir = exe_dir.substr(0, last_slash);
      return exe_dir + "/" + filename;
    }
  }
  // Fallback to current directory
  return filename;
}

CefRefPtr<CefRenderHandler> BrowserClient::GetRenderHandler() {
  return this;
}
CefRefPtr<CefLifeSpanHandler> BrowserClient::GetLifeSpanHandler() {
  return this;
}
CefRefPtr<CefLoadHandler> BrowserClient::GetLoadHandler() {
  return this;
}
CefRefPtr<CefDisplayHandler> BrowserClient::GetDisplayHandler() {
  return this;
}
CefRefPtr<CefJSDialogHandler> BrowserClient::GetJSDialogHandler() {
  return this;
}
CefRefPtr<CefDownloadHandler> BrowserClient::GetDownloadHandler() {
  return this;
}
CefRefPtr<CefDialogHandler> BrowserClient::GetDialogHandler() {
  return this;
}
CefRefPtr<CefRequestHandler> BrowserClient::GetRequestHandler() {
  return static_cast<CefRequestHandler*>(this);
}

CefRefPtr<CefResourceRequestHandler> BrowserClient::GetResourceRequestHandler(
    CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
    CefRefPtr<CefRequest> request, bool is_navigation, bool is_download,
    const CefString &request_initiator, bool &disable_default_handling) {
  return static_cast<CefResourceRequestHandler*>(this);
}

cef_return_value_t BrowserClient::OnBeforeResourceLoad(
    CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
    CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback) {
  // Spoof the User-Agent client hints (Sec-CH-UA*) so sites that gate on the
  // browser brand (e.g. WhatsApp Web requires "Google Chrome") don't reject us.
  // CEF reports the unbranded "Chromium" brand by default, which trips those
  // checks. We advertise a standard Google Chrome brand with our major version.
  const std::string ua = "Mozilla/5.0 (Plan9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" +
                         std::string(CHROMIUM_VERSION) + " Safari/537.36";
  request->SetHeaderByName("User-Agent", ua, true);
  request->SetHeaderByName(
      "Sec-CH-UA",
      "\"Google Chrome\";v=\"" + chrome_major_ +
          "\", \"Chromium\";v=\"" + chrome_major_ + "\", \"Not A Brand\";v=\"99\"",
      true);
  request->SetHeaderByName("Sec-CH-UA-Mobile", "?0", true);
  request->SetHeaderByName("Sec-CH-UA-Platform", "\"Plan9\"", true);
  request->SetHeaderByName("Sec-CH-UA-Platform-Version", "\"0.0.0\"", true);
  request->SetHeaderByName("Sec-CH-UA-Full-Version-List",
                           "\"Google Chrome\";v=\"" + std::string(CHROMIUM_VERSION) +
                               "\", \"Chromium\";v=\"" + std::string(CHROMIUM_VERSION) +
                               "\", \"Not A Brand\";v=\"99.0.0.0\"",
                           true);
  return RV_CONTINUE;
}

BrowserClient::BrowserClient(int width, int height, int cell_width,
                             int cell_height, GraphicsBackend backend,
                             int fb_offset_x, int fb_offset_y)
    : width_(width), height_(height), cell_width_(cell_width),
      cell_height_(cell_height), backend_(backend), fb_offset_x_(fb_offset_x),
      fb_offset_y_(fb_offset_y), is_closing_(false),
      current_selected_index_(-1) {

  // Log cell dimensions using direct file write
  std::ofstream log("/tmp/peak_debug.log", std::ios::app);
  if (log) {
    log << "BrowserClient created: " << width << "x" << height
        << " pixels, cell: " << cell_width << "x" << cell_height << std::endl;
    log.close();
  }

  // Graphics backend selection: framebuffer blit when /dev/fb0 is ours
  // (plain fb console / tmux on a VT), sixel stream on STDOUT otherwise
  // (SSH, X11/xterm and kitty terminals).
  if (backend_ == GraphicsBackend::Framebuffer) {
    LOGB("Renderer: Framebuffer " << width << "x" << height);
    renderer_ = std::make_unique<FbRenderer>(width, height, cell_width,
                                             cell_height, fb_offset_x,
                                             fb_offset_y);
  } else {
    LOGB("Renderer: Sixel " << width << "x" << height << " cells "
                            << cell_width << "x" << cell_height);
    renderer_ = std::make_unique<SixelRenderer>(width, height, cell_width,
                                                cell_height);
  }

  status_bar_ = std::make_unique<StatusBar>();

  // Derive the Chromium major version (e.g. "143" from "143.0.0.0") for
  // spoofing UA client hints as Google Chrome.
  chrome_major_ = CHROMIUM_VERSION;
  size_t dot = chrome_major_.find('.');
  if (dot != std::string::npos) {
    chrome_major_ = chrome_major_.substr(0, dot);
  }

  RunOneTimeImports();
}

void BrowserClient::GetViewRect(CefRefPtr<CefBrowser> browser, CefRect &rect) {
  rect.x = 0;
  rect.y = 0;
  rect.width = width_;
  rect.height = height_;
}

void BrowserClient::Resize(int width, int height, int cell_width,
                           int cell_height, int fb_offset_x, int fb_offset_y) {
  std::lock_guard<std::mutex> lock(render_mutex_);
  
  width_ = width;
  height_ = height;
  cell_width_ = cell_width;
  cell_height_ = cell_height;
  fb_offset_x_ = fb_offset_x;
  fb_offset_y_ = fb_offset_y;

  // Recalculate auto zoom if enabled
  ProfileConfig &config = ProfileConfig::getInstance();
  std::string behavior = config.getDefaultZoomBehavior();
  
  if (behavior == "auto" && browser_) {
    // Auto-calculate zoom based on:
    // 1. Terminal cell size (DPI adaptation)
    // 2. Rendering resolution (window size adaptation)
    
    const double reference_cell_height = 20.0;
    const double reference_cell_width = 10.0;
    const double reference_width = 1600.0; // Reference resolution
    const double reference_height = 900.0;
    
    // Factor 1: Cell size ratio (DPI)
    double height_ratio = cell_height_ / reference_cell_height;
    double width_ratio = cell_width_ / reference_cell_width;
    double cell_zoom = (height_ratio * 0.7) + (width_ratio * 0.3);
    
    // Factor 2: Resolution ratio (window size)
    double res_height_ratio = height / reference_height;
    double res_width_ratio = width / reference_width;
    double res_zoom = (res_height_ratio * 0.5) + (res_width_ratio * 0.5);
    
    // Combine both factors: 60% cell size, 40% resolution
    double zoom_level = (cell_zoom * 0.6) + (res_zoom * 0.4);
    
    // Apply bounds (0.25x to 3.0x)
    if (zoom_level < 0.25) zoom_level = 0.25;
    if (zoom_level > 3.0) zoom_level = 3.0;
    
    // Check for site-specific override
    std::string url = browser_->GetMainFrame()->GetURL().ToString();
    std::string domain;
    size_t proto = url.find("://");
    if (proto != std::string::npos) {
      size_t start = proto + 3;
      size_t end = url.find("/", start);
      domain = (end != std::string::npos) ? url.substr(start, end - start) : url.substr(start);
      size_t colon = domain.find(":");
      if (colon != std::string::npos) {
        domain = domain.substr(0, colon);
      }
    }
    
    // Site-specific zoom overrides auto-calculated zoom
    if (!domain.empty()) {
      double site_zoom = config.getSiteZoomLevel(domain);
      if (site_zoom != config.getZoomLevel()) {
        zoom_level = site_zoom;
      }
    }
    
    // Apply zoom
    double cef_zoom = std::log2(zoom_level);
    browser_->GetHost()->SetZoomLevel(cef_zoom);
    if (input_handler_) {
      input_handler_->setZoomLevel(cef_zoom);
    }
  }

  // Recreate the renderer with the new dimensions (same backend as before)
  if (backend_ == GraphicsBackend::Framebuffer) {
    renderer_ = std::make_unique<FbRenderer>(width, height, cell_width_,
                                             cell_height_, fb_offset_x_,
                                             fb_offset_y_);
  } else {
    renderer_ = std::make_unique<SixelRenderer>(width, height, cell_width_,
                                                cell_height_);
  }

  LOGB("Browser resized to " << width << "x" << height << ", cells=" << cell_width << "x" << cell_height);
}

void BrowserClient::OnPaint(CefRefPtr<CefBrowser> browser,
                            PaintElementType type, const RectList &dirtyRects,
                            const void *buffer, int width, int height) {
  std::lock_guard<std::mutex> lock(render_mutex_);

  // Skip rendering when URL input, console, popup confirm, JS dialog, file
  // input, download confirm, auth dialog, bookmarks, user scripts, or download manager is
  // active Note: coordinate_mode_active is NOT in this
  // list because they use JS overlays that need the page visible
  if (url_input_active_ || console_active_ || popup_confirm_active_ ||
      js_dialog_active_ || file_input_active_ || download_confirm_active_ ||
      auth_dialog_active_ || bookmarks_active_ || user_scripts_active_ || 
      download_manager_active_) {
    return;
  }

  if (type == PET_VIEW && renderer_ && buffer && width > 0 && height > 0) {
    try {
      // Force full render on first 3 paints to avoid black tiles on startup
      bool force_render = false;
      if (paint_count_ < 3) {
        paint_count_++;
        force_render = true;
      }

      // Force full render if requested after OnLoadEnd
      if (force_next_paint_) {
        force_next_paint_ = false;
        force_render = true;
      }

      // Check if status bar requested a full redraw (e.g., after closing)
      if (status_bar_ && status_bar_->IsRedrawRequested()) {
        status_bar_->ClearRedrawRequest();
        force_render = true;
      }

      if (force_render) {
        renderer_->forceFullRender();
      }

      // Convert CEF RectList to std::vector<CefRect>
      std::vector<CefRect> rects;
      for (size_t i = 0; i < dirtyRects.size(); i++) {
        rects.push_back(dirtyRects[i]);
      }

      // Cache the last frame (for every tab) so it can be re-blitted when the
      // tab becomes active or after a tmux pane switch.
      size_t frame_bytes =
          static_cast<size_t>(width) * static_cast<size_t>(height) * 4;
      if (last_frame_.size() != frame_bytes) {
        last_frame_.resize(frame_bytes);
      }
      memcpy(last_frame_.data(), buffer, frame_bytes);
      last_width_ = width;
      last_height_ = height;
      last_paint_time_ = std::chrono::steady_clock::now();
      {
        const unsigned char *p = (const unsigned char *)buffer;
        const unsigned char *m = p + ((size_t)width / 2 * 4) +
                                 ((size_t)height / 2 * (size_t)width * 4);
        LOGB("Paint " << width << "x" << height << " px=" << (unsigned)p[0]
             << "," << (unsigned)p[1] << "," << (unsigned)p[2] << ","
             << (unsigned)p[3] << " mid=" << (unsigned)m[0] << ","
             << (unsigned)m[1] << "," << (unsigned)m[2] << ","
             << (unsigned)m[3]);
      }

      // Only the active tab blits to /dev/fb0 and owns the status bar.
      if (active_) {
        renderer_->render(buffer, width, height, false, rects);

        // Redraw status bar after sixel render (so it stays visible)
        // Skip for coordinate mode (which has its own yellow status bar)
        // Skip for search mode (which has its own search bar)
        // Allow for mouse emu mode since it doesn't use status bar after
        // initial activation
        if (status_bar_ && !coordinate_mode_active_ && !search_active_) {
          status_bar_->redraw();
        }
      }
    } catch (const std::exception &e) {
      LOGB("Render error: " << e.what());
    } catch (...) {
      LOGB("Unknown render error");
    }
  }
}

void BrowserClient::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
  browser_ = browser;
  LOGB("Browser created");
  // Keep the input handler pointed at this tab's browser once it exists.
  if (active_ && input_handler_) {
    input_handler_->updateBrowser(browser);
  }
}

void BrowserClient::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
  browser_ = nullptr;
  is_closing_ = true;

  // Cancel any pending callbacks to prevent crashes
  {
    std::lock_guard<std::mutex> lock(js_dialog_mutex_);
    if (js_dialog_callback_) {
      js_dialog_callback_->Continue(false, "");
      js_dialog_callback_ = nullptr;
    }
    js_dialog_active_ = false;
  }

  {
    std::lock_guard<std::mutex> lock(file_dialog_mutex_);
    if (file_dialog_callback_) {
      file_dialog_callback_->Cancel();
      file_dialog_callback_ = nullptr;
    }
    file_input_active_ = false;
  }

  {
    std::lock_guard<std::mutex> lock(download_mutex_);
    // download_callback_ doesn't need to be called if rejected
    download_callback_ = nullptr;
    download_confirm_active_ = false;
  }

  if (status_bar_) {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear(false); // Don't redraw title on exit
  }
  LOGB("Browser closing");

  // Notify the tab manager so it can drop this tab (and shut down if it was
  // the last one).
  if (tab_manager_)
    tab_manager_->onTabClosed(this);
}

bool BrowserClient::OnBeforePopup(
    CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int popup_id,
    const CefString &target_url, const CefString &target_frame_name,
    CefLifeSpanHandler::WindowOpenDisposition target_disposition,
    bool user_gesture, const CefPopupFeatures &popupFeatures,
    CefWindowInfo &windowInfo, CefRefPtr<CefClient> &client,
    CefBrowserSettings &settings, CefRefPtr<CefDictionaryValue> &extra_info,
    bool *no_javascript_access) {
  std::string url = target_url.ToString();
  LOGB("OnBeforePopup: Intercepting popup to " << url);

  // Store the URL and show confirmation dialog
  SetPopupConfirmActive(true, url);

  // Return true to cancel the popup creation
  return true;
}

void BrowserClient::OnLoadEnd(CefRefPtr<CefBrowser> browser,
                              CefRefPtr<CefFrame> frame, int httpStatusCode) {
  if (frame->IsMain()) {
    std::string url = frame->GetURL().ToString();
    LOGB("OnLoadEnd: url=" << url << " status=" << httpStatusCode);

    // Reset paint count to force first 3 paints (important for Kitty renderer)
    paint_count_ = 0;
    
    // Force full render on next paint (including first load to avoid race
    // conditions)
    force_next_paint_ = true;
    first_load_complete_ = true;

    // Apply zoom based on config
    ProfileConfig &config = ProfileConfig::getInstance();
    std::string behavior = config.getDefaultZoomBehavior();
    double zoom_level = 0.0; // Default to 1.0 (no zoom)
    
    if (behavior == "auto") {
      // Auto-calculate zoom based on:
      // 1. Terminal cell size (DPI adaptation)
      // 2. Rendering resolution (window size adaptation)
      const double reference_cell_height = 20.0;
      const double reference_cell_width = 10.0;
      const double reference_width = 1600.0;
      const double reference_height = 900.0;
      
      // Factor 1: Cell size ratio (DPI)
      double height_ratio = cell_height_ / reference_cell_height;
      double width_ratio = cell_width_ / reference_cell_width;
      double cell_zoom = (height_ratio * 0.7) + (width_ratio * 0.3);
      
      // Factor 2: Resolution ratio (window size)
      double res_height_ratio = height_ / reference_height;
      double res_width_ratio = width_ / reference_width;
      double res_zoom = (res_height_ratio * 0.5) + (res_width_ratio * 0.5);
      
      // Combine both factors: 60% cell size, 40% resolution
      zoom_level = (cell_zoom * 0.6) + (res_zoom * 0.4);
      
      // Apply bounds (0.25x to 3.0x)
      if (zoom_level < 0.25) zoom_level = 0.25;
      if (zoom_level > 3.0) zoom_level = 3.0;
      
      // Check for site-specific override
      std::string domain;
      size_t proto = url.find("://");
      if (proto != std::string::npos) {
        size_t start = proto + 3;
        size_t end = url.find("/", start);
        domain = (end != std::string::npos) ? url.substr(start, end - start) : url.substr(start);
        size_t colon = domain.find(":");
        if (colon != std::string::npos) {
          domain = domain.substr(0, colon);
        }
      }
      
      // Site-specific zoom overrides auto-calculated zoom
      if (!domain.empty()) {
        double site_zoom = config.getSiteZoomLevel(domain);
        if (site_zoom != config.getZoomLevel()) {
          // Site has custom zoom, use it instead
          zoom_level = site_zoom;
        }
      }
      
    } else if (behavior == "fixed") {
      // Check for site-specific zoom first
      std::string domain;
      size_t proto = url.find("://");
      if (proto != std::string::npos) {
        size_t start = proto + 3;
        size_t end = url.find("/", start);
        domain = (end != std::string::npos) ? url.substr(start, end - start) : url.substr(start);
        // Remove port if present
        size_t colon = domain.find(":");
        if (colon != std::string::npos) {
          domain = domain.substr(0, colon);
        }
      }
      
      if (!domain.empty()) {
        zoom_level = config.getSiteZoomLevel(domain);
      } else {
        zoom_level = config.getZoomLevel();
      }
    }
    // else behavior == "none", zoom_level stays 0.0 (no zoom applied)
    
    // Apply zoom if needed
    if (zoom_level > 0.0 && behavior != "none") {
      // Convert from multiplier to CEF zoom level
      // CEF uses log scale: level = log2(zoom_multiplier)
      double cef_zoom = std::log2(zoom_level);
      browser_->GetHost()->SetZoomLevel(cef_zoom);
      // Update InputHandler's tracked zoom level
      if (input_handler_) {
        input_handler_->setZoomLevel(cef_zoom);
      }
    }

    // Invalidate to trigger redraw
    if (browser_) {
      browser_->GetHost()->Invalidate(PET_VIEW);
    }

    // Clear modes on navigation and request switch to STANDARD mode
    coordinate_mode_active_ = false;
    mode_switch_requested_ = true;
    switch_to_insert_mode_ = false; // Switch to STANDARD mode

    // Clear status bar on new page load only if something is showing
    if (status_bar_) {
      std::lock_guard<std::mutex> lock(render_mutex_);
      // Only clear if we're showing something (not just blank)
      if (!current_options_.empty() || url_input_active_ || console_active_ ||
          popup_confirm_active_ || js_dialog_active_ || file_input_active_ ||
          download_confirm_active_ || bookmarks_active_) {
        status_bar_->clear();
      }
    }
    current_options_.clear();

    LOGB("OnLoadEnd: injecting select detector...");
    injectSelectDetector();
    LOGB("OnLoadEnd: injection complete");

    LOGB("OnLoadEnd: injecting file upload interceptor...");
    injectFileUploadInterceptor();
    LOGB("OnLoadEnd: file upload interceptor injected");

    LOGB("OnLoadEnd: injecting coordinate cursor...");
    {
      std::string js_path = GetJsFilePath("coordinate_cursor.js");
      std::ifstream cf(js_path);
      if (cf.is_open()) {
        std::string js((std::istreambuf_iterator<char>(cf)),
                       std::istreambuf_iterator<char>());
        cf.close();
        frame->ExecuteJavaScript(js, "", 0);
      } else {
        LOGB("Warning: could not load coordinate_cursor.js from " << js_path);
      }
    }

    // Set white background + black text as default for pages that don't
    // specify their own.  No !important so sites that set their own
    // background/color keep theirs.
    frame->ExecuteJavaScript(
        "var s=document.createElement('style');"
        "s.textContent='html,body{background:#fff;color:#000}';"
        "document.documentElement.appendChild(s);",
        frame->GetURL(), 0);

    // Auto-inject user scripts if enabled
    InjectUserScriptsForCurrentPage();
  }
}

void BrowserClient::OnLoadError(CefRefPtr<CefBrowser> browser,
                                CefRefPtr<CefFrame> frame, ErrorCode errorCode,
                                const CefString &errorText,
                                const CefString &failedUrl) {
  if (frame->IsMain() && errorCode != ERR_ABORTED) {
    LOGB("Load error: " << errorText.ToString());
  }
}

bool BrowserClient::OnConsoleMessage(CefRefPtr<CefBrowser> browser,
                                     cef_log_severity_t level,
                                     const CefString &message,
                                     const CefString &source, int line) {
  std::string msg = message.ToString();

  // Log ALL console messages for debugging
  FILE *log = fopen("/tmp/peak_debug.log", "a");
  if (log) {
    fprintf(log, "Console: %s\n", msg.c_str());
    fclose(log);
  }

  // Store console messages for console view
  {
    std::lock_guard<std::mutex> lock(console_mutex_);

    // Skip internal messages if configured to hide them
    bool is_internal = msg.find("[peak]") == 0;
    bool should_show = !is_internal || show_internal_console_logs_;

    if (should_show) {
      // Format message with severity
      std::string level_str;
      switch (level) {
      case LOGSEVERITY_DEBUG:
        level_str = "[DEBUG] ";
        break;
      case LOGSEVERITY_INFO:
        level_str = "[INFO] ";
        break;
      case LOGSEVERITY_WARNING:
        level_str = "[WARN] ";
        break;
      case LOGSEVERITY_ERROR:
        level_str = "[ERROR] ";
        break;
      default:
        level_str = "[LOG] ";
        break;
      }

      console_logs_.push_back(level_str + msg);

      // Keep only last 1000 messages
      if (console_logs_.size() > 1000) {
        console_logs_.erase(console_logs_.begin(), console_logs_.begin() + 100);
      }

      // Trigger status bar redraw if console is active
      if (console_active_ && status_bar_) {
        status_bar_->RequestRedraw();
      }
    }
  }

  // Check for our custom messages
  if (msg.find("PEAK_SELECT_") == 0) {
    parseSelectMessage(msg);
    return true; // Suppress console output
  }

  // Handle DOM change notifications from MutationObserver
  // Used by hint mode and mouse emulation to trigger re-render after overlay changes
  if (msg.find("[peak] DOM_CHANGED") == 0) {
    if (browser_ && browser_->GetHost()) {
      // Add small delay to let CEF finish rendering DOM changes into paint buffer
      // This ensures overlays are included in the frame
      CefRefPtr<CefBrowser> browser = browser_;
      std::thread([browser]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(16)); // ~1 frame at 60fps
        if (browser && browser->GetHost()) {
          browser->GetHost()->Invalidate(PET_VIEW);
        }
      }).detach();
    }
    return true; // Suppress console output
  }

  // File input detected at the clicked coordinate: open our own file picker
  // overlay to avoid the X11 code path crash that SendMouseClickEvent
  // triggers on file inputs.
  if (msg.find("[peak] HINT_FILE_INPUT:") == 0) {
    try {
      std::string pos_str = msg.substr(msg.find("HINT_FILE_INPUT:") + 16);
      size_t colon = pos_str.find(':');
      if (colon != std::string::npos) {
        int x = std::stoi(pos_str.substr(0, colon));
        int y = std::stoi(pos_str.substr(colon + 1));
        LOGB("HINT_FILE_INPUT at (" << x << "," << y << ")");
        SetCoordinateModeActive(false);
        HandleFileInputClick(x, y);
      }
    } catch (const std::exception &e) {
      LOGB("Failed to parse HINT_FILE_INPUT: " << e.what());
    }
    return true;
  }

  // Coordinate click landed on a regular element (not a file input):
  // perform a real mouse click there.
  if (msg.find("[peak] HINT_NOT_FILE_INPUT:") == 0) {
    try {
      std::string pos_str = msg.substr(msg.find("HINT_NOT_FILE_INPUT:") + 20);
      size_t colon = pos_str.find(':');
      if (colon != std::string::npos) {
        int x = std::stoi(pos_str.substr(0, colon));
        int y = std::stoi(pos_str.substr(colon + 1));
        SetCoordinateModeActive(false);
        HandleHintClick(x, y);
      }
    } catch (const std::exception &e) {
      LOGB("Failed to parse HINT_NOT_FILE_INPUT: " << e.what());
    }
    return true;
  }

  if (msg.find("[peak] HINT_") == 0) {
    // Suppress coordinate mode debug messages
    return true;
  }

  // File dialog JS overlay response
  if (msg.find("[peak] FILE_DIALOG_RESPONSE:") == 0) {
    std::string path = msg.substr(msg.find("FILE_DIALOG_RESPONSE:") + 21);
    LOGB("FILE_DIALOG_RESPONSE: " << path);
    HandleFileDialogResponse(path);
    return true;
  }
  if (msg.find("[peak] FILE_DIALOG_CANCEL") == 0) {
    LOGB("FILE_DIALOG_CANCEL");
    HandleFileDialogResponse("");
    return true;
  }

  // File upload from JS interceptor (bypasses CEF file dialog entirely)
  if (msg.find("[peak] FILE_UPLOAD:") == 0) {
    std::string path = msg.substr(msg.find("FILE_UPLOAD:") + 12);
    LOGB("FILE_UPLOAD: " << path);
    HandleFileUpload(path);
    return true;
  }

  // File upload completed — clear state
  if (msg.find("[peak] FILE_UPLOAD_DONE") == 0) {
    LOGB("FILE_UPLOAD_DONE: upload complete");
    {
      FILE *flog = fopen("/tmp/peak_file.log", "a");
      if (flog) {
        fprintf(flog, "FILE_UPLOAD_DONE received from JS\n");
        fclose(flog);
      }
    }
    file_server_.stop();
    {
      std::lock_guard<std::mutex> lock(file_upload_mutex_);
      file_upload_active_ = false;
      file_upload_pending_ = false;
    }
    return true;
  }

  // File upload error from JS
  if (msg.find("[peak] FILE_UPLOAD_ERROR:") == 0) {
    std::string err = msg.substr(msg.find("FILE_UPLOAD_ERROR:") + 18);
    LOGB("FILE_UPLOAD_ERROR: " << err);
    {
      FILE *flog = fopen("/tmp/peak_file.log", "a");
      if (flog) {
        fprintf(flog, "FILE_UPLOAD_ERROR received: %s\n", err.c_str());
        fclose(flog);
      }
    }
    file_server_.stop();
    {
      std::lock_guard<std::mutex> lock(file_upload_mutex_);
      file_upload_active_ = false;
      file_upload_pending_ = false;
    }
    return true;
  }

  // Password autofill feedback from JS
  if (msg.find("[peak] PASSWORD_FILLED") == 0) {
    LOGB("PASSWORD_FILLED");
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showMessage("🔑 Credentials filled");
    return true;
  }
  if (msg.find("[peak] PASSWORD_FILL_ERROR:") == 0) {
    std::string err = msg.substr(msg.find("PASSWORD_FILL_ERROR:") + 19);
    LOGB("PASSWORD_FILL_ERROR: " << err);
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showMessage("🔑 Password fill failed: " + err);
    return true;
  }

  // File upload dialog requested by the page — open the Firefox-style file
  // chooser popup. The user picks a file there; FileChooserEnter() then runs
  // the proven HandleFileUpload() pipeline (local HTTP server + fetch).
  if (msg.find("[peak] FILE_UPLOAD_DIALOG_OPEN") == 0) {
    LOGB("FILE_UPLOAD_DIALOG_OPEN: opening file chooser popup");
    OpenFileChooser(true);
    return true;
  }







  if (msg.find("[peak] VISUAL_MODE_COPY:") == 0) {
    // Copy selected text from visual mode
    std::string text =
        msg.substr(msg.find("VISUAL_MODE_COPY:") + 17);
    if (!text.empty()) {
      Clipboard::copyToClipboard(text);
      LOGB("Copied selection: " << text.length() << " characters");
    }
    // Visual mode will be exited by the input handler (y key)
    return true;
  }
  if (msg.find("[peak] VISUAL_MODE_CLOSED") == 0) {
    // Visual mode closed - just log it
    // Mode switch is handled by input handler (ESC key)
    LOGB("Visual mode closed");
    return true;
  }
  if (msg.find("[peak] PHYSICAL_MOUSE_TEXT_INPUT") == 0) {
    // Physical mouse clicked on a text input - switch to INSERT mode
    LOGB("Physical mouse clicked text input - switching to INSERT mode");
    mode_switch_requested_ = true;
    switch_to_insert_mode_ = true;
    if (browser_) {
      browser_->GetHost()->Invalidate(PET_VIEW);
    }
    return true;
  }
  if (msg.find("[peak] INPUT_FOCUS:") == 0) {
    // A page input field gained focus (e.g. the coordinate cursor clicked it)
    // - switch to INSERT mode automatically so typing just works.
    std::string v = msg.substr(msg.find("INPUT_FOCUS:") + 12);
    if (v == "1") {
      mode_switch_requested_ = true;
      switch_to_insert_mode_ = true;
      if (browser_) {
        browser_->GetHost()->Invalidate(PET_VIEW);
      }
    }
    return true;
  }


  // Check for inspect mode messages
  if (msg.find("[peak] INSPECT_MODE:") == 0) {
    // Parse inspect mode status: [peak] INSPECT_MODE:ON or OFF
    std::string status = msg.substr(msg.find("INSPECT_MODE:") + 12);
    LOGB("Inspect mode: " << status);
    return true;
  }
  if (msg.find("[peak] INSPECT_MODE_") == 0) {
    // Suppress inspect mode debug messages
    return true;
  }

  return false; // Show other console messages
}

void BrowserClient::OnTitleChange(CefRefPtr<CefBrowser> browser,
                                  const CefString &title) {
  std::string page_title = title.ToString();
  current_page_title_ = page_title; // Store for bookmarks
  std::string window_title = "peak - " + page_title;
  LOGB("OnTitleChange called: " << page_title);

  // Use printf and fflush for immediate output
  printf("\033]0;%s\007", window_title.c_str());
  fflush(stdout);

  // Show title in status bar
  if (status_bar_) {
    status_bar_->showTitle(page_title, input_mode_);
  }
}

void BrowserClient::injectSelectDetector() {
  if (!browser_)
    return;

  // Read JavaScript file from executable directory
  std::string js_path = GetJsFilePath("select_detector.js");
  std::ifstream js_file(js_path);
  if (!js_file.is_open()) {
    LOGB("Warning: Could not load select_detector.js from " << js_path);
    return;
  }

  std::stringstream buffer;
  buffer << js_file.rdbuf();
  std::string js_code = buffer.str();

  // Execute JavaScript in main frame
  CefRefPtr<CefFrame> frame = browser_->GetMainFrame();
  if (frame) {
    frame->ExecuteJavaScript(js_code, frame->GetURL(), 0);
    LOGB("Select detector injected");
  }
}

void BrowserClient::injectFileUploadInterceptor() {
  if (!browser_)
    return;

  std::string js_path = GetJsFilePath("file_upload_interceptor.js");
  std::ifstream js_file(js_path);
  if (!js_file.is_open()) {
    LOGB("Warning: Could not load file_upload_interceptor.js from " << js_path);
    return;
  }

  std::stringstream buffer;
  buffer << js_file.rdbuf();
  std::string js_code = buffer.str();

  CefRefPtr<CefFrame> frame = browser_->GetMainFrame();
  if (frame) {
    frame->ExecuteJavaScript(js_code, frame->GetURL(), 0);
    LOGB("File upload interceptor injected");
  }
}

// Escape a string for embedding in a JSON/JS double-quoted literal.
// Control characters are dropped; UTF-8 bytes pass through unchanged.
static std::string FcEscapeJs(const std::string &s) {
  std::string out;
  out.reserve(s.size() + 8);
  for (unsigned char c : s) {
    switch (c) {
    case '\\':
      out += "\\\\";
      break;
    case '"':
      out += "\\\"";
      break;
    default:
      if (c >= 32)
        out += (char)c;
      break;
    }
  }
  return out;
}

void BrowserClient::OpenFileChooser(bool for_upload) {
  if (is_closing_)
    return;

  fc_for_upload_ = for_upload;
  // Accept filters only apply to native CEF dialogs
  if (for_upload)
    fc_accept_ext_.clear();

  if (fc_dir_.empty()) {
    const char *home = getenv("HOME");
    fc_dir_ = (home && *home) ? home : "/";
  }

  fc_selected_ = 0;
  fc_scroll_ = 0;
  FcScanDirectory();
  file_chooser_active_ = true;
  LOGB("FileChooser: open at " << fc_dir_ << " (" << fc_entries_.size()
                               << " entries)");
  FcSendToJs();
}

void BrowserClient::FcScanDirectory() {
  auto sort_fn = [](const FileChooserEntry &a, const FileChooserEntry &b) {
    std::string la = a.name, lb = b.name;
    for (auto &c : la)
      c = std::tolower((unsigned char)c);
    for (auto &c : lb)
      c = std::tolower((unsigned char)c);
    return la < lb;
  };

  auto scan = [&](const std::string &dir,
                  std::vector<FileChooserEntry> &dirs,
                  std::vector<FileChooserEntry> &files) -> bool {
    DIR *d = opendir(dir.c_str());
    if (!d)
      return false;
    struct dirent *ent;
    while ((ent = readdir(d)) != nullptr) {
      std::string name = ent->d_name;
      if (name == "." || name == "..")
        continue;
      std::string full = dir;
      if (full.empty() || full.back() != '/')
        full += '/';
      full += name;
      bool is_dir = (ent->d_type == DT_DIR);
      struct stat st;
      if (stat(full.c_str(), &st) == 0) {
        is_dir = S_ISDIR(st.st_mode); // authoritative for symlinks etc.
      }
      if (is_dir) {
        dirs.push_back({name, true});
      } else {
        files.push_back({name, false});
      }
    }
    closedir(d);
    std::sort(dirs.begin(), dirs.end(), sort_fn);
    std::sort(files.begin(), files.end(), sort_fn);
    return true;
  };

  std::vector<FileChooserEntry> dirs, files;
  if (!scan(fc_dir_, dirs, files)) {
    // Directory vanished or is unreadable: fall back to HOME, then /
    const char *home = getenv("HOME");
    fc_dir_ = (home && *home) ? home : "/";
    dirs.clear();
    files.clear();
    scan(fc_dir_, dirs, files);
  }

  // Apply accept filters (from CEF OnFileDialog) to regular files. If the
  // filter would hide everything, show all files instead.
  if (!fc_accept_ext_.empty()) {
    std::vector<FileChooserEntry> filtered;
    for (const auto &f : files) {
      size_t dot = f.name.find_last_of('.');
      if (dot != std::string::npos) {
        std::string ext = f.name.substr(dot + 1);
        for (auto &c : ext)
          c = std::tolower((unsigned char)c);
        if (std::find(fc_accept_ext_.begin(), fc_accept_ext_.end(), ext) !=
            fc_accept_ext_.end()) {
          filtered.push_back(f);
        }
      }
    }
    if (!filtered.empty())
      files.swap(filtered);
  }

  fc_entries_ = std::move(dirs);
  fc_entries_.insert(fc_entries_.end(), files.begin(), files.end());
}

void BrowserClient::FcSendToJs() {
  if (!browser_ || !browser_->GetMainFrame())
    return;

  // Make sure the renderer script is present (idempotent inside the script)
  static std::string chooser_js;
  if (chooser_js.empty()) {
    std::string js_path = GetJsFilePath("file_chooser.js");
    std::ifstream js_file(js_path);
    if (js_file.is_open()) {
      std::stringstream buffer;
      buffer << js_file.rdbuf();
      chooser_js = buffer.str();
    } else {
      LOGB("Warning: Could not load file_chooser.js from " << js_path);
    }
  }
  if (!chooser_js.empty()) {
    browser_->GetMainFrame()->ExecuteJavaScript(chooser_js, "", 0);
  }

  std::string items = "[";
  for (size_t i = 0; i < fc_entries_.size(); i++) {
    if (i)
      items += ",";
    items += "{\"n\":\"" + FcEscapeJs(fc_entries_[i].name) +
             "\",\"d\":" + (fc_entries_[i].is_dir ? "true" : "false") + "}";
  }
  items += "]";

  std::string js =
      "if(window.__tb_fc_show){window.__tb_fc_show(" +
      std::to_string(fc_selected_) + "," + std::to_string(fc_scroll_) +
      ",\"" + FcEscapeJs(fc_dir_) + "\"," + items + ");}";
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
}

void BrowserClient::FileChooserNavigate(int delta) {
  if (!file_chooser_active_ || fc_entries_.empty())
    return;

  int n = static_cast<int>(fc_entries_.size());
  fc_selected_ += delta;
  if (fc_selected_ < 0)
    fc_selected_ = 0;
  if (fc_selected_ >= n)
    fc_selected_ = n - 1;

  // Keep the selection inside the visible window
  if (fc_selected_ < fc_scroll_)
    fc_scroll_ = fc_selected_;
  if (fc_selected_ >= fc_scroll_ + fc_view_rows_)
    fc_scroll_ = fc_selected_ - fc_view_rows_ + 1;

  FcSendToJs();
}

void BrowserClient::FileChooserTop() {
  if (!file_chooser_active_)
    return;
  fc_selected_ = 0;
  fc_scroll_ = 0;
  FcSendToJs();
}

void BrowserClient::FileChooserBottom() {
  if (!file_chooser_active_ || fc_entries_.empty())
    return;
  fc_selected_ = static_cast<int>(fc_entries_.size()) - 1;
  if (fc_selected_ >= fc_view_rows_)
    fc_scroll_ = fc_selected_ - fc_view_rows_ + 1;
  else
    fc_scroll_ = 0;
  FcSendToJs();
}

void BrowserClient::FileChooserEnter() {
  if (!file_chooser_active_)
    return;

  if (fc_selected_ < 0 ||
      fc_selected_ >= static_cast<int>(fc_entries_.size()))
    return; // empty directory

  const FileChooserEntry &e = fc_entries_[fc_selected_];
  if (e.is_dir) {
    std::string next = fc_dir_;
    if (next.empty() || next.back() != '/')
      next += '/';
    next += e.name;
    fc_dir_ = next;
    fc_selected_ = 0;
    fc_scroll_ = 0;
    FcScanDirectory();
    LOGB("FileChooser: enter dir " << fc_dir_);
    FcSendToJs();
    return;
  }

  std::string path = fc_dir_;
  if (path.empty() || path.back() != '/')
    path += '/';
  path += e.name;

  file_chooser_active_ = false;
  if (browser_ && browser_->GetMainFrame()) {
    browser_->GetMainFrame()->ExecuteJavaScript(
        "if(window.__tb_fc_close)window.__tb_fc_close();", "", 0);
  }
  LOGB("FileChooser: selected " << path);

  if (fc_for_upload_) {
    HandleFileUpload(path);
  } else {
    HandleFileDialogResponse(path);
  }
}

void BrowserClient::FileChooserParent() {
  if (!file_chooser_active_ || fc_dir_ == "/")
    return;

  size_t pos = fc_dir_.find_last_of('/');
  if (pos == std::string::npos)
    return;

  std::string last_component =
      fc_dir_.substr(pos + 1); // empty only for a trailing slash
  fc_dir_ = (pos == 0) ? "/" : fc_dir_.substr(0, pos);
  FcScanDirectory();

  // Select the directory we just came out of
  fc_selected_ = 0;
  fc_scroll_ = 0;
  if (!last_component.empty()) {
    for (size_t i = 0; i < fc_entries_.size(); i++) {
      if (fc_entries_[i].is_dir && fc_entries_[i].name == last_component) {
        fc_selected_ = static_cast<int>(i);
        if (fc_selected_ >= fc_view_rows_)
          fc_scroll_ = fc_selected_ - fc_view_rows_ + 1;
        break;
      }
    }
  }
  LOGB("FileChooser: parent dir " << fc_dir_);
  FcSendToJs();
}

void BrowserClient::CancelFileChooser() {
  if (!file_chooser_active_)
    return;

  file_chooser_active_ = false;
  LOGB("FileChooser: canceled");

  if (browser_ && browser_->GetMainFrame()) {
    browser_->GetMainFrame()->ExecuteJavaScript(
        "if(window.__tb_fc_close)window.__tb_fc_close();", "", 0);
  }

  if (fc_for_upload_) {
    CancelFileUpload();
  } else {
    HandleFileDialogResponse("");
  }
}

void BrowserClient::HandleFileUpload(const std::string &file_path) {
  {
    FILE *log = fopen("/tmp/peak_file.log", "a");
    if (log) {
      fprintf(log, "HandleFileUpload: called with path='%s'\n", file_path.c_str());
      fclose(log);
    }
  }

  if (is_closing_ || !browser_ || !browser_->GetMainFrame()) {
    FILE *log = fopen("/tmp/peak_file.log", "a");
    if (log) {
      fprintf(log, "HandleFileUpload: ABORT is_closing=%d browser=%d mainframe=%d\n",
              (int)is_closing_.load(), (browser_ != nullptr), (browser_ && browser_->GetMainFrame() ? 1 : 0));
      fclose(log);
    }
    file_input_active_ = false;
    file_upload_pending_ = false;
    return;
  }

  if (file_path.empty()) {
    LOGB("HandleFileUpload: empty path");
    file_input_active_ = false;
    file_upload_pending_ = false;
    return;
  }

  // Expand ~ to home directory
  std::string expanded_path = file_path;
  if (expanded_path[0] == '~') {
    const char *home = getenv("HOME");
    if (home) {
      expanded_path = std::string(home) + expanded_path.substr(1);
    }
  }

  // Resolve relative paths to absolute
  if (!expanded_path.empty() && expanded_path[0] != '/') {
    char *abs_path = realpath(expanded_path.c_str(), nullptr);
    if (abs_path) {
      expanded_path = abs_path;
      free(abs_path);
    } else {
      LOGB("HandleFileUpload: file not found (relative): " << file_path);
      file_input_active_ = false;
      file_upload_pending_ = false;
      std::string err_js =
          "if(window.__tb_file_upload_error)window.__tb_file_upload_error('File not found: " + file_path + "');";
      browser_->GetMainFrame()->ExecuteJavaScript(err_js, "", 0);
      return;
    }
  }

  // Validate file exists and is readable
  struct stat st;
  if (stat(expanded_path.c_str(), &st) != 0) {
    LOGB("HandleFileUpload: file not found: " << expanded_path);
    file_input_active_ = false;
    file_upload_pending_ = false;
    std::string err_js =
        "if(window.__tb_file_upload_error)window.__tb_file_upload_error('File not found: " + expanded_path + "');";
    browser_->GetMainFrame()->ExecuteJavaScript(err_js, "", 0);
    return;
  }
  if (!S_ISREG(st.st_mode)) {
    LOGB("HandleFileUpload: not a regular file: " << expanded_path);
    file_input_active_ = false;
    file_upload_pending_ = false;
    std::string err_js =
        "if(window.__tb_file_upload_error)window.__tb_file_upload_error('Not a regular file');";
    browser_->GetMainFrame()->ExecuteJavaScript(err_js, "", 0);
    return;
  }
  if (access(expanded_path.c_str(), R_OK) != 0) {
    LOGB("HandleFileUpload: not readable: " << expanded_path);
    file_input_active_ = false;
    file_upload_pending_ = false;
    std::string err_js =
        "if(window.__tb_file_upload_error)window.__tb_file_upload_error('Not readable (permission denied)');";
    browser_->GetMainFrame()->ExecuteJavaScript(err_js, "", 0);
    return;
  }

  // User confirmed path — no longer pending. Clear file input mode so
  // keystrokes stop being captured and OnPaint resumes rendering.
  // file_upload_active_ stays true until FILE_UPLOAD_DONE from JS.
  file_input_active_ = false;
  file_upload_pending_ = false;

  // Extract filename from path
  std::string filename = expanded_path;
  size_t last_slash = filename.find_last_of('/');
  if (last_slash != std::string::npos) {
    filename = filename.substr(last_slash + 1);
  }

  // Determine MIME type from extension
  std::string mime_type = "application/octet-stream";
  size_t dot = filename.find_last_of('.');
  if (dot != std::string::npos) {
    std::string ext = filename.substr(dot + 1);
    for (auto &c : ext) c = std::tolower(c);
    if (ext == "mp4") mime_type = "video/mp4";
    else if (ext == "webm") mime_type = "video/webm";
    else if (ext == "mkv") mime_type = "video/x-matroska";
    else if (ext == "avi") mime_type = "video/x-msvideo";
    else if (ext == "mov") mime_type = "video/quicktime";
    else if (ext == "png") mime_type = "image/png";
    else if (ext == "jpg" || ext == "jpeg") mime_type = "image/jpeg";
    else if (ext == "gif") mime_type = "image/gif";
    else if (ext == "webp") mime_type = "image/webp";
    else if (ext == "pdf") mime_type = "application/pdf";
    else if (ext == "txt") mime_type = "text/plain";
    else if (ext == "csv") mime_type = "text/csv";
    else if (ext == "json") mime_type = "application/json";
  }

  // Escape special chars in filename for JS string
  std::string safe_filename;
  for (char c : filename) {
    if (c == '\\') safe_filename += "\\\\";
    else if (c == '\'') safe_filename += "\\'";
    else if (c == '\n') safe_filename += "\\n";
    else safe_filename += c;
  }

  // Stop any previous file server
  file_server_.stop();

  // Start local HTTP file server — streams file via sendfile(), works for any size
  if (!file_server_.start(expanded_path)) {
    LOGB("HandleFileUpload: file_server start failed");
    file_upload_active_ = false;
    std::string err_js =
        "if(window.__tb_file_upload_error)window.__tb_file_upload_error('Failed to start file server');";
    browser_->GetMainFrame()->ExecuteJavaScript(err_js, "", 0);
    return;
  }

  int srv_port = file_server_.port();
  std::string url = "http://127.0.0.1:" + std::to_string(srv_port) + "/";

  // Tell JS to fetch file from local server and create File object
  std::string js =
      "if(window.__tb_file_upload_from_url)window.__tb_file_upload_from_url('"
      + url + "','" + safe_filename + "','" + mime_type + "');";

  FILE *flog = fopen("/tmp/peak_file.log", "a");
  if (flog) {
    fprintf(flog, "HandleFileUpload: fetch url='%s' filename='%s' mime='%s'\n",
            url.c_str(), safe_filename.c_str(), mime_type.c_str());
    fclose(flog);
  }
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);

// State is cleared by JS response or by CancelFileUpload
}

void BrowserClient::CancelFileUpload() {
  LOGB("CancelFileUpload: dismissing JS overlay");

  // Stop the file server
  file_server_.stop();

  // Dismiss the JS overlay
  if (browser_ && browser_->GetMainFrame()) {
    std::string js = "if(window.__tb_file_upload_cancel)window.__tb_file_upload_cancel();";
    browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
  }

  // Clear all file upload state
  {
    std::lock_guard<std::mutex> lock(file_upload_mutex_);
    file_upload_active_ = false;
    file_upload_pending_ = false;
  }
  file_input_active_ = false;

  if (browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

void BrowserClient::parseSelectMessage(const std::string &message) {
  if (!status_bar_)
    return;

  if (message.find("PEAK_SELECT_FOCUSED:") == 0) {
    // Extract JSON data
    std::string json =
        message.substr(message.find("PEAK_SELECT_FOCUSED:") + 33);

    // Simple JSON parsing (find options array and selectedIndex)
    std::vector<std::string> options;
    int selected_index = 0;

    // Extract options (looking for ["text1","text2",...])
    size_t options_start = json.find("[");
    size_t options_end = json.find("]");
    if (options_start != std::string::npos &&
        options_end != std::string::npos) {
      std::string options_str =
          json.substr(options_start + 1, options_end - options_start - 1);

      // Parse each option
      size_t pos = 0;
      while (pos < options_str.length()) {
        size_t quote_start = options_str.find('"', pos);
        if (quote_start == std::string::npos)
          break;

        size_t quote_end = options_str.find('"', quote_start + 1);
        if (quote_end == std::string::npos)
          break;

        std::string option =
            options_str.substr(quote_start + 1, quote_end - quote_start - 1);
        options.push_back(option);
        pos = quote_end + 1;
      }
    }

    // Extract selectedIndex
    size_t index_pos = json.find("selectedIndex\":");
    if (index_pos != std::string::npos) {
      selected_index = std::atoi(json.c_str() + index_pos + 15);
    }

    // Show status bar
    if (!options.empty()) {
      current_options_ = options;               // Save for later updates
      current_selected_index_ = selected_index; // Save current index

      std::lock_guard<std::mutex> lock(render_mutex_);
      status_bar_->showComboboxOptions(options, selected_index);
    }

  } else if (message == "PEAK_SELECT_BLURRED") {
    {
      std::lock_guard<std::mutex> lock(render_mutex_);
      status_bar_->clear();
    }
    current_options_.clear();     // Clear saved options
    current_selected_index_ = -1; // Reset index

  } else if (message.find("PEAK_SELECT_CHANGED:") == 0) {
    // Extract new selected index
    int new_index =
        std::atoi(message.c_str() + 23); // Skip "PEAK_SELECT_CHANGED:"

    FILE *log = fopen("/tmp/peak_debug.log", "a");
    if (log) {
      fprintf(log, "SELECT_CHANGED: new_index=%d, have_options=%d\n", new_index,
              (int)current_options_.size());
      fclose(log);
    }

    // Update status bar if it's currently showing
    if (status_bar_ && !current_options_.empty()) {
      std::lock_guard<std::mutex> lock(render_mutex_);
      status_bar_->showComboboxOptions(current_options_, new_index);
    }
  }
}

bool BrowserClient::HandleSelectNavigation(int direction) {
  // Only handle if status bar is showing and we have options
  if (current_options_.empty() || current_selected_index_ < 0) {
    return false;
  }

  // Calculate new selection
  int new_index = current_selected_index_ + direction;

  // Clamp to valid range
  if (new_index < 0) {
    new_index = 0;
  }
  if (new_index >= (int)current_options_.size()) {
    new_index = current_options_.size() - 1;
  }

  // Only update if index actually changed
  if (new_index == current_selected_index_) {
    return true; // We handled it, but no change needed
  }

  current_selected_index_ = new_index;

  // Update status bar display
  {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showComboboxOptions(current_options_, current_selected_index_);
  }

  // Update the actual select element in CEF via JavaScript
  if (browser_ && browser_->GetMainFrame()) {
    std::string js = "if (window._peak_focused_select) { "
                     "window._peak_focused_select.selectedIndex = " +
                     std::to_string(current_selected_index_) +
                     "; "
                     "window._peak_select_index = " +
                     std::to_string(current_selected_index_) + "; }";
    browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
  }

  return true; // We handled it
}

bool BrowserClient::HandleSelectConfirm() {
  // Only handle if status bar is showing and we have options
  if (current_options_.empty() || current_selected_index_ < 0) {
    return false;
  }

  // Set the final selection in CEF and trigger change event
  if (browser_ && browser_->GetMainFrame()) {
    std::string js = "if (window._peak_focused_select) { "
                     "window._peak_focused_select.selectedIndex = " +
                     std::to_string(current_selected_index_) +
                     "; "
                     // Trigger change event so the page knows selection changed
                     "var event = new Event('change', { bubbles: true }); "
                     "window._peak_focused_select.dispatchEvent(event); "
                     // Blur the select to close it
                     "window._peak_focused_select.blur(); "
                     "}";
    browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
  }

  // Clear status bar and state
  {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear();
  }
  current_options_.clear();
  current_selected_index_ = -1;

  return true; // We handled it
}

void BrowserClient::ExecuteJavaScript(const std::string &code) {
  if (browser_ && browser_->GetMainFrame()) {
    // Escape backslashes and quotes in user code
    std::string escaped_code = code;
    size_t pos = 0;
    while ((pos = escaped_code.find('\\', pos)) != std::string::npos) {
      escaped_code.replace(pos, 1, "\\\\");
      pos += 2;
    }
    pos = 0;
    while ((pos = escaped_code.find('"', pos)) != std::string::npos) {
      escaped_code.replace(pos, 1, "\\\"");
      pos += 2;
    }
    pos = 0;
    while ((pos = escaped_code.find('\n', pos)) != std::string::npos) {
      escaped_code.replace(pos, 1, "\\n");
      pos += 2;
    }

    // Execute code in global scope using indirect eval
    std::string wrapped_code = "(function() { "
                               "  try { "
                               "    var result = (0, eval)(\"" +
                               escaped_code +
                               "\"); "
                               "    console.log('← ' + (result !== undefined ? "
                               "result : 'undefined')); "
                               "    return result; "
                               "  } catch(e) { "
                               "    console.error('✗ ' + e.toString()); "
                               "  } "
                               "})();";

    browser_->GetMainFrame()->ExecuteJavaScript(wrapped_code, "", 0);
  }
}

void BrowserClient::SetPopupConfirmActive(bool active, const std::string &url) {
  popup_confirm_active_ = active;
  popup_url_ = url;

  if (active) {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showPopupConfirm(url);
  } else {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear();
  }
}

void BrowserClient::HandlePopupResponse(bool accept) {
  if (!popup_confirm_active_) {
    return;
  }

  std::string url = popup_url_;
  SetPopupConfirmActive(false);

  if (accept && browser_ && browser_->GetMainFrame()) {
    LOGB("Opening popup URL in current window: " << url);
    browser_->GetMainFrame()->LoadURL(url);
  } else {
    LOGB("Popup rejected by user");
    // Force a repaint to clear the status bar
    if (browser_ && browser_->GetHost()) {
      browser_->GetHost()->Invalidate(PET_VIEW);
    }
  }
}

bool BrowserClient::OnJSDialog(CefRefPtr<CefBrowser> browser,
                               const CefString &origin_url,
                               CefJSDialogHandler::JSDialogType dialog_type,
                               const CefString &message_text,
                               const CefString &default_prompt_text,
                               CefRefPtr<CefJSDialogCallback> callback,
                               bool &suppress_message) {
  LOGB("JS Dialog: type=" << dialog_type
                          << " message=" << message_text.ToString());

  std::lock_guard<std::mutex> lock(js_dialog_mutex_);

  // Store dialog info
  js_dialog_active_ = true;
  js_dialog_type_ = dialog_type;
  js_dialog_message_ = message_text.ToString();
  js_dialog_prompt_default_ = default_prompt_text.ToString();
  js_dialog_callback_ = callback;

  // Show appropriate dialog in status bar
  std::lock_guard<std::mutex> render_lock(render_mutex_);
  switch (dialog_type) {
  case JSDIALOGTYPE_ALERT:
    status_bar_->showJSAlert(js_dialog_message_);
    break;
  case JSDIALOGTYPE_CONFIRM:
    status_bar_->showJSConfirm(js_dialog_message_);
    break;
  case JSDIALOGTYPE_PROMPT:
    status_bar_->showJSPrompt(js_dialog_message_, js_dialog_prompt_default_);
    break;
  }

  // Return true to handle it ourselves
  return true;
}

void BrowserClient::HandleJSDialogResponse(bool success,
                                           const std::string &input) {
  // Don't handle if browser is closing
  if (is_closing_) {
    return;
  }

  CefRefPtr<CefJSDialogCallback> callback;

  {
    std::lock_guard<std::mutex> lock(js_dialog_mutex_);

    if (!js_dialog_active_ || !js_dialog_callback_) {
      return;
    }

    LOGB("JS Dialog response: success=" << success << " input=" << input);

    // Take ownership of callback before unlocking
    callback = js_dialog_callback_;
    js_dialog_callback_ = nullptr;
    js_dialog_active_ = false;
  }

  // Clear the dialog from status bar
  {
    std::lock_guard<std::mutex> lock(render_mutex_);
    if (status_bar_) {
      status_bar_->clear();
    }
  }

  // Call the callback outside the mutex to avoid potential deadlocks
  if (callback) {
    callback->Continue(success, input);
  }

  // Force repaint to clear the dialog
  if (browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

bool BrowserClient::OnFileDialog(
    CefRefPtr<CefBrowser> browser, CefDialogHandler::FileDialogMode mode,
    const CefString &title, const CefString &default_file_path,
    const std::vector<CefString> &accept_filters,
    const std::vector<CefString> &accept_extensions,
    const std::vector<CefString> &accept_descriptions,
    CefRefPtr<CefFileDialogCallback> callback) {
  LOGB("File Dialog: mode=" << mode << " title=" << title.ToString()
                            << " default_path="
                            << default_file_path.ToString());

  std::lock_guard<std::mutex> lock(file_dialog_mutex_);

  // If a dialog is already pending, cancel the old one first
  if (file_input_active_ && file_dialog_callback_) {
    LOGB("File Dialog: cancelling previous pending dialog");
    file_dialog_callback_->Cancel();
    file_dialog_callback_ = nullptr;
  }

  file_input_active_ = true;
  file_dialog_callback_ = callback;

  // Start in the directory of the default file path, if any
  std::string dp = default_file_path.ToString();
  if (!dp.empty()) {
    size_t slash = dp.find_last_of('/');
    if (slash == std::string::npos)
      fc_dir_.clear(); // OpenFileChooser falls back to HOME
    else if (slash == 0)
      fc_dir_ = "/";
    else
      fc_dir_ = dp.substr(0, slash);
  }

  // Build a lowercase extension whitelist from the accept filters
  fc_accept_ext_.clear();
  auto add_ext = [this](std::string tok) {
    if (tok.rfind("*.", 0) == 0)
      tok = tok.substr(2);
    if (!tok.empty() && tok[0] == '.')
      tok = tok.substr(1);
    for (auto &c : tok)
      c = std::tolower((unsigned char)c);
    if (!tok.empty() && tok != "*" &&
        std::find(fc_accept_ext_.begin(), fc_accept_ext_.end(), tok) ==
            fc_accept_ext_.end()) {
      fc_accept_ext_.push_back(tok);
    }
  };
  for (const auto &f : accept_filters) {
    std::string s = f.ToString();
    size_t start = 0;
    while (start <= s.size()) {
      size_t comma = s.find(',', start);
      if (comma == std::string::npos) {
        add_ext(s.substr(start));
        break;
      }
      add_ext(s.substr(start, comma - start));
      start = comma + 1;
    }
  }
  for (const auto &e : accept_extensions) {
    add_ext(e.ToString());
  }

  // Open the Firefox-style chooser popup; confirming routes the picked file
  // through HandleFileDialogResponse() which continues the CEF callback.
  OpenFileChooser(false);

  return true;
}

void BrowserClient::HandleFileDialogResponse(const std::string &file_path) {
  // Don't handle if browser is closing
  if (is_closing_) {
    return;
  }

  CefRefPtr<CefFileDialogCallback> callback;

  {
    std::lock_guard<std::mutex> lock(file_dialog_mutex_);

    if (!file_input_active_ || !file_dialog_callback_) {
      return;
    }

    LOGB("File Dialog response: file_path=" << file_path);

    // Take ownership of callback before unlocking
    callback = file_dialog_callback_;
    file_dialog_callback_ = nullptr;
    file_input_active_ = false;
  }

  // Call the callback outside the mutex to avoid potential deadlocks
  if (callback) {
    if (!file_path.empty()) {
      std::vector<CefString> file_paths;
      file_paths.push_back(file_path);
      callback->Continue(file_paths);
    } else {
      callback->Cancel();
    }
  }

  if (browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

bool BrowserClient::GetAuthCredentials(
    CefRefPtr<CefBrowser> browser, const CefString &origin_url, bool isProxy,
    const CefString &host, int port, const CefString &realm,
    const CefString &scheme, CefRefPtr<CefAuthCallback> callback) {
  
  // If this is a proxy authentication request, check for configured credentials
  if (isProxy) {
    ProfileConfig &config = ProfileConfig::getInstance();
    std::string proxy_username = config.getProxyUsername();
    std::string proxy_password = config.getProxyPassword();
    
    // If proxy credentials are configured, use them automatically
    if (!proxy_username.empty()) {
      callback->Continue(proxy_username, proxy_password);
      return true;
    }
    // Otherwise fall through to show interactive dialog
  }
  
  std::lock_guard<std::mutex> lock(auth_mutex_);

  auth_dialog_active_ = true;
  auth_callback_ = callback;
  auth_realm_ = realm.ToString();
  
  // If realm is empty, show host:port instead
  std::string display_realm = auth_realm_;
  if (display_realm.empty()) {
    display_realm = host.ToString() + ":" + std::to_string(port);
  }

  if (status_bar_) {
    status_bar_->showAuthDialog("Username:", display_realm);
  }

  return true;
}

void BrowserClient::HandleAuthResponse(bool accept,
                                       const std::string &username,
                                       const std::string &password) {
  if (is_closing_) {
    return;
  }

  CefRefPtr<CefAuthCallback> callback;

  {
    std::lock_guard<std::mutex> lock(auth_mutex_);

    if (!auth_dialog_active_ || !auth_callback_) {
      return;
    }

    LOGB("Auth response: accept=" << accept << " username=" << username);

    callback = auth_callback_;
    auth_callback_ = nullptr;
    auth_dialog_active_ = false;
    auth_realm_.clear();
  }

  if (callback) {
    if (accept && !username.empty()) {
      callback->Continue(username, password);
    } else {
      callback->Cancel();
    }
  }

  if (browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

bool BrowserClient::OnBeforeDownload(
    CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
    const CefString &suggested_name,
    CefRefPtr<CefBeforeDownloadCallback> callback) {
  std::lock_guard<std::mutex> lock(download_mutex_);

  download_filename_ = suggested_name.ToString();
  download_url_ = download_item->GetURL().ToString();
  download_callback_ = callback;
  download_confirm_active_ = true;

  // Add to downloads list
  DownloadEntry entry;
  entry.id = download_item->GetId();
  entry.filename = suggested_name.ToString();
  entry.url = download_item->GetURL().ToString();
  entry.full_path = "";
  entry.total_bytes = 0;
  entry.received_bytes = 0;
  entry.percent_complete = 0;
  entry.speed = 0;
  entry.is_complete = false;
  entry.is_canceled = false;
  entry.is_in_progress = false;
  downloads_list_.push_back(entry);

  LOGB("Download request: " << download_filename_ << " from " << download_url_);

  // Show download confirmation dialog
  std::lock_guard<std::mutex> render_lock(render_mutex_);
  status_bar_->showDownloadConfirm(download_filename_, download_url_);

  return true;
}

void BrowserClient::OnDownloadUpdated(
    CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
    CefRefPtr<CefDownloadItemCallback> callback) {
  std::lock_guard<std::mutex> lock(download_mutex_);

  // Find and update the download entry
  int32_t id = download_item->GetId();
  for (auto &entry : downloads_list_) {
    if (entry.id == id) {
      // Update filename - use suggested name if available, otherwise extract
      // from path
      std::string suggested = download_item->GetSuggestedFileName().ToString();
      if (!suggested.empty()) {
        entry.filename = suggested;
      } else {
        std::string path = download_item->GetFullPath().ToString();
        if (!path.empty()) {
          size_t pos = path.find_last_of("/\\");
          entry.filename =
              (pos != std::string::npos) ? path.substr(pos + 1) : path;
        }
      }
      entry.full_path = download_item->GetFullPath().ToString();
      entry.total_bytes = download_item->GetTotalBytes();
      entry.received_bytes = download_item->GetReceivedBytes();
      entry.percent_complete = download_item->GetPercentComplete();
      entry.speed = download_item->GetCurrentSpeed();
      entry.is_complete = download_item->IsComplete();
      entry.is_canceled = download_item->IsCanceled();
      entry.is_in_progress = download_item->IsInProgress();
      break;
    }
  }

  if (download_item->IsComplete()) {
    LOGB("Download complete: " << download_item->GetFullPath().ToString());
    std::lock_guard<std::mutex> render_lock(render_mutex_);
    status_bar_->showMessage("Download complete: " +
                             download_item->GetFullPath().ToString());
  } else if (download_item->IsCanceled()) {
    LOGB("Download canceled");
  }

  // Refresh download manager if active
  if (download_manager_active_ && browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

static void ensureDir(const std::string &path) {
  if (path.empty())
    return;
  char *copy = strdup(path.c_str());
  struct stat st;
  for (char *p = copy + 1; *p; ++p) {
    if (*p == '/' || *p == '\\') {
      char saved = *p;
      *p = '\0';
      if (stat(copy, &st) != 0)
        mkdir(copy, 0700);
      *p = saved;
    }
  }
  if (stat(copy, &st) != 0)
    mkdir(copy, 0700);
  free(copy);
}

void BrowserClient::HandleDownloadResponse(bool accept,
                                           const std::string &path) {
  // Don't handle if browser is closing
  if (is_closing_) {
    return;
  }

  CefRefPtr<CefBeforeDownloadCallback> callback;
  std::string filename;

  {
    std::lock_guard<std::mutex> lock(download_mutex_);

    if (!download_confirm_active_ || !download_callback_) {
      return;
    }

    // Take ownership of callback and data before unlocking
    callback = download_callback_;
    filename = download_filename_;
    download_callback_ = nullptr;
    download_confirm_active_ = false;
  }

  // Call the callback outside the mutex to avoid potential deadlocks
  if (callback) {
    if (accept) {
      std::string download_path;
      if (!path.empty()) {
        download_path = path;
      } else {
        std::string name = filename;
        size_t slash = name.find_last_of("/\\");
        if (slash != std::string::npos)
          name = name.substr(slash + 1);
        download_path = std::string(PEAK_DOWNLOAD_DIR) + "/" + name;
      }
      size_t slash = download_path.find_last_of("/");
      if (slash != std::string::npos)
        ensureDir(download_path.substr(0, slash));

      LOGB("Download accepted: " << download_path);
      callback->Continue(download_path, false);
    } else {
      LOGB("Download rejected");
      // Not calling Continue() means the download is rejected
    }
  }

  // Force repaint to clear the dialog
  if (browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

void BrowserClient::AddCurrentPageToBookmarks() {
  if (!browser_)
    return;

  CefRefPtr<CefFrame> frame = browser_->GetMainFrame();
  if (!frame)
    return;

  std::string url = frame->GetURL().ToString();
  if (url.empty() || url == "about:blank")
    return;

  bookmarks_manager_.addBookmark(current_page_title_, url);

  std::lock_guard<std::mutex> lock(render_mutex_);
  status_bar_->showMessage("📚 Bookmark added: " + current_page_title_);
}

void BrowserClient::SetBookmarksActive(bool active) {
  bookmarks_active_ = active;
  if (active) {
    bookmarks_selected_index_ = 0;

    // Build display list
    const auto &bookmarks = bookmarks_manager_.getBookmarks();
    std::vector<std::string> display_list;
    for (const auto &bookmark : bookmarks) {
      display_list.push_back(bookmark.title + " - " + bookmark.url);
    }

    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showBookmarks(display_list, bookmarks_selected_index_);
  } else {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear();

    // Force a repaint
    if (browser_ && browser_->GetHost()) {
      browser_->GetHost()->Invalidate(PET_VIEW);
    }
  }
}

bool BrowserClient::HandleBookmarkNavigation(int direction) {
  if (!bookmarks_active_)
    return false;

  const auto &bookmarks = bookmarks_manager_.getBookmarks();
  if (bookmarks.empty())
    return true;

  bookmarks_selected_index_ += direction;
  if (bookmarks_selected_index_ < 0) {
    bookmarks_selected_index_ = 0;
  } else if (bookmarks_selected_index_ >= bookmarks.size()) {
    bookmarks_selected_index_ = bookmarks.size() - 1;
  }

  // Build display list
  std::vector<std::string> display_list;
  for (const auto &bookmark : bookmarks) {
    display_list.push_back(bookmark.title + " - " + bookmark.url);
  }

  std::lock_guard<std::mutex> lock(render_mutex_);
  status_bar_->showBookmarks(display_list, bookmarks_selected_index_);

  return true;
}

bool BrowserClient::HandleBookmarkConfirm() {
  if (!bookmarks_active_)
    return false;

  const auto &bookmarks = bookmarks_manager_.getBookmarks();
  LOGB("HandleBookmarkConfirm: bookmarks.size="
       << bookmarks.size() << " selected=" << bookmarks_selected_index_);

  if (bookmarks.empty() || bookmarks_selected_index_ >= bookmarks.size()) {
    return false;
  }

  std::string url = bookmarks[bookmarks_selected_index_].url;
  LOGB("Opening bookmark: " << url);

  // Close bookmarks view
  SetBookmarksActive(false);

  // Navigate to URL
  if (browser_ && browser_->GetMainFrame()) {
    browser_->GetMainFrame()->LoadURL(url);
  }

  return true;
}

bool BrowserClient::HandleBookmarkDelete() {
  if (!bookmarks_active_)
    return false;

  const auto &bookmarks = bookmarks_manager_.getBookmarks();
  if (bookmarks.empty() || bookmarks_selected_index_ >= bookmarks.size()) {
    return false;
  }

  bookmarks_manager_.removeBookmark(bookmarks_selected_index_);

  // Adjust selection
  const auto &updated_bookmarks = bookmarks_manager_.getBookmarks();
  if (bookmarks_selected_index_ >= updated_bookmarks.size() &&
      bookmarks_selected_index_ > 0) {
    bookmarks_selected_index_--;
  }

  // Update display
  std::vector<std::string> display_list;
  for (const auto &bookmark : updated_bookmarks) {
    display_list.push_back(bookmark.title + " - " + bookmark.url);
  }

  std::lock_guard<std::mutex> lock(render_mutex_);
  status_bar_->showBookmarks(display_list, bookmarks_selected_index_);

  return true;
}

void BrowserClient::ShowPasswordsList() {
  passwords_sorted_ = passwords_manager_.getEntries();

  // Sort entries matching the current page host first
  std::string page_host;
  if (browser_ && browser_->GetMainFrame()) {
    page_host = UrlHost(browser_->GetMainFrame()->GetURL().ToString());
  }
  if (!page_host.empty()) {
    auto score = [&page_host](const PasswordEntry &e) {
      std::string eh = UrlHost(e.url);
      if (eh == page_host) {
        return 2;
      }
      if (!eh.empty() && page_host.size() > eh.size() &&
          page_host.compare(page_host.size() - eh.size() - 1, eh.size() + 1,
                            "." + eh) == 0) {
        return 1;
      }
      return 0;
    };
    std::stable_sort(passwords_sorted_.begin(), passwords_sorted_.end(),
                     [&score](const PasswordEntry &a, const PasswordEntry &b) {
                       return score(a) > score(b);
                     });
  }

  std::vector<std::string> display_list;
  for (const auto &e : passwords_sorted_) {
    std::string user =
        e.username.empty() ? std::string("(no username)") : e.username;
    display_list.push_back(user + " — " + UrlHost(e.url));
  }

  std::lock_guard<std::mutex> lock(render_mutex_);
  status_bar_->showPasswords(display_list, passwords_selected_index_);
}

void BrowserClient::SetPasswordsActive(bool active) {
  passwords_active_ = active;
  if (active) {
    passwords_selected_index_ = 0;
    ShowPasswordsList();
  } else {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear();
    if (browser_) {
      browser_->GetHost()->Invalidate(PET_VIEW);
    }
  }
}

bool BrowserClient::HandlePasswordNavigation(int direction) {
  if (!passwords_active_) {
    return false;
  }
  if (passwords_sorted_.empty()) {
    return true;
  }

  passwords_selected_index_ += direction;
  if (passwords_selected_index_ < 0) {
    passwords_selected_index_ = 0;
  } else if (passwords_selected_index_ >=
             static_cast<int>(passwords_sorted_.size())) {
    passwords_selected_index_ = passwords_sorted_.size() - 1;
  }

  ShowPasswordsList();
  return true;
}

bool BrowserClient::HandlePasswordConfirm() {
  if (!passwords_active_) {
    return false;
  }
  if (passwords_sorted_.empty() ||
      passwords_selected_index_ >=
          static_cast<int>(passwords_sorted_.size())) {
    return true;
  }

  PasswordEntry entry = passwords_sorted_[passwords_selected_index_];
  LOGB("Filling credentials for " << entry.url << " (" << entry.username
                                  << ")");

  SetPasswordsActive(false);
  FillCredentials(entry);
  return true;
}

bool BrowserClient::HandlePasswordDelete() {
  if (!passwords_active_) {
    return false;
  }
  if (passwords_sorted_.empty() ||
      passwords_selected_index_ >=
          static_cast<int>(passwords_sorted_.size())) {
    return true;
  }

  // Find the entry in the manager by url+username (display list is sorted)
  const PasswordEntry &selected = passwords_sorted_[passwords_selected_index_];
  const auto &entries = passwords_manager_.getEntries();
  for (size_t i = 0; i < entries.size(); i++) {
    if (entries[i].url == selected.url &&
        entries[i].username == selected.username) {
      passwords_manager_.removeEntry(i);
      break;
    }
  }

  passwords_sorted_.erase(passwords_sorted_.begin() +
                          passwords_selected_index_);
  if (passwords_selected_index_ > 0 &&
      passwords_selected_index_ >=
          static_cast<int>(passwords_sorted_.size())) {
    passwords_selected_index_--;
  }

  ShowPasswordsList();
  return true;
}

void BrowserClient::FillCredentials(const PasswordEntry &entry) {
  if (!browser_ || !browser_->GetMainFrame()) {
    return;
  }

  auto jsonEscape = [](const std::string &s) {
    std::string out;
    for (char c : s) {
      switch (c) {
      case '"':
        out += "\\\"";
        break;
      case '\\':
        out += "\\\\";
        break;
      case '\n':
        out += "\\n";
        break;
      case '\r':
        out += "\\r";
        break;
      case '\t':
        out += "\\t";
        break;
      default:
        if (static_cast<unsigned char>(c) < 0x20) {
          char buf[8];
          snprintf(buf, sizeof(buf), "\\u%04x", c);
          out += buf;
        } else {
          out += c;
        }
        break;
      }
    }
    return out;
  };

  // Native value setter + input/change events so framework pages (React,
  // Angular, ...) pick the values up. Prefers visible fields inside the
  // password field's form.
  std::string js =
      "(function(){"
      "var U=\"" +
      jsonEscape(entry.username) + "\",P=\"" + jsonEscape(entry.password) +
      "\";"
      "function sv(e,v){var d=Object.getOwnPropertyDescriptor("
      "HTMLInputElement.prototype,'value');d.set.call(e,v);"
      "e.dispatchEvent(new Event('input',{bubbles:true}));"
      "e.dispatchEvent(new Event('change',{bubbles:true}));}"
      "var all=document.querySelectorAll('input[type=password]');"
      "var vis=[];for(var i=0;i<all.length;i++){"
      "var r=all[i].getBoundingClientRect();"
      "if(r.width>0||r.height>0)vis.push(all[i]);}"
      "if(vis.length==0&&all.length>0)vis=[all[0]];"
      "if(vis.length==0){console.log('[peak] "
      "PASSWORD_FILL_ERROR:no password field on page');return;}"
      "var pw=vis[0];var f=pw.form||document;"
      "var u=null;var cs=f.querySelectorAll('input');"
      "for(var j=0;j<cs.length;j++){var el=cs[j];"
      "var t=(el.getAttribute('type')||'').toLowerCase();"
      "if(t=='password'||t=='hidden'||t=='submit'||t=='button'||"
      "t=='image'||t=='file'||t=='checkbox'||t=='radio')continue;"
      "var r2=el.getBoundingClientRect();"
      "if(r2.width==0&&r2.height==0)continue;"
      "if(el.value==U){u=el;break;}if(!u)u=el;}"
      "try{if(u)sv(u,U);}catch(x){}"
      "sv(pw,P);"
      "console.log('[peak] PASSWORD_FILLED');"
      "})()";

  ExecuteJavaScript(js);
}

void BrowserClient::RunOneTimeImports() {
  const char *home = getenv("HOME");
  if (!home || !*home) {
    struct passwd *pwent = getpwuid(getuid());
    home = pwent ? pwent->pw_dir : "";
  }
  if (!*home) {
    return;
  }

  mkdir("/etc/peak", 0755);
  struct stat st;

  // Firefox bookmark export -> bookmarks list (once)
  std::string bm_src = std::string(home) + "/bookmarks.json";
  std::string bm_marker = "/etc/peak/.ff_bookmarks_imported";
  if (stat(bm_src.c_str(), &st) == 0 && stat(bm_marker.c_str(), &st) != 0) {
    int n = bookmarks_manager_.importFirefoxJson(bm_src);
    LOGB("Firefox bookmark import from " << bm_src << ": " << n << " added");
    FILE *m = fopen(bm_marker.c_str(), "w");
    if (m) {
      fputs("1\n", m);
      fclose(m);
    }
  }

  // Firefox password export -> password store (once)
  std::string pw_src = std::string(home) + "/passwords.csv";
  std::string pw_marker = "/etc/peak/.ff_passwords_imported";
  if (stat(pw_src.c_str(), &st) == 0 && stat(pw_marker.c_str(), &st) != 0) {
    int n = passwords_manager_.importFirefoxCsv(pw_src);
    LOGB("Firefox password import from " << pw_src << ": " << n << " added");
    FILE *m = fopen(pw_marker.c_str(), "w");
    if (m) {
      fputs("1\n", m);
      fclose(m);
    }
  }
}

void BrowserClient::SetUserScriptsActive(bool active) {
  user_scripts_active_ = active;
  if (active) {
    user_scripts_selected_index_ = 0;

    // Get all available scripts
    std::vector<std::string> script_names =
        user_scripts_manager_.getAllScriptNames();

    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showUserScripts(script_names, user_scripts_selected_index_);
  } else {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear();

    // Force a repaint
    if (browser_ && browser_->GetHost()) {
      browser_->GetHost()->Invalidate(PET_VIEW);
    }
  }
}

bool BrowserClient::HandleUserScriptNavigation(int direction) {
  if (!user_scripts_active_)
    return false;

  std::vector<std::string> script_names =
      user_scripts_manager_.getAllScriptNames();
  if (script_names.empty())
    return true;

  user_scripts_selected_index_ += direction;
  if (user_scripts_selected_index_ < 0) {
    user_scripts_selected_index_ = 0;
  } else if (user_scripts_selected_index_ >= script_names.size()) {
    user_scripts_selected_index_ = script_names.size() - 1;
  }

  std::lock_guard<std::mutex> lock(render_mutex_);
  status_bar_->showUserScripts(script_names, user_scripts_selected_index_);

  return true;
}

bool BrowserClient::HandleUserScriptConfirm() {
  if (!user_scripts_active_)
    return false;

  std::vector<std::string> script_names =
      user_scripts_manager_.getAllScriptNames();
  if (script_names.empty() ||
      user_scripts_selected_index_ >= script_names.size()) {
    return false;
  }

  std::string script_name = script_names[user_scripts_selected_index_];
  std::string script_content =
      user_scripts_manager_.getScriptContent(script_name);

  LOGB("Injecting user script: " << script_name);

  // Close user scripts view
  SetUserScriptsActive(false);

  // Execute script
  if (!script_content.empty() && browser_) {
    CefRefPtr<CefFrame> frame = browser_->GetMainFrame();
    if (frame) {
      frame->ExecuteJavaScript(script_content, frame->GetURL(), 0);

      // Show confirmation
      std::lock_guard<std::mutex> lock(render_mutex_);
      status_bar_->showMessage("📜 Script injected: " + script_name + " (reload 'r' to exit)");
    }
  }

  return true;
}

void BrowserClient::ToggleAutoInjectUserScripts() {
  bool current = user_scripts_manager_.isAutoInjectEnabled();
  user_scripts_manager_.setAutoInject(!current);

  LOGB("ToggleAutoInjectUserScripts: was=" << current << " now=" << !current);

  std::lock_guard<std::mutex> lock(render_mutex_);
  if (!current) {
    status_bar_->showMessage("📜 User scripts auto-inject: ENABLED");
  } else {
    status_bar_->showMessage("📜 User scripts auto-inject: DISABLED");
  }
}

void BrowserClient::InjectUserScriptsForCurrentPage() {
  if (!browser_)
    return;

  CefRefPtr<CefFrame> frame = browser_->GetMainFrame();
  if (!frame)
    return;

  std::string url = frame->GetURL().ToString();
  std::vector<std::string> matching_scripts =
      user_scripts_manager_.getMatchingScripts(url);

  for (const auto &script_name : matching_scripts) {
    std::string script_content =
        user_scripts_manager_.getScriptContent(script_name);
    if (!script_content.empty()) {
      LOGB("Auto-injecting user script: " << script_name
                                          << " for URL: " << url);
      frame->ExecuteJavaScript(script_content, frame->GetURL(), 0);
    }
  }
}

// Hint Mode implementation
void BrowserClient::ActivateCoordinateMode() {
  if (!browser_ || !browser_->GetMainFrame()) {
    LOGB("ActivateCoordinateMode: browser or frame is null");
    return;
  }

  // Read coordinate click JavaScript (crosshair + file-input detection)
  std::string js_path = GetJsFilePath("coordinate_click.js");
  std::ifstream file(js_path);
  if (!file.is_open()) {
    LOGB("Failed to load coordinate_click.js from " << js_path);
    return;
  }

  std::stringstream buffer;
  buffer << file.rdbuf();
  std::string coord_js = buffer.str();

  if (coord_js.empty()) {
    LOGB("coordinate_click.js is empty!");
    return;
  }

  LOGB("Activating coordinate mode, JS size: " << coord_js.size() << " bytes");

  coordinate_mode_active_ = true;
  coordinate_count_ = 0;

  CefRefPtr<CefFrame> frame = browser_->GetMainFrame();
  if (frame) {
    frame->ExecuteJavaScript(coord_js, "", 0);

    // Trigger render after delay to ensure overlay is visible
    CefRefPtr<CefBrowser> browser = browser_;
    std::thread([browser]() {
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      if (browser && browser->GetHost()) {
        browser->GetHost()->Invalidate(PET_VIEW);
      }
    }).detach();
  }

  // Show coordinate input in status bar
  if (status_bar_) {
    status_bar_->showCoordinateInput("", coordinate_count_);
  } else {
    LOGB("Status bar is null!");
  }
}

void BrowserClient::SetCoordinateModeActive(bool active) {
  coordinate_mode_active_ = active;
  if (!active && browser_ && browser_->GetMainFrame()) {
    // Cleanup crosshair overlay
    browser_->GetMainFrame()->ExecuteJavaScript(
        "if (window.__tb_coord) { window.__tb_coord.cleanup(); }", "",
        0);
  }
}

void BrowserClient::PlaceCoordinateCursor(int col, int row) {
  if (!browser_ || !browser_->GetMainFrame())
    return;
  std::string js =
      "if(window.__tb_coord_cursor){window.__tb_coord_cursor.place(" +
      std::to_string(col) + "," + std::to_string(row) + ");}";
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
  if (browser_)
    browser_->GetHost()->Invalidate(PET_VIEW);
}

void BrowserClient::HandleCoordinateClick(int x, int y) {
  if (!browser_ || !browser_->GetMainFrame()) {
    LOGB("HandleCoordinateClick: browser or frame is null");
    return;
  }

  coordinate_mode_active_ = false;
  if (status_bar_) {
    status_bar_->clear();
  }

  // Ask the page whether this coordinate is a file input. The JS helper
  // reports back via console messages, which then trigger the actual click
  // (HandleHintClick) or the file picker (HandleFileInputClick). Prefer the
  // always-on cursor script; fall back to the full grid script (Link Hint Mode).
  std::string js =
      "if (window.__tb_coord_cursor) { window.__tb_coord_cursor.check(" +
      std::to_string(x) + "," + std::to_string(y) + "); }" +
      "else if (window.__tb_coord) { window.__tb_coord.check(" +
      std::to_string(x) + "," + std::to_string(y) + "); }";
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
}

void BrowserClient::SetCoordinateHighlight(int col, int row) {
  if (!browser_ || !browser_->GetMainFrame()) {
    return;
  }
  std::string js =
      "if (window.__tb_coord) { window.__tb_coord.highlight(" +
      std::to_string(col) + "," + std::to_string(row) + "); }";
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
}

void BrowserClient::HandleHintClick(int x, int y) {
  if (!browser_ || !browser_->GetHost()) {
    return;
  }

  // Clamp to the viewport.
  if (x < 0) {
    x = 0;
  }
  if (y < 0) {
    y = 0;
  }
  if (x > width_) {
    x = width_;
  }
  if (y > height_) {
    y = height_;
  }

  CefMouseEvent mouse_event;
  mouse_event.x = x;
  mouse_event.y = y;
  mouse_event.modifiers = 0;

  LOGB("Hint click at (" << x << "," << y << ")");

  browser_->GetHost()->SendMouseMoveEvent(mouse_event, false);
  browser_->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1);
  browser_->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1);
  browser_->GetHost()->SetFocus(true);

  LOGB("Hint click completed");
}

void BrowserClient::HandleFileInputClick(int x, int y) {
  if (!browser_ || !browser_->GetMainFrame()) {
    return;
  }

  // Open the Firefox-style file chooser popup instead of CEF's dialog or a
  // DOM overlay (both SendMouseClickEvent/RunFileDialog can hit the
  // cef_get_xdisplay() crash on file inputs). The chosen path is routed back
  // through HandleFileUpload() which continues the upload pipeline.
  OpenFileChooser(true);
  return;

  std::string js =
      "(function(){"
      "  if(document.getElementById('__tb_file_picker'))return;"
      "  var d=document.createElement('div');d.id='__tb_file_picker';"
      "  d.style.cssText='position:fixed;top:0;left:0;right:0;bottom:0;"
      "  z-index:2147483647;background:rgba(0,0,0,0.85);display:flex;"
      "  align-items:center;justify-content:center;font-family:monospace;';"
      "  var box=document.createElement('div');"
      "  box.style.cssText='background:#fff;padding:20px;border-radius:8px;"
      "  min-width:400px;box-shadow:0 4px 20px rgba(0,0,0,0.5);';"
      "  var lbl=document.createElement('div');"
      "  lbl.textContent='File Path:';"
      "  lbl.style.cssText='margin-bottom:8px;font-size:14px;color:#000;font-weight:bold;';"
      "  var inp=document.createElement('input');"
      "  inp.type='text';inp.value='';inp.placeholder='/path/to/file';"
      "  inp.style.cssText='width:100%;padding:8px;font-size:14px;"
      "  font-family:monospace;border:1px solid #999;border-radius:4px;"
      "  box-sizing:border-box;';"
      "  var btns=document.createElement('div');"
      "  btns.style.cssText='margin-top:10px;text-align:right;';"
      "  var ok=document.createElement('button');"
      "  ok.textContent='OK';ok.style.cssText='padding:6px 16px;font-size:13px;"
      "  margin-left:8px;cursor:pointer;background:#4a90d9;color:#fff;"
      "  border:none;border-radius:4px;';"
      "  var cancel=document.createElement('button');"
      "  cancel.textContent='Cancel';cancel.style.cssText='padding:6px 16px;"
      "  font-size:13px;cursor:pointer;background:#ccc;color:#000;"
      "  border:none;border-radius:4px;';"
      "  function submit(){"
      "    console.log('[peak] FILE_DIALOG_RESPONSE:'+inp.value);"
      "    d.remove();"
      "  }"
      "  function cancelDialog(){"
      "    console.log('[peak] FILE_DIALOG_CANCEL');"
      "    d.remove();"
      "  }"
      "  ok.onclick=submit;"
      "  cancel.onclick=cancelDialog;"
      "  inp.onkeydown=function(e){if(e.key==='Enter')submit();"
      "    if(e.key==='Escape')cancelDialog();};"
      "  btns.appendChild(cancel);btns.appendChild(ok);"
      "  box.appendChild(lbl);box.appendChild(inp);box.appendChild(btns);"
      "  d.appendChild(box);document.documentElement.appendChild(d);"
      "  inp.focus();inp.select();"
      "})();";
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
}

// Mouse Emulation Mode implementation


void BrowserClient::ToggleDownloadManager() {
  download_manager_active_ = !download_manager_active_;

  if (download_manager_active_) {
    download_manager_selected_index_ = 0;

    std::vector<std::string> display_list;
    {
      std::lock_guard<std::mutex> lock(download_mutex_);
      for (const auto &entry : downloads_list_) {
        std::string status =
            entry.is_complete
                ? "✓"
                : (entry.is_canceled ? "✗"
                                     : (entry.is_in_progress ? "⬇" : "…"));
        std::string display = status + " " + entry.filename;
        if (entry.is_in_progress && entry.total_bytes > 0) {
          display += " (" + std::to_string(entry.percent_complete) + "%)";
        }
        display_list.push_back(display);
      }
    }

    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->showDownloadManager(display_list,
                                     download_manager_selected_index_);
  } else {
    std::lock_guard<std::mutex> lock(render_mutex_);
    status_bar_->clear();
  }

  if (browser_ && browser_->GetHost()) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

void BrowserClient::HandleDownloadManagerNavigation(int direction) {
  if (!download_manager_active_)
    return;

  int total = downloads_list_.size();
  if (total == 0)
    return;

  download_manager_selected_index_ += direction;
  if (download_manager_selected_index_ < 0)
    download_manager_selected_index_ = 0;
  if (download_manager_selected_index_ >= total)
    download_manager_selected_index_ = total - 1;

  std::vector<std::string> display_list;
  {
    std::lock_guard<std::mutex> lock(download_mutex_);
    for (const auto &entry : downloads_list_) {
      std::string status =
          entry.is_complete
              ? "✓"
              : (entry.is_canceled ? "✗" : (entry.is_in_progress ? "⬇" : "…"));
      std::string display = status + " " + entry.filename;
      if (entry.is_in_progress && entry.total_bytes > 0) {
        display += " (" + std::to_string(entry.percent_complete) + "%)";
      }
      display_list.push_back(display);
    }
  }

  std::lock_guard<std::mutex> lock(render_mutex_);
  status_bar_->showDownloadManager(display_list,
                                   download_manager_selected_index_);
}

void BrowserClient::HandleDownloadManagerAction(char action) {
  if (!download_manager_active_)
    return;

  if (action == 'm' || action == 'M') {
    ToggleDownloadManager();
    return;
  }

  if (action == 'c' || action == 'C') {
    std::lock_guard<std::mutex> lock(download_mutex_);
    auto it = downloads_list_.begin();
    while (it != downloads_list_.end()) {
      if (it->is_complete || it->is_canceled) {
        it = downloads_list_.erase(it);
      } else {
        ++it;
      }
    }
    download_manager_selected_index_ = 0;

    std::vector<std::string> display_list;
    for (const auto &entry : downloads_list_) {
      std::string status =
          entry.is_complete
              ? "✓"
              : (entry.is_canceled ? "✗" : (entry.is_in_progress ? "⬇" : "…"));
      std::string display = status + " " + entry.filename;
      if (entry.is_in_progress && entry.total_bytes > 0) {
        display += " (" + std::to_string(entry.percent_complete) + "%)";
      }
      display_list.push_back(display);
    }

    std::lock_guard<std::mutex> render_lock(render_mutex_);
    status_bar_->showDownloadManager(display_list,
                                     download_manager_selected_index_);
  }
}

void BrowserClient::CopyCurrentURL() {
  if (!browser_ || !browser_->GetMainFrame()) {
    LOGB("CopyCurrentURL: browser or frame is null");
    return;
  }

  std::string url = browser_->GetMainFrame()->GetURL().ToString();
  if (!url.empty()) {
    Clipboard::copyToClipboard(url);
    LOGB("Copied URL to clipboard: " << url);
  }
}

void BrowserClient::ActivateVisualMode() {
  if (!browser_ || !browser_->GetMainFrame()) {
    LOGB("ActivateVisualMode: browser or frame is null");
    return;
  }

  visual_mode_active_ = true;

  // Load visual mode JavaScript
  std::string js_path = GetJsFilePath("visual_mode.js");
  std::ifstream file(js_path);
  if (!file.is_open()) {
    LOGB("Failed to load visual_mode.js from " << js_path);
    return;
  }

  std::string js((std::istreambuf_iterator<char>(file)),
                 std::istreambuf_iterator<char>());
  file.close();

  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);

  // Refresh the framebuffer so the initial selection highlight appears
  if (browser_) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}

void BrowserClient::SetVisualModeActive(bool active) {
  visual_mode_active_ = active;

  if (!active && browser_ && browser_->GetMainFrame()) {
    // Cleanup visual mode
    std::string js = "if (window.__peak_visual_mode) { "
                     "window.__peak_visual_mode.cleanup(); }";
    browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
  }
}

void BrowserClient::HandleVisualModeKey(const std::string &key) {
  if (!browser_ || !browser_->GetMainFrame()) {
    return;
  }

  std::string js = "if (window.__peak_visual_mode) { "
                   "window.__peak_visual_mode.handleKey('" +
                   key + "'); }";
  browser_->GetMainFrame()->ExecuteJavaScript(js, "", 0);
}

void BrowserClient::OnFindResult(CefRefPtr<CefBrowser> browser,
                                  int identifier,
                                  int count,
                                  const CefRect& selectionRect,
                                  int activeMatchOrdinal,
                                  bool finalUpdate) {
  search_match_count_ = count;
  search_active_match_ = activeMatchOrdinal;
  
  // Update status bar with match count
  if (status_bar_ && search_active_ && input_handler_) {
    std::string query = input_handler_->GetSearchQuery();
    status_bar_->showSearchInput(query, activeMatchOrdinal, count);
  }
  
  // Trigger render now that Find() is complete and buffer is updated
  // This ensures we render the frame WITH highlights, not before
  if (finalUpdate && browser_) {
    browser_->GetHost()->Invalidate(PET_VIEW);
  }
}
