// Popup script for Officeless Web Extender

const sidepanelBtn = document.getElementById('sidepanelBtn');

sidepanelBtn.addEventListener('click', async () => {
    console.log('Checking current tab...');

    try {
        const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });

        if (!activeTab) {
            alert('No active tab found');
            return;
        }

        const url = activeTab.url;
        const allowedPattern = /^https:\/\/studio\.mekari\.com\/my-projects\/[^/]+/;

        if (!allowedPattern.test(url)) {
            alert('Side panel can only be opened from Mekari Officeless Studio project pages (https://studio.mekari.com/my-projects/...)');
            return;
        }

        console.log('URL validated:', url);

        const currentWindow = await chrome.windows.getCurrent();
        await chrome.sidePanel.open({ windowId: currentWindow.id });

        console.log('Side panel opened successfully');
        window.close();
    } catch (err) {
        console.error('Error opening side panel:', err);
        alert('Error: ' + err.message);
    }
});
