export function toggleSidebar() {
    const sidebar = document.getElementById('rightSidebar');
    sidebar.classList.toggle('collapsed');
    localStorage.setItem('sidebar_collapsed', sidebar.classList.contains('collapsed'));
    
    // Resize chart after sidebar toggle
    setTimeout(() => {
        if (window.dashboard && window.dashboard.chart) {
            const container = document.getElementById('chart');
            window.dashboard.chart.applyOptions({
                width: container.clientWidth,
                height: container.clientHeight
            });
        }
    }, 350); // Wait for CSS transition
}

export function restoreSidebarState() {
    const collapsed = localStorage.getItem('sidebar_collapsed') !== 'false'; // Default to collapsed
    const sidebar = document.getElementById('rightSidebar');
    if (collapsed && sidebar) {
        sidebar.classList.add('collapsed');
    }
}

// Tab Management
let activeTab = 'indicators';

export function initSidebarTabs() {
    const tabs = document.querySelectorAll('.sidebar-tab');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            switchTab(tab.dataset.tab);
        });
    });
}

export function switchTab(tabId) {
    activeTab = tabId;
    localStorage.setItem('sidebar_active_tab', tabId);
    
    document.querySelectorAll('.sidebar-tab').forEach(tab => {
        tab.classList.toggle('active', tab.dataset.tab === tabId);
    });
    
    document.querySelectorAll('.sidebar-tab-panel').forEach(panel => {
        panel.classList.toggle('active', panel.id === `tab-${tabId}`);
    });
    
    if (tabId === 'indicators') {
        setTimeout(() => {
            if (window.drawIndicatorsOnChart) {
                window.drawIndicatorsOnChart();
            }
        }, 50);
    } else if (tabId === 'strategy') {
        setTimeout(() => {
            if (window.renderStrategyPanel) {
                window.renderStrategyPanel();
            }
        }, 50);
    }
}

export function getActiveTab() {
    return activeTab;
}

export function restoreSidebarTabState() {
    const savedTab = localStorage.getItem('sidebar_active_tab') || 'indicators';
    switchTab(savedTab);
}
