/**
 * ITR POS Tab Management System
 * Handles opening pages in tabs using iframes
 */

class TabManager {
    constructor() {
        this.tabs = [];
        this.activeTabId = null;
        this.maxTabs = 15;
        this.tabCounter = 0;
        this.contextMenu = null;
        this.contextMenuTabId = null;
        
        this.init();
    }

    init() {
        // Create context menu
        this.createContextMenu();
        
        // Load tabs from sessionStorage
        this.loadTabsFromStorage();
        
        // Setup event listeners
        this.setupEventListeners();
        
        // Close context menu on outside click
        document.addEventListener('click', (e) => {
            if (this.contextMenu && !this.contextMenu.contains(e.target)) {
                this.hideContextMenu();
            }
        });

        // Keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                if (e.key === 'w' || e.key === 'W') {
                    e.preventDefault();
                    if (this.activeTabId) {
                        this.closeTab(this.activeTabId);
                    }
                } else if (e.key === 't' || e.key === 'T') {
                    // Ctrl+T could open new tab - implement if needed
                }
            }
        });
    }

    createContextMenu() {
        this.contextMenu = document.createElement('div');
        this.contextMenu.className = 'tab-context-menu';
        this.contextMenu.innerHTML = `
            <div class="tab-context-menu-item" data-action="close">
                <i data-feather="x"></i> Close Tab
            </div>
            <div class="tab-context-menu-item" data-action="close-others">
                <i data-feather="x-circle"></i> Close Others
            </div>
            <div class="tab-context-menu-item" data-action="close-all">
                <i data-feather="x-square"></i> Close All
            </div>
            <div class="tab-context-menu-item" data-action="reload">
                <i data-feather="refresh-cw"></i> Reload Tab
            </div>
        `;
        document.body.appendChild(this.contextMenu);

        // Attach event listeners
        this.contextMenu.querySelectorAll('.tab-context-menu-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const action = item.dataset.action;
                this.handleContextMenuAction(action);
            });
        });
    }

    setupEventListeners() {
        // Intercept navigation links
        this.interceptNavigationLinks();
        
        // Handle iframe load events
        document.addEventListener('iframeLoaded', (e) => {
            this.handleIframeLoad(e.detail);
        });

        // Handle iframe title updates
        window.addEventListener('message', (e) => {
            if (e.data && e.data.type === 'tabTitleUpdate') {
                this.updateTabTitle(e.data.tabId, e.data.title);
            }
            
            // Handle link clicks from inside iframes
            if (e.data && e.data.type === 'openInTab' && e.data.url) {
                // Extract relative path from absolute URL if needed
                let url = e.data.url;
                try {
                    const urlObj = new URL(url);
                    if (urlObj.hostname === window.location.hostname) {
                        // Same domain - use relative path, preserve query params
                        url = urlObj.pathname + urlObj.search;
                    }
                } catch(err) {
                    // Already relative or invalid - use as is
                }
                
                // Make sure iframe parameter is removed from URL (will be added by openTab)
                url = url.replace(/[?&]iframe=1(&|$)/, '').replace(/[?&]$/, '');
                
                this.openTab(url, e.data.title || null);
            }
            
            // Handle same-page navigation (update current tab instead of opening new one)
            if (e.data && e.data.type === 'updateSameTab' && e.data.url) {
                // Find the iframe that sent this message
                const iframe = e.source.frameElement || Array.from(document.querySelectorAll('.tab-content-frame')).find(f => f.contentWindow === e.source);
                
                if (iframe && iframe.dataset.tabId) {
                    // Update the iframe src with iframe parameter
                    let url = e.data.url;
                    url = url.replace(/[?&]iframe=1(&|$)/, '').replace(/[?&]$/, '');
                    const separator = url.includes('?') ? '&' : '?';
                    iframe.src = url + separator + 'iframe=1';
                    
                    // Update tab title if provided
                    if (e.data.title) {
                        const tabId = iframe.dataset.tabId;
                        this.updateTabTitle(tabId, e.data.title);
                    }
                }
            }
        });
        
        // Inject script into iframes to intercept links
        this.setupIframeLinkInterception();
    }
    
    setupIframeLinkInterception() {
        // Process all existing iframes
        document.querySelectorAll('.tab-content-frame').forEach(iframe => {
            this.injectLinkInterceptorIntoIframe(iframe);
        });
    }
    
    injectLinkInterceptorIntoIframe(iframe) {
        try {
            const iframeWindow = iframe.contentWindow;
            const iframeDoc = iframe.contentDocument || iframeWindow.document;
            
            // Check if already injected
            if (iframeDoc.getElementById('tab-link-interceptor')) {
                return;
            }
            
            // Inject script to intercept links in iframe
            const script = iframeDoc.createElement('script');
            script.id = 'tab-link-interceptor';
            script.textContent = `
                (function() {
                    // Only run if we're inside an iframe
                    if (window.self !== window.top) {
                        // Function to check if URL should open in tab
                        function shouldOpenInTab(url) {
                            if (!url) return false;
                            if (url.startsWith('#')) return false;
                            if (url.startsWith('javascript:')) return false;
                            if (url.includes('print_') || url.includes('vouchers/')) return false;
                            if (url.includes('pos.php')) return false;
                            if (url.includes('login.php') || url.includes('logout.php')) return false;
                            
                            // Skip external links (but allow same-domain)
                            if (url.startsWith('http://') || url.startsWith('https://')) {
                                try {
                                    const linkHost = new URL(url, window.location.href).hostname;
                                    if (linkHost !== window.location.hostname) return false;
                                } catch(err) {
                                    return false;
                                }
                            }
                            return true;
                        }
                        
                        // Function to add iframe parameter
                        function addIframeParam(url) {
                            if (url.includes('?')) {
                                if (!url.includes('iframe=1')) {
                                    return url + '&iframe=1';
                                }
                            } else {
                                if (!url.includes('iframe=1')) {
                                    return url + '?iframe=1';
                                }
                            }
                            return url;
                        }
                        
                        // Function to check if it's the same page
                        function isSamePage(url) {
                            try {
                                const currentPath = window.location.pathname.split('/').pop();
                                let urlPath = url;
                                if (url.includes('/')) {
                                    urlPath = url.split('?')[0].split('/').pop();
                                } else {
                                    urlPath = url.split('?')[0];
                                }
                                return urlPath.toLowerCase() === currentPath.toLowerCase();
                            } catch(e) {
                                return false;
                            }
                        }
                        
                        // Function to send message to parent
                        function sendToParent(url, title, updateSame) {
                            if (window.parent && window.parent !== window) {
                                // Resolve relative URL to absolute
                                let absoluteUrl = url;
                                try {
                                    if (!url.startsWith('http://') && !url.startsWith('https://')) {
                                        absoluteUrl = new URL(url, window.location.href).href;
                                    }
                                } catch(err) {
                                    absoluteUrl = url;
                                }
                                
                                window.parent.postMessage({
                                    type: updateSame ? 'updateSameTab' : 'openInTab',
                                    url: absoluteUrl,
                                    title: title || null
                                }, '*');
                                return true;
                            }
                            return false;
                        }
                        
                        // Intercept link clicks
                        document.addEventListener('click', function(e) {
                            const link = e.target.closest('a');
                            if (!link) return;
                            
                            const href = link.getAttribute('href');
                            if (!href || !shouldOpenInTab(href)) return;
                            
                            // Skip if should not open in tab
                            if (link.getAttribute('target') === '_blank') return;
                            if (link.hasAttribute('data-bs-toggle')) return;
                            if (link.hasAttribute('download')) return;
                            
                            // Get title from link
                            let title = link.textContent.trim();
                            if (!title || title === '') {
                                const span = link.querySelector('span:not([class*="icon"]):not([class*="feather"])');
                                if (span) title = span.textContent.trim();
                            }
                            if (!title || title === '') {
                                title = link.getAttribute('title');
                            }
                            
                            // Clean up title - remove icons/extra whitespace
                            if (title) {
                                title = title.replace(/\\s+/g, ' ').trim();
                            }
                            
                            // Send message to parent to open in new tab
                            if (sendToParent(href, title)) {
                                e.preventDefault();
                                e.stopPropagation();
                            }
                        }, true);
                        
                        // Intercept window.location.href assignments (for JavaScript navigation like customer_ledger.php)
                        // This is tricky - we need to intercept before the navigation happens
                        
                        // Method 1: Intercept Location.prototype.href setter
                        try {
                            const locationHrefDescriptor = Object.getOwnPropertyDescriptor(Location.prototype, 'href');
                            if (locationHrefDescriptor && locationHrefDescriptor.set) {
                                const originalSetHref = locationHrefDescriptor.set;
                                
                                Object.defineProperty(Location.prototype, 'href', {
                                    set: function(url) {
                                        const urlString = String(url);
                                        
                                        // Check if same page - preserve iframe parameter
                                        if (isSamePage(urlString)) {
                                            const urlWithIframe = addIframeParam(urlString);
                                            // Send message to update same tab
                                            sendToParent(urlString, null, true);
                                            // Navigate with iframe parameter
                                            return originalSetHref.call(this, urlWithIframe);
                                        }
                                        
                                        // Different page - open in new tab
                                        if (shouldOpenInTab(urlString)) {
                                            if (sendToParent(urlString, null, false)) {
                                                return; // Prevent navigation
                                            }
                                        }
                                        
                                        // Allow normal navigation
                                        originalSetHref.call(this, urlString);
                                    },
                                    get: locationHrefDescriptor.get,
                                    configurable: true,
                                    enumerable: true
                                });
                            }
                        } catch(e) {
                            // Fallback - intercept assign and replace methods
                        }
                        
                        // Method 2: Intercept location.assign() and location.replace()
                        const originalAssign = window.location.assign;
                        const originalReplace = window.location.replace;
                        
                        window.location.assign = function(url) {
                            const urlString = String(url);
                            
                            // Check if same page - preserve iframe parameter
                            if (isSamePage(urlString)) {
                                const urlWithIframe = addIframeParam(urlString);
                                sendToParent(urlString, null, true);
                                return originalAssign.call(this, urlWithIframe);
                            }
                            
                            // Different page - open in new tab
                            if (shouldOpenInTab(urlString)) {
                                if (sendToParent(urlString, null, false)) {
                                    return; // Prevent navigation
                                }
                            }
                            return originalAssign.call(this, urlString);
                        };
                        
                        window.location.replace = function(url) {
                            const urlString = String(url);
                            
                            // Check if same page - preserve iframe parameter
                            if (isSamePage(urlString)) {
                                const urlWithIframe = addIframeParam(urlString);
                                sendToParent(urlString, null, true);
                                return originalReplace.call(this, urlWithIframe);
                            }
                            
                            // Different page - open in new tab
                            if (shouldOpenInTab(urlString)) {
                                if (sendToParent(urlString, null, false)) {
                                    return; // Prevent navigation
                                }
                            }
                            return originalReplace.call(this, urlString);
                        };
                        
                        // Intercept location.reload() to preserve iframe parameter
                        const originalReload = window.location.reload;
                        window.location.reload = function(forceReload) {
                            const currentUrl = window.location.href;
                            if (currentUrl.includes('iframe=1')) {
                                return originalReload.call(this, forceReload);
                            } else {
                                const urlWithIframe = addIframeParam(currentUrl);
                                window.location.href = urlWithIframe;
                            }
                        };
                        
                        // Load customer modal layout script if on customer list page
                        function loadCustomerModalLayout() {
                            if (window.location.pathname.includes('customer_list.php')) {
                                // Inject CSS
                                if (!document.getElementById('customer-modal-layout-css')) {
                                    const link = document.createElement('link');
                                    link.id = 'customer-modal-layout-css';
                                    link.rel = 'stylesheet';
                                    link.href = 'assets/css/customer_modal_layout.css';
                                    document.head.appendChild(link);
                                }
                                
                                // Inject JavaScript
                                if (!document.getElementById('customer-modal-layout-js')) {
                                    const script = document.createElement('script');
                                    script.id = 'customer-modal-layout-js';
                                    script.src = 'assets/js/customer_modal_layout.js';
                                    script.async = true;
                                    document.head.appendChild(script);
                                }
                            }
                        }
                        
                        // Function to auto-detect and mark customer forms
                        function markCustomerForms() {
                            // Mark Add Customer form
                            const addCustomerModal = document.getElementById('addCustomerModal');
                            if (addCustomerModal) {
                                const addForms = addCustomerModal.querySelectorAll('form');
                                addForms.forEach(function(form) {
                                    if (form.action && form.action.includes('add_customer.php')) {
                                        form.setAttribute('data-skip-iframe', 'true');
                                    }
                                });
                            }
                            
                            // Mark Edit Customer form
                            const editCustomerForm = document.getElementById('editCustomerForm');
                            if (editCustomerForm) {
                                editCustomerForm.classList.add('ajax-form');
                                editCustomerForm.setAttribute('data-ajax', 'true');
                            }
                        }
                        
                        // Load customer modal layout and mark forms when DOM is ready
                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', function() {
                                loadCustomerModalLayout();
                                markCustomerForms();
                            });
                        } else {
                            loadCustomerModalLayout();
                            markCustomerForms();
                        }
                        
                        // Also mark forms when modals are shown (Bootstrap 5)
                        document.addEventListener('shown.bs.modal', function(e) {
                            if (e.target.id === 'addCustomerModal' || e.target.id === 'editCustomerModal') {
                                markCustomerForms();
                            }
                        });
                        
                        // Also mark forms when modals are shown (Bootstrap 4/jQuery)
                        if (typeof $ !== 'undefined') {
                            $(document).on('shown.bs.modal', '#addCustomerModal, #editCustomerModal', function() {
                                markCustomerForms();
                            });
                        }
                        
                        // Intercept form submissions to preserve iframe parameter
                        document.addEventListener('submit', function(e) {
                            const form = e.target;
                            if (!form || form.tagName !== 'FORM') return;
                            
                            // Skip if form has data-skip-iframe attribute
                            if (form.hasAttribute('data-skip-iframe')) return;
                            
                            // Skip AJAX forms
                            if (form.hasAttribute('data-ajax') || form.classList.contains('ajax-form')) return;
                            
                            // Get form action URL
                            let actionUrl = form.action || '';
                            const formMethod = (form.method || 'get').toLowerCase();
                            
                            // If action is empty or just hash, it submits to the same page
                            if (!actionUrl || actionUrl === '' || actionUrl === '#') {
                                actionUrl = window.location.pathname;
                            }
                            
                            // Check if it's the same page (filter forms, etc.)
                            if (isSamePage(actionUrl) || !actionUrl || actionUrl === window.location.pathname || actionUrl.startsWith('#')) {
                                // For GET method forms, prevent default and manually navigate
                                if (formMethod === 'get') {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    
                                    // Build URL with current params, iframe param, and form fields
                                    const formData = new FormData(form);
                                    const params = new URLSearchParams();
                                    
                                    // Add current URL params (preserve existing)
                                    const currentParams = new URLSearchParams(window.location.search);
                                    currentParams.forEach((value, key) => {
                                        params.set(key, value);
                                    });
                                    
                                    // Ensure iframe parameter is set
                                    params.set('iframe', '1');
                                    
                                    // Add form fields (will overwrite any existing params with same name)
                                    formData.forEach((value, key) => {
                                        if (value && value.toString().trim() !== '') {
                                            params.set(key, value);
                                        }
                                    });
                                    
                                    // Build final URL
                                    const finalUrl = window.location.pathname + '?' + params.toString();
                                    
                                    // Navigate to the new URL (this will trigger our location.href interceptor which will handle updateSameTab)
                                    window.location.href = finalUrl;
                                    return false;
                                } else if (formMethod === 'post') {
                                    // For POST forms, add iframe as hidden input to preserve it
                                    if (!form.querySelector('input[name="iframe"]')) {
                                        const hiddenInput = document.createElement('input');
                                        hiddenInput.type = 'hidden';
                                        hiddenInput.name = 'iframe';
                                        hiddenInput.value = '1';
                                        form.appendChild(hiddenInput);
                                    }
                                }
                            } else {
                                // Different page - ensure iframe param in action
                                if (formMethod === 'get') {
                                    if (!actionUrl.includes('iframe=1')) {
                                        const separator = actionUrl.includes('?') ? '&' : '?';
                                        form.action = actionUrl + separator + 'iframe=1';
                                    }
                                }
                            }
                        }, true); // Use capture phase
                        
                        // Also intercept programmatic form submissions (like jQuery .submit())
                        const originalFormSubmit = HTMLFormElement.prototype.submit;
                        HTMLFormElement.prototype.submit = function() {
                            // Check if it's in iframe
                            if (window.self !== window.top) {
                                const actionUrl = this.action || '';
                                const formMethod = (this.method || 'get').toLowerCase();
                                
                                // Handle same-page GET submissions
                                if ((!actionUrl || actionUrl === '' || actionUrl === '#' || isSamePage(actionUrl)) && formMethod === 'get') {
                                    // Build URL with current params, iframe param, and form fields
                                    const formData = new FormData(this);
                                    const params = new URLSearchParams();
                                    
                                    // Add current URL params
                                    const currentParams = new URLSearchParams(window.location.search);
                                    currentParams.forEach((value, key) => {
                                        params.set(key, value);
                                    });
                                    
                                    // Ensure iframe parameter
                                    params.set('iframe', '1');
                                    
                                    // Add form fields
                                    formData.forEach((value, key) => {
                                        if (value && value.toString().trim() !== '') {
                                            params.set(key, value);
                                        }
                                    });
                                    
                                    // Build final URL
                                    const finalUrl = window.location.pathname + '?' + params.toString();
                                    
                                    // Navigate manually (this will trigger our location.href interceptor)
                                    window.location.href = finalUrl;
                                    return;
                                } else if (formMethod === 'post') {
                                    // For POST, add hidden input
                                    if (!this.querySelector('input[name="iframe"]')) {
                                        const hiddenInput = document.createElement('input');
                                        hiddenInput.type = 'hidden';
                                        hiddenInput.name = 'iframe';
                                        hiddenInput.value = '1';
                                        this.appendChild(hiddenInput);
                                    }
                                }
                            }
                            return originalFormSubmit.call(this);
                        };
                    }
                })();
            `;
            
            // Inject when iframe is ready
            if (iframeDoc.readyState === 'loading') {
                iframeDoc.addEventListener('DOMContentLoaded', () => {
                    try {
                        if (iframeDoc.head && !iframeDoc.getElementById('tab-link-interceptor')) {
                            iframeDoc.head.appendChild(script);
                        }
                    } catch(e) {
                        // Ignore errors
                    }
                });
            } else {
                // Already loaded
                if (iframeDoc.head && !iframeDoc.getElementById('tab-link-interceptor')) {
                    iframeDoc.head.appendChild(script);
                }
            }
        } catch(e) {
            // Cross-origin or other error - ignore
        }
    }

    interceptNavigationLinks() {
        // Intercept clicks on navigation links
        document.addEventListener('click', (e) => {
            const link = e.target.closest('a');
            if (!link) return;

            const href = link.getAttribute('href');
            if (!href) return;

            // Check if link should open in tab
            if (this.shouldOpenInTab(link, href)) {
                e.preventDefault();
                e.stopPropagation();
                
                // Get page title from link text or span within nav-icon-item
                let pageTitle = this.getPageTitleFromLink(link);
                if (!pageTitle) {
                    pageTitle = this.getPageTitleFromUrl(href);
                }
                
                this.openTab(href, pageTitle);
            }
        }, true);
    }
    
    getPageTitleFromLink(link) {
        // Try to get title from span text in nav-icon-item structure
        const navItem = link.closest('.nav-icon-item');
        if (navItem) {
            // Find the span that contains the text (not in icon-box)
            const spans = navItem.querySelectorAll('span');
            for (let span of spans) {
                // Skip spans that are inside icon-box or are just icons
                if (!span.closest('.icon-box')) {
                    const text = span.textContent.trim();
                    if (text && text.length > 0) {
                        return text;
                    }
                }
            }
        }
        
        // Try to get from link text directly (excluding icon text)
        let linkText = link.textContent.trim();
        // Remove any icon text or empty text
        linkText = linkText.replace(/\s+/g, ' ').trim();
        if (linkText && linkText.length > 0 && linkText !== 'ITR POS') {
            return linkText;
        }
        
        // Try to get from title attribute
        const titleAttr = link.getAttribute('title');
        if (titleAttr) {
            return titleAttr;
        }
        
        return null;
    }

    shouldOpenInTab(link, href) {
        // Skip if already has target="_blank"
        if (link.getAttribute('target') === '_blank') return false;
        
        // Skip external links
        if (href.startsWith('http://') || href.startsWith('https://')) {
            if (!href.includes(window.location.hostname)) return false;
        }
        
        // Skip anchor links
        if (href.startsWith('#')) return false;
        
        // Skip javascript: links
        if (href.startsWith('javascript:')) return false;
        
        // Skip data-bs-toggle (modals)
        if (link.hasAttribute('data-bs-toggle')) return false;
        
        // Skip download links
        if (link.hasAttribute('download')) return false;
        
        // Skip print pages - open in new window
        if (href.includes('print_') || href.includes('vouchers/')) return false;
        
        // Skip POS page - open normally
        if (href.includes('pos.php')) return false;
        
        // Skip login/logout
        if (href.includes('login.php') || href.includes('logout.php')) return false;
        
        // Skip dashboard/index - allow normal navigation for logo/home link
        if (href === 'index.php' && link.closest('.primary-navigation a[href="index.php"]')) {
            return false; // Logo link opens normally
        }
        
        // Only intercept links in navigation areas or page content areas
        const isInNav = link.closest('.primary-navigation, .secondary-navigation, .nav-icon-item');
        const isInContent = link.closest('.page-wrapper, .content, .card-body');
        
        // Intercept navigation links OR content links with report-link class
        if (isInNav !== null) {
            return true;
        }
        
        // Intercept report links and other page content links (but not in iframes)
        if (isInContent !== null && !link.closest('.tab-content-frame')) {
            // Check if it's a report link or similar
            if (link.classList.contains('report-link') || 
                link.closest('.report-link') ||
                link.closest('.card-body, .list-unstyled')) {
                return true;
            }
        }
        
        return false;
    }

    getPageTitleFromUrl(url) {
        // Extract filename from URL
        const filename = url.split('/').pop().split('?')[0];
        // Convert filename to readable title
        return filename
            .replace('.php', '')
            .replace(/_/g, ' ')
            .replace(/\b\w/g, l => l.toUpperCase());
    }

    openTab(url, title) {
        // Check if tab already exists
        const existingTab = this.tabs.find(tab => tab.url === url);
        if (existingTab) {
            this.switchTab(existingTab.id);
            return existingTab.id;
        }

        // Check max tabs limit
        if (this.tabs.length >= this.maxTabs) {
            // Close oldest tab
            this.closeTab(this.tabs[0].id);
        }

        // Generate tab ID
        const tabId = 'tab-' + (++this.tabCounter);

        // Create tab object
        const tab = {
            id: tabId,
            url: url,
            title: title || this.getPageTitleFromUrl(url),
            createdAt: Date.now()
        };

        this.tabs.push(tab);

        // Create tab UI
        this.createTabUI(tab);

        // Create iframe
        this.createTabIframe(tab);

        // Switch to new tab
        this.switchTab(tabId);

        // Save to storage
        this.saveTabsToStorage();

        // Enable tab system
        document.body.classList.add('tabs-active');

        // Hide empty state
        const emptyState = document.getElementById('tabEmptyState');
        if (emptyState) {
            emptyState.style.display = 'none';
        }

        return tabId;
    }

    createTabUI(tab) {
        const tabBar = document.querySelector('.tab-bar');
        if (!tabBar) return;

        const tabItem = document.createElement('div');
        tabItem.className = 'tab-item';
        tabItem.dataset.tabId = tab.id;
        tabItem.innerHTML = `
            <span class="tab-title">${this.escapeHtml(tab.title)}</span>
            <button class="tab-close" title="Close">
                <i data-feather="x"></i>
            </button>
        `;

        tabBar.appendChild(tabItem);

        // Initialize feather icons
        if (typeof feather !== 'undefined') {
            feather.replace();
        }

        // Attach event listeners
        const titleEl = tabItem.querySelector('.tab-title');
        titleEl.addEventListener('click', () => this.switchTab(tab.id));
        tabItem.addEventListener('click', (e) => {
            if (!e.target.closest('.tab-close')) {
                this.switchTab(tab.id);
            }
        });

        const closeBtn = tabItem.querySelector('.tab-close');
        closeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.closeTab(tab.id);
        });

        // Right-click context menu
        tabItem.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            this.showContextMenu(e, tab.id);
        });
    }

    createTabIframe(tab) {
        const container = document.querySelector('.tab-content-container');
        if (!container) return;

        const iframe = document.createElement('iframe');
        iframe.id = tab.id + '-frame';
        iframe.className = 'tab-content-frame loading';
        
        // Add iframe parameter to URL to detect iframe loading
        const separator = tab.url.includes('?') ? '&' : '?';
        iframe.src = tab.url + separator + 'iframe=1';
        iframe.setAttribute('data-tab-id', tab.id);

        // Handle iframe load
        iframe.addEventListener('load', () => {
            iframe.classList.remove('loading');
            this.updateTabTitleFromIframe(tab.id);
            // Setup link interception for this iframe
            setTimeout(() => {
                this.injectLinkInterceptorIntoIframe(iframe);
            }, 500);
        });

        // Handle iframe errors
        iframe.addEventListener('error', () => {
            iframe.classList.remove('loading');
            console.error('Failed to load tab:', tab.url);
        });

        container.appendChild(iframe);
    }

    switchTab(tabId) {
        // Update active tab
        this.activeTabId = tabId;

        // Update UI
        document.querySelectorAll('.tab-item').forEach(item => {
            if (item.dataset.tabId === tabId) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });

        // Show/hide iframes
        document.querySelectorAll('.tab-content-frame').forEach(frame => {
            if (frame.dataset.tabId === tabId) {
                frame.classList.add('active');
            } else {
                frame.classList.remove('active');
            }
        });

        // Hide empty state
        const emptyState = document.getElementById('tabEmptyState');
        if (emptyState) {
            emptyState.style.display = 'none';
        }
    }

    closeTab(tabId) {
        // Remove from tabs array
        this.tabs = this.tabs.filter(tab => tab.id !== tabId);

        // Remove UI
        const tabItem = document.querySelector(`[data-tab-id="${tabId}"]`);
        if (tabItem) {
            tabItem.remove();
        }

        // Remove iframe
        const iframe = document.getElementById(tabId + '-frame');
        if (iframe) {
            iframe.remove();
        }

        // Switch to another tab if this was active
        if (this.activeTabId === tabId) {
            if (this.tabs.length > 0) {
                // Switch to last tab
                this.switchTab(this.tabs[this.tabs.length - 1].id);
            } else {
                this.activeTabId = null;
                // Disable tab system, show default content
                document.body.classList.remove('tabs-active');
                // Show empty state
                const emptyState = document.getElementById('tabEmptyState');
                if (emptyState) {
                    emptyState.style.display = 'flex';
                }
            }
        }

        // Save to storage
        this.saveTabsToStorage();
    }

    closeAllTabs() {
        const tabIds = [...this.tabs.map(tab => tab.id)];
        tabIds.forEach(id => this.closeTab(id));
    }

    closeOtherTabs(tabId) {
        const tabIds = this.tabs.filter(tab => tab.id !== tabId).map(tab => tab.id);
        tabIds.forEach(id => this.closeTab(id));
    }

    reloadTab(tabId) {
        const iframe = document.getElementById(tabId + '-frame');
        if (iframe) {
            iframe.classList.add('loading');
            iframe.src = iframe.src; // Reload
        }
    }

    updateTabTitle(tabId, title) {
        const tab = this.tabs.find(t => t.id === tabId);
        if (tab) {
            tab.title = title;
            const tabItem = document.querySelector(`[data-tab-id="${tabId}"] .tab-title`);
            if (tabItem) {
                tabItem.textContent = title;
            }
            this.saveTabsToStorage();
        }
    }

    updateTabTitleFromIframe(tabId) {
        const iframe = document.getElementById(tabId + '-frame');
        if (!iframe) return;

        try {
            // Try to get title from iframe (may fail due to cross-origin)
            const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            
            // Try to get title from document title
            let title = iframeDoc.title;
            
            // If no title, try to get from page-header or page-title
            if (!title || title === 'ITR POS') {
                const pageTitle = iframeDoc.querySelector('.page-title h4, .page-header h4, h4.page-title');
                if (pageTitle) {
                    title = pageTitle.textContent.trim();
                }
            }
            
            // Clean up title - remove "ITR POS" prefix if present
            if (title && title.includes('|')) {
                title = title.split('|')[0].trim();
            }
            if (title && title.toLowerCase() === 'itr pos') {
                // Try to get from URL or link
                const tab = this.tabs.find(t => t.id === tabId);
                if (tab) {
                    title = tab.title; // Keep original title from link
                }
            }
            
            if (title && title !== 'ITR POS') {
                this.updateTabTitle(tabId, title);
            }
        } catch (e) {
            // Cross-origin or other error - ignore
            // This is expected for same-origin pages, but won't work cross-origin
        }
    }

    showContextMenu(e, tabId) {
        this.contextMenuTabId = tabId;
        this.contextMenu.style.display = 'block';
        this.contextMenu.style.left = e.pageX + 'px';
        this.contextMenu.style.top = e.pageY + 'px';
        this.contextMenu.classList.add('show');
    }

    hideContextMenu() {
        if (this.contextMenu) {
            this.contextMenu.classList.remove('show');
            this.contextMenu.style.display = 'none';
        }
    }

    handleContextMenuAction(action) {
        if (!this.contextMenuTabId) return;

        switch (action) {
            case 'close':
                this.closeTab(this.contextMenuTabId);
                break;
            case 'close-others':
                this.closeOtherTabs(this.contextMenuTabId);
                break;
            case 'close-all':
                this.closeAllTabs();
                break;
            case 'reload':
                this.reloadTab(this.contextMenuTabId);
                break;
        }

        this.hideContextMenu();
    }

    saveTabsToStorage() {
        try {
            const tabsData = this.tabs.map(tab => ({
                id: tab.id,
                url: tab.url,
                title: tab.title,
                createdAt: tab.createdAt
            }));
            sessionStorage.setItem('itrpos_tabs', JSON.stringify(tabsData));
            sessionStorage.setItem('itrpos_active_tab', this.activeTabId);
        } catch (e) {
            console.error('Failed to save tabs to storage:', e);
        }
    }

    loadTabsFromStorage() {
        try {
            const tabsData = sessionStorage.getItem('itrpos_tabs');
            if (tabsData) {
                const tabs = JSON.parse(tabsData);
                tabs.forEach(tab => {
                    this.tabs.push(tab);
                    this.createTabUI(tab);
                    this.createTabIframe(tab);
                });
            }

            const activeTabId = sessionStorage.getItem('itrpos_active_tab');
            if (activeTabId && this.tabs.find(t => t.id === activeTabId)) {
                this.switchTab(activeTabId);
                document.body.classList.add('tabs-active');
            } else if (this.tabs.length > 0) {
                // Activate first tab
                this.switchTab(this.tabs[0].id);
                document.body.classList.add('tabs-active');
                // Hide empty state
                const emptyState = document.getElementById('tabEmptyState');
                if (emptyState) {
                    emptyState.style.display = 'none';
                }
            } else {
                // Show empty state if no tabs
                const emptyState = document.getElementById('tabEmptyState');
                if (emptyState) {
                    emptyState.style.display = 'flex';
                }
            }
        } catch (e) {
            console.error('Failed to load tabs from storage:', e);
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Tab Manager initialization DISABLED - Tab system has been removed
// Links will now navigate normally instead of opening in tabs
// Initialize Tab Manager when DOM is ready
// Only initialize if NOT inside an iframe (to prevent nested tab systems)
/*
document.addEventListener('DOMContentLoaded', () => {
    if (window.self === window.top) {
        // We're in the main window, not an iframe
        window.tabManager = new TabManager();
    } else {
        // We're inside an iframe - hide header/navigation, show only page content
        const header = document.querySelector('.top-info-bar, .primary-navigation, .secondary-navigation, .tab-system-container');
        if (header) {
            header.style.display = 'none';
        }
        // Hide tab system if it exists
        const tabSystem = document.querySelector('.tab-system-container');
        if (tabSystem) {
            tabSystem.style.display = 'none';
        }
        // Make page wrapper full height
        const pageWrapper = document.querySelector('.page-wrapper');
        if (pageWrapper) {
            pageWrapper.style.marginTop = '0';
            pageWrapper.style.paddingTop = '10px';
        }
    }
});
*/

