"use strict";
import logger from './logger.js';

// #region Constants and Helper Functions
function setBadgeText(enabled) {
    const text = enabled ? "ON" : "OFF"
    void chrome.action.setBadgeText({text: text})
}

function isGoogleMeetPage(url) {
    return url && (url.startsWith('http://meet.google.com/') || url.startsWith('https://meet.google.com/'));
}

function showErrorMessage(message) {
    const errorElement = document.getElementById("errorMessage");
    errorElement.textContent = message;
    errorElement.style.display = message ? "block" : "none";
}

function handleContentScriptError(error) {
    logger.debug("Error sending message:", chrome.runtime.lastError);
    if (error.message.includes("Receiving end does not exist")) {
        showErrorMessage("Please refresh the Google Meet page to use this extension");
    } else {
        showErrorMessage("An error occurred. Please try again.");
    }
}

function resetSliderState() {
    checkbox.checked = false;
    setBadgeText(false);
    chrome.storage.sync.set({ "slider": false });
}
// #endregion Constants and Helper Functions

// #region DOM Elements
const checkbox = document.getElementById("slider");
const downloadButton = document.querySelector(".downloadBtn");
// #endregion DOM Elements

// #region Storage Operations
function initializeSliderState() {
    chrome.storage.sync.get("slider", (data) => {
        const isEnabled = !!data.slider;
        checkbox.checked = isEnabled;
        setBadgeText(isEnabled);
    });
}

function saveSliderState(isChecked) {
    chrome.storage.sync.set({ "slider": isChecked }, (error) => {
        if (error) {
            showErrorMessage("Failed to save settings. Please try again.");
            return;
        }
        setBadgeText(isChecked);
    });
}
// #endregion Storage Operations

// #region Message Handling
function sendMessageToContentScript(tabId, action) {
    chrome.tabs.sendMessage(tabId, { action }, (response) => {
        if (chrome.runtime.lastError) {
            handleContentScriptError(chrome.runtime.lastError);
            return;
        }
        showErrorMessage(""); // Clear any previous error messages
    });
}

function handleTabAction(action) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length === 0) {
            showErrorMessage("No active tab found");
            resetSliderState();
            return;
        }

        const currentTab = tabs[0];
        if (!isGoogleMeetPage(currentTab.url)) {
            showErrorMessage("Extension can only be used on Google Meet pages");
            resetSliderState();
            return;
        }

        sendMessageToContentScript(currentTab.id, action);
    });
}
// #endregion Message Handling

// #region Event Listeners
function setupSliderListener() {
    checkbox.addEventListener("change", (event) => {
        const isChecked = event.target.checked;
        saveSliderState(isChecked);
        handleTabAction(isChecked ? "startCapture" : "stopCapture");
    });
}

function setupDownloadButtonListener() {
    downloadButton.addEventListener("click", () => {
        handleTabAction("downloadSrt");
    });
}
// #endregion Event Listeners

// #region Initialization
function initializePopup() {
    logger.debug("Initializing popup");
    initializeSliderState();
    setupSliderListener();
    setupDownloadButtonListener();
}

// Start the popup initialization
initializePopup();
// #endregion Initialization
