<?php
namespace Components;

class SitePanel extends Base
{
    public static function render(array $opts = []): string
    {
        $panelId = $opts['id'] ?? 'app-site-panel';
        $bodyId = $opts['body_id'] ?? 'app-site-panel-body';
        $loadingId = $opts['loading_id'] ?? 'app-site-panel-loading';

        $title = $opts['title'] ?? '';
        $content = $opts['content'] ?? '';

        $onboardingProgress = isset($opts['onboarding_progress']) ? (float) $opts['onboarding_progress'] : 43.0;
        $onboardingIcon = self::renderRocketProgressIcon($onboardingProgress);

        $tabs = [
            [
                'value' => 'health',
                'label' => Base::lng('UI_HUB_TAB_HEALTH', 'Status'),
                'icon' => Base::SVG_PULSE
            ],
            [
                'value' => 'notifications',
                'label' => Base::lng('UI_HUB_TAB_NOTIFICATIONS', 'Notifications'),
                'icon' => Base::SVG_BELL
            ],
/*
            [
                'value' => 'onboarding',
                'label' => Base::lng('UI_HUB_TAB_ONBOARDING', 'Onboarding'),
                'icon' => $onboardingIcon
            ],
*/
            [
                'value' => 'view',
                'label' => Base::lng('UI_HUB_TAB_VIEW', 'View'),
                'icon' => Base::SVG_EYE,
                'x-show' => "hubTab === 'view' || viewHasContent"
            ],
        ];

        if (!empty($opts['include']) && is_file($opts['include'])) {
            ob_start();
            include $opts['include'];
            $content .= ob_get_clean();
        }

        $initialCollapsed = $opts['collapsed'] ?? empty($content);

        ob_start();
        ?>
        <script>
            (function() {
                const STORAGE_KEY_WIDTH = 'mb-site-panel-width';
                const STORAGE_KEY_COLLAPSED = 'mb-site-panel-collapsed';
                
                const sitePanelComponent = () => ({
                        panelWidth: parseInt(localStorage.getItem(STORAGE_KEY_WIDTH)) || 350,
                        panelCollapsed: <?= $initialCollapsed ? 'localStorage.getItem(STORAGE_KEY_COLLAPSED) !== "false"' : 'false' ?>,
                        panelTitle: <?= json_encode($title) ?>,
                        hubTab: 'health',
                        viewHasContent: <?= !empty($content) ? 'true' : 'false' ?>,
                        isResizing: false,
                        isRefreshing: 0,
                        lastToggle: 0,
                        
                        init() {
                            window.addEventListener('mb-site-panel-reset-view', () => this.resetView());
                            if (!this.panelCollapsed && !this.panelTitle) {
                                if (this.hubTab === 'notifications') {
                                    const targetId = '<?= $bodyId ?>-notifications';
                                    const target = document.getElementById(targetId);
                                    if (target && target.innerHTML.trim() === '') {
                                        htmx.ajax('GET', '<?= \Components\Router::url('notification_hub', ['partial' => 1, 'hub_tab' => 'notifications']) ?>', {
                                            target: '#' + targetId,
                                            headers: {
                                                'X-No-Global-Loader': '1',
                                                'X-No-Local-Loader': '1'
                                            }
                                        });
                                    }
                                } else if (this.hubTab === 'health') {
                                    const targetId = '<?= $bodyId ?>-health';
                                    const target = document.getElementById(targetId);
                                    if (target && target.innerHTML.trim() === '') {
                                        htmx.ajax('GET', '<?= \Components\Router::url('health_hub', ['partial' => 1, 'hub_tab' => 'health']) ?>', {
                                            target: '#' + targetId,
                                            headers: {
                                                'X-No-Global-Loader': '1',
                                                'X-No-Local-Loader': '1'
                                            }
                                        });
                                    }
                                }
                            }
                        },

                        switchTab(tab) {
                            this.hubTab = tab;
                            this.panelTitle = ''; // Hide title when showing hub tabs
                        },

                        resetView() {
                            this.viewHasContent = false;
                            this.hubTab = 'notifications';
                            this.panelTitle = '';
                            const targetId = '<?= $bodyId ?>-view';
                            const target = document.getElementById(targetId);
                            if (target) {
                                target.innerHTML = `<?= str_replace(["\r", "\n"], '', self::viewSkeleton()) ?>`;
                            }
                        },
                        
                        startResizing(e) {
                            if (this.panelCollapsed) return;
                            this.isResizing = true;
                            const startX = e.clientX;
                            const startWidth = this.panelWidth;
                            
                            const onMouseMove = (moveEvent) => {
                                if (!this.isResizing) return;
                                const diff = startX - moveEvent.clientX;
                                let newWidth = startWidth + diff;
                                if (newWidth < 300) newWidth = 300;
                                if (newWidth > 500) newWidth = 500; // Increased limit slightly for flexibility
                                this.panelWidth = newWidth;
                            };
                            
                            const onMouseUp = () => {
                                this.isResizing = false;
                                localStorage.setItem(STORAGE_KEY_WIDTH, this.panelWidth);
                                document.removeEventListener('mousemove', onMouseMove);
                                document.removeEventListener('mouseup', onMouseUp);
                                document.body.classList.remove('cursor-col-resize', 'select-none');
                            };
                            
                            document.addEventListener('mousemove', onMouseMove);
                            document.addEventListener('mouseup', onMouseUp);
                            document.body.classList.add('cursor-col-resize', 'select-none');
                        },
                        
                        togglePanel(opts = {}) {
                            this.lastToggle = Date.now();
                            if (this.panelCollapsed) {
                                this.openPanel(opts);
                            } else {
                                // If it's open, and we didn't provide specific opts, or we provided the SAME tab/title, then close.
                                // Otherwise, open with new opts (which might just switch tab).
                                const isSameTab = !opts.tab || this.hubTab === opts.tab;
                                const isSameTitle = opts.title === undefined || this.panelTitle === (opts.title || '');

                                if (isSameTab && isSameTitle) {
                                    this.panelCollapsed = true;
                                    localStorage.setItem(STORAGE_KEY_COLLAPSED, true);
                                } else {
                                    this.openPanel(opts);
                                }
                            }
                        },

                        refreshCurrentTab() {
                            if (this.isRefreshing) return;

                            const tab = this.hubTab;
                            if (tab === 'notifications') {
                                this.$dispatch('notifications-refresh');
                            } else if (tab === 'health') {
                                this.$dispatch('health-refresh');
                            }
                        },

                        openPanel(opts = {}) {
                            if (opts.collapsed) {
                                this.panelCollapsed = true;
                                localStorage.setItem(STORAGE_KEY_COLLAPSED, true);
                                return;
                            }
                            if (this.panelCollapsed) this.lastToggle = Date.now();
                            this.panelCollapsed = false;
                            localStorage.setItem(STORAGE_KEY_COLLAPSED, false);

                            if (opts.tab) {
                                this.hubTab = opts.tab;
                            }

                            if (opts.title !== undefined) {
                                this.panelTitle = opts.title || '';
                            }

                            const targetId = '<?= $bodyId ?>-' + (this.panelTitle ? 'view' : (opts.tab || this.hubTab));
                            const target = document.getElementById(targetId);

                            if (opts.content) {
                                if (target) target.innerHTML = opts.content;
                            }

                            if (targetId === '<?= $bodyId ?>-view' && (opts.content || opts.url || opts.tab === 'view' || this.panelTitle)) {
                                this.viewHasContent = true;
                            }
                            
                            if (opts.url && window.htmx) {
                                if (target) htmx.ajax('GET', opts.url, { target: '#' + target.id });
                            }

                            if (!opts.content && !opts.url && opts.tab) {
                                this.switchTab(opts.tab);
                            }

                            if (this.hubTab === 'notifications' && !this.panelTitle) {
                                const targetId = '<?= $bodyId ?>-notifications';
                                const target = document.getElementById(targetId);
                                if (target && target.innerHTML.trim() === '') {
                                    htmx.ajax('GET', '<?= \Components\Router::url('notification_hub', ['partial' => 1, 'hub_tab' => 'notifications']) ?>', {
                                        target: '#' + targetId,
                                        headers: {
                                            'X-No-Global-Loader': '1',
                                            'X-No-Local-Loader': '1'
                                        }
                                    });
                                }
                            } else if (this.hubTab === 'health' && !this.panelTitle) {
                                const targetId = '<?= $bodyId ?>-health';
                                const target = document.getElementById(targetId);
                                if (target && target.innerHTML.trim() === '') {
                                    htmx.ajax('GET', '<?= \Components\Router::url('health_hub', ['partial' => 1, 'hub_tab' => 'health']) ?>', {
                                        target: '#' + targetId,
                                        headers: {
                                            'X-No-Global-Loader': '1',
                                            'X-No-Local-Loader': '1'
                                        }
                                    });
                                }
                            }
                        }
                    });

                window.sitePanel = sitePanelComponent;
                const register = () => {
                    if (window.Alpine) {
                        Alpine.data('sitePanel', sitePanelComponent);
                    }
                };
                if (window.Alpine) {
                    register();
                } else {
                    document.addEventListener('alpine:init', register);
                }

                // Global helper
                window.MBSitePanel = {
                    open: (opts) => {
                        window.dispatchEvent(new CustomEvent('mb-site-panel-open-internal', { detail: opts }));
                    },
                    close: () => {
                        window.dispatchEvent(new CustomEvent('mb-site-panel-open-internal', { detail: { collapsed: true } }));
                    },
                    toggle: (opts) => {
                        window.dispatchEvent(new CustomEvent('mb-site-panel-toggle-internal', { detail: opts }));
                    },
                    resetView: () => {
                        window.dispatchEvent(new CustomEvent('mb-site-panel-reset-view'));
                    }
                };
                
                document.addEventListener('mb-site-panel-open', (e) => {
                    window.MBSitePanel.open(e.detail);
                });

                document.addEventListener('click', (e) => {
                    const btn = e.target.closest('[command]');
                    if (!btn) return;

                    const command = btn.getAttribute('command');
                    const targetId = btn.getAttribute('commandfor');
                    if (!targetId) return;

                    if (targetId === '<?= $panelId ?>' || targetId.startsWith('<?= $bodyId ?>')) {
                        if (command === 'show-sitepanel' || command === 'toggle-sitepanel') {
                            const url = btn.getAttribute('data-url') || btn.getAttribute('hx-get');
                            const tab = btn.getAttribute('data-tab');
                            const title = btn.hasAttribute('data-title') ? btn.getAttribute('data-title') : (tab ? null : btn.title);
                            const content = btn.getAttribute('data-content');

                            const opts = {
                                title: title || null,
                                content: content || null,
                                tab: tab || null
                            };

                            // Only pass URL if it's NOT an HTMX button already targeting our body
                            const hxTarget = btn.getAttribute('hx-target');
                            if (url && (!hxTarget || !hxTarget.startsWith('#' + '<?= $bodyId ?>'))) {
                                opts.url = url;
                            }

                            if (command === 'toggle-sitepanel') {
                                window.MBSitePanel.toggle(opts);
                            } else {
                                window.MBSitePanel.open(opts);
                            }
                        } else if (command === 'close') {
                            window.MBSitePanel.close();
                        }
                    }
                }, true);

                document.addEventListener('htmx:afterOnLoad', (e) => {
                    const hubTabs = ['health','notifications',  'onboarding', 'view'];
                    const isHubTarget = hubTabs.some(tab => e.detail.target.id === '<?= $bodyId ?>-' + tab);

                    if (e.detail.target.id === '<?= $bodyId ?>' || isHubTarget) {
                        if (e.detail.target.id === '<?= $bodyId ?>-view') {
                            const panel = document.getElementById('<?= $panelId ?>');
                            if (panel && window.Alpine) {
                                Alpine.$data(panel).viewHasContent = true;
                            }
                        }

                        const title = e.detail.xhr.getResponseHeader('X-Site-Panel-Title');
                        const opts = {};
                        if (title) {
                            opts.title = title;
                        }
                        window.MBSitePanel.open(opts);
                    }
                });

                // HTMX listener to bind loader
                if (window.MBLoader && window.MBLoader.bindHtmxOverlay) {
                    window.MBLoader.bindHtmxOverlay('<?= $bodyId ?>-health', '<?= $loadingId ?>', 350);
                    window.MBLoader.bindHtmxOverlay('<?= $bodyId ?>-notifications', '<?= $loadingId ?>', 350);
                    window.MBLoader.bindHtmxOverlay('<?= $bodyId ?>-onboarding', '<?= $loadingId ?>', 350);
                    window.MBLoader.bindHtmxOverlay('<?= $bodyId ?>-view', '<?= $loadingId ?>', 350);
                }
            })();
        </script>
        <div x-data="sitePanel()" class="flex h-full shrink-0">
        <!-- Resize handle / Toggle bar -->
        <div id="<?= self::h($panelId) ?>-resizer"
             x-cloak
             class="relative group flex cursor-col-resize items-center justify-center transition-all duration-300 z-10"
             :class="[
                panelCollapsed ? ' w-0 right-4.25 ' : ' w-2 -right-1.25',
                isResizing ? '!duration-0' : ''
             ]"
             @mousedown="startResizing($event)"
             @click="panelCollapsed && togglePanel()"
             @dblclick="!panelCollapsed && (Date.now() - lastToggle > 400) && togglePanel()"
        >
            <div class="z-10 flex h-22 w-1.25  shrink-0 rounded-lg bg-divider"></div>
        </div>

        <!-- Site Panel Container -->
        <div id="<?= self::h($panelId) ?>" 
             class="relative flex flex-col overflow-hidden rounded-2xl border border-divider/70 bg-canvas transition-all"
             :class="[
                panelCollapsed ? 'w-0 border-0 ease-out opacity-0 duration-300' : 'ml-2.5 ease-out-back-sm duration-400',
                isResizing ? '!duration-0' : ''
             ]"
             :style="{ width: panelCollapsed ? '0' : panelWidth + 'px' }"
             @mb-site-panel-open-internal.window="openPanel($event.detail)"
             @mb-site-panel-toggle-internal.window="togglePanel($event.detail)"
             x-cloak
        >
            <div class="flex h-full flex-col shrink-0" :style="{ width: panelWidth + 'px' }">
                <!-- Panel Header -->
                <div class="flex items-center justify-between border-b border-divider px-4 py-0.5 pb-0 shrink-0 " x-cloak>
                    <div class="flex-1 min-w-0" x-show="!panelTitle">
                        <?= Ui\Tabs::desktopNavOnly('hubTab', $tabs, [
                            'compact' => true,
                            'activeClasses' => 'inline-flex items-center gap-1.5 border-b-2 px-1 py-3 text-sm font-medium whitespace-nowrap border-brand text-brand',
                            'inactiveClasses' => 'inline-flex items-center gap-1.5 border-b-2 px-1 py-3 text-sm font-medium whitespace-nowrap border-transparent text-secondary hover:border-emphasis hover:text-primary',
                            'onClick' => 'switchTab({value})'
                        ]) ?>
                    </div>
                    <h3 class="text-sm font-medium text-secondary truncate" x-text="panelTitle" x-show="panelTitle"></h3>
                    <div class="flex items-center gap-3">
                        <button type="button"
                                x-show="['health', 'notifications'].includes(hubTab) && !panelTitle"
                                @click="refreshCurrentTab()"
                                class="relative rounded-md text-gray-400 hover:text-gray-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand dark:hover:text-white dark:focus-visible:outline-brand-500"
                                title="<?= self::h(Base::lng('UI_REFRESH', 'Refresh')) ?>"
                        >
                            <span class="sr-only">Refresh</span>
                            <div class="[&_svg]:size-3.5" :class="isRefreshing ? 'animate-spin' : ''">
                                <?= Base::SVG_REFRESH; ?>
                            </div>
                        </button>
                        <button type="button" @click="togglePanel()"
                                class="relative rounded-md text-gray-400 hover:text-gray-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand dark:hover:text-white dark:focus-visible:outline-brand-500"
                        >
                            <span class="absolute -inset-2.5"></span>
                            <span class="sr-only">Close modal</span>
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"
                                 class="size-5">
                                <path d="M6 18 18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </button>
                    </div>

                </div>

                <div class="relative min-h-0 flex-1"
                     <?= self::scrollHintsData(); ?>
                     @htmx:before-request="if ($event.detail.pathInfo && $event.detail.pathInfo.requestPath && ($event.detail.pathInfo.requestPath.includes('notification') || $event.detail.pathInfo.requestPath.includes('health'))) isRefreshing++"
                     @htmx:after-request="if ($event.detail.pathInfo && $event.detail.pathInfo.requestPath && ($event.detail.pathInfo.requestPath.includes('notification') || $event.detail.pathInfo.requestPath.includes('health'))) isRefreshing = Math.max(0, isRefreshing - 1)"
                >
                    <div class="relative h-full overflow-auto px-4 py-3"
                         x-ref="scroller"
                         @scroll.passive="update()"
                    >
                        <?= self::loaderOverlay($loadingId, 'z-10 rounded-2xl'); ?>
                        <div id="<?= self::h($bodyId) ?>-notifications" x-show="hubTab === 'notifications' && !panelTitle">
                        <?php
                            include BEEZUI_ROOT . '/pages/components/notification_hub.php';
                        ?>
                    </div>
                        <div id="<?= self::h($bodyId) ?>-health" x-show="hubTab === 'health' && !panelTitle">
                        <?php
                            include BEEZUI_ROOT . '/pages/components/health_hub.php';
                        ?>
                    </div>
                        <div id="<?= self::h($bodyId) ?>-onboarding" x-show="hubTab === 'onboarding' && !panelTitle">
                        <?= Ui\EmptyState::simple([
                            'icon' => Base::SVG_ROCKET,
                            'title' => 'Onboarding',
                            'text' => 'Coming soon...'
                        ]) ?>
                    </div>
                        <div id="<?= self::h($bodyId) ?>-view" x-show="hubTab === 'view' || panelTitle">
                        <?php if (empty($content)): ?>
                            <?= self::viewSkeleton() ?>
                        <?php else: ?>
                            <?= $content ?>
                        <?php endif; ?>
                    </div>

                    </div>

                    <?= self::scrollHintsHtml([
                        'top_from' => 'from-canvas',
                        'bottom_from' => 'from-canvas',
                    ]); ?>
                </div>
            </div>
        </div>

        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render a loading skeleton for the view tab
     */
    public static function viewSkeleton(): string
    {
        ob_start();
        ?>
        <div class="animate-pulse space-y-6 px-1 pt-4">
            <div class="rounded-lg bg-divider/70 px-4 py-4 border border-divider/50">
                <div class="h-4 bg-muted rounded w-1/3 mb-3"></div>
                <div class="h-3 bg-muted rounded w-1/2"></div>
            </div>
            <div class="space-y-4 px-1">
                <div class="h-3 bg-divider/50 rounded w-1/4 mb-4"></div>
                <div class="space-y-3">
                    <div class="h-9 bg-divider/70 rounded-lg w-full border border-divider/50"></div>
                    <div class="h-9 bg-divider/70 rounded-lg w-full border border-divider/50"></div>
                    <div class="h-9 bg-divider/70 rounded-lg w-full border border-divider/50"></div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
}
