var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import { DeesElement, property, html, customElement, queryAsync, render, domtools } from '@design.estate/dees-element';
import { resolveTemplateFactory, getDemoAtIndex, getDemoCount, hasMultipleDemos } from './wcctools.helpers.js';
import * as plugins from '../wcctools.plugins.js';
// wcc tools
import './wcc-frame.js';
import './wcc-sidebar.js';
import './wcc-properties.js';
import {} from './wcc-properties.js';
import { breakpoints } from '@design.estate/dees-domtools';
import { WccFrame } from './wcc-frame.js';
import { WccSidebar } from './wcc-sidebar.js';
/**
 * Get filtered and sorted items from a section
 */
export const getSectionItems = (section) => {
    let entries = Object.entries(section.items);
    // Apply filter if provided
    if (section.filter) {
        const filterFn = section.filter;
        entries = entries.filter(([name, item]) => filterFn(name, item));
    }
    // Apply sort if provided
    if (section.sort) {
        entries.sort(section.sort);
    }
    return entries;
};
let WccDashboard = (() => {
    let _classDecorators = [customElement('wcc-dashboard')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _sections_decorators;
    let _sections_initializers = [];
    let _sections_extraInitializers = [];
    let _selectedSection_decorators;
    let _selectedSection_initializers = [];
    let _selectedSection_extraInitializers = [];
    let _selectedType_decorators;
    let _selectedType_initializers = [];
    let _selectedType_extraInitializers = [];
    let _selectedItemName_decorators;
    let _selectedItemName_initializers = [];
    let _selectedItemName_extraInitializers = [];
    let _selectedItem_decorators;
    let _selectedItem_initializers = [];
    let _selectedItem_extraInitializers = [];
    let _selectedDemoIndex_decorators;
    let _selectedDemoIndex_initializers = [];
    let _selectedDemoIndex_extraInitializers = [];
    let _selectedViewport_decorators;
    let _selectedViewport_initializers = [];
    let _selectedViewport_extraInitializers = [];
    let _selectedTheme_decorators;
    let _selectedTheme_initializers = [];
    let _selectedTheme_extraInitializers = [];
    let _searchQuery_decorators;
    let _searchQuery_initializers = [];
    let _searchQuery_extraInitializers = [];
    let _pinnedItems_decorators;
    let _pinnedItems_initializers = [];
    let _pinnedItems_extraInitializers = [];
    let _sidebarWidth_decorators;
    let _sidebarWidth_initializers = [];
    let _sidebarWidth_extraInitializers = [];
    let _warning_decorators;
    let _warning_initializers = [];
    let _warning_extraInitializers = [];
    let _wccFrame_decorators;
    let _wccFrame_initializers = [];
    let _wccFrame_extraInitializers = [];
    var WccDashboard = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _sections_decorators = [property()];
            _selectedSection_decorators = [property()];
            _selectedType_decorators = [property()];
            _selectedItemName_decorators = [property()];
            _selectedItem_decorators = [property()];
            _selectedDemoIndex_decorators = [property({ type: Number })];
            _selectedViewport_decorators = [property()];
            _selectedTheme_decorators = [property()];
            _searchQuery_decorators = [property()];
            _pinnedItems_decorators = [property({ attribute: false })];
            _sidebarWidth_decorators = [property({ type: Number })];
            _warning_decorators = [property()];
            _wccFrame_decorators = [queryAsync('wcc-frame')];
            __esDecorate(this, null, _sections_decorators, { kind: "accessor", name: "sections", static: false, private: false, access: { has: obj => "sections" in obj, get: obj => obj.sections, set: (obj, value) => { obj.sections = value; } }, metadata: _metadata }, _sections_initializers, _sections_extraInitializers);
            __esDecorate(this, null, _selectedSection_decorators, { kind: "accessor", name: "selectedSection", static: false, private: false, access: { has: obj => "selectedSection" in obj, get: obj => obj.selectedSection, set: (obj, value) => { obj.selectedSection = value; } }, metadata: _metadata }, _selectedSection_initializers, _selectedSection_extraInitializers);
            __esDecorate(this, null, _selectedType_decorators, { kind: "accessor", name: "selectedType", static: false, private: false, access: { has: obj => "selectedType" in obj, get: obj => obj.selectedType, set: (obj, value) => { obj.selectedType = value; } }, metadata: _metadata }, _selectedType_initializers, _selectedType_extraInitializers);
            __esDecorate(this, null, _selectedItemName_decorators, { kind: "accessor", name: "selectedItemName", static: false, private: false, access: { has: obj => "selectedItemName" in obj, get: obj => obj.selectedItemName, set: (obj, value) => { obj.selectedItemName = value; } }, metadata: _metadata }, _selectedItemName_initializers, _selectedItemName_extraInitializers);
            __esDecorate(this, null, _selectedItem_decorators, { kind: "accessor", name: "selectedItem", static: false, private: false, access: { has: obj => "selectedItem" in obj, get: obj => obj.selectedItem, set: (obj, value) => { obj.selectedItem = value; } }, metadata: _metadata }, _selectedItem_initializers, _selectedItem_extraInitializers);
            __esDecorate(this, null, _selectedDemoIndex_decorators, { kind: "accessor", name: "selectedDemoIndex", static: false, private: false, access: { has: obj => "selectedDemoIndex" in obj, get: obj => obj.selectedDemoIndex, set: (obj, value) => { obj.selectedDemoIndex = value; } }, metadata: _metadata }, _selectedDemoIndex_initializers, _selectedDemoIndex_extraInitializers);
            __esDecorate(this, null, _selectedViewport_decorators, { kind: "accessor", name: "selectedViewport", static: false, private: false, access: { has: obj => "selectedViewport" in obj, get: obj => obj.selectedViewport, set: (obj, value) => { obj.selectedViewport = value; } }, metadata: _metadata }, _selectedViewport_initializers, _selectedViewport_extraInitializers);
            __esDecorate(this, null, _selectedTheme_decorators, { kind: "accessor", name: "selectedTheme", static: false, private: false, access: { has: obj => "selectedTheme" in obj, get: obj => obj.selectedTheme, set: (obj, value) => { obj.selectedTheme = value; } }, metadata: _metadata }, _selectedTheme_initializers, _selectedTheme_extraInitializers);
            __esDecorate(this, null, _searchQuery_decorators, { kind: "accessor", name: "searchQuery", static: false, private: false, access: { has: obj => "searchQuery" in obj, get: obj => obj.searchQuery, set: (obj, value) => { obj.searchQuery = value; } }, metadata: _metadata }, _searchQuery_initializers, _searchQuery_extraInitializers);
            __esDecorate(this, null, _pinnedItems_decorators, { kind: "accessor", name: "pinnedItems", static: false, private: false, access: { has: obj => "pinnedItems" in obj, get: obj => obj.pinnedItems, set: (obj, value) => { obj.pinnedItems = value; } }, metadata: _metadata }, _pinnedItems_initializers, _pinnedItems_extraInitializers);
            __esDecorate(this, null, _sidebarWidth_decorators, { kind: "accessor", name: "sidebarWidth", static: false, private: false, access: { has: obj => "sidebarWidth" in obj, get: obj => obj.sidebarWidth, set: (obj, value) => { obj.sidebarWidth = value; } }, metadata: _metadata }, _sidebarWidth_initializers, _sidebarWidth_extraInitializers);
            __esDecorate(this, null, _warning_decorators, { kind: "accessor", name: "warning", static: false, private: false, access: { has: obj => "warning" in obj, get: obj => obj.warning, set: (obj, value) => { obj.warning = value; } }, metadata: _metadata }, _warning_initializers, _warning_extraInitializers);
            __esDecorate(this, null, _wccFrame_decorators, { kind: "accessor", name: "wccFrame", static: false, private: false, access: { has: obj => "wccFrame" in obj, get: obj => obj.wccFrame, set: (obj, value) => { obj.wccFrame = value; } }, metadata: _metadata }, _wccFrame_initializers, _wccFrame_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            WccDashboard = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
            __runInitializers(_classThis, _classExtraInitializers);
        }
        #sections_accessor_storage = __runInitializers(this, _sections_initializers, []);
        get sections() { return this.#sections_accessor_storage; }
        set sections(value) { this.#sections_accessor_storage = value; }
        #selectedSection_accessor_storage = (__runInitializers(this, _sections_extraInitializers), __runInitializers(this, _selectedSection_initializers, null));
        get selectedSection() { return this.#selectedSection_accessor_storage; }
        set selectedSection(value) { this.#selectedSection_accessor_storage = value; }
        #selectedType_accessor_storage = (__runInitializers(this, _selectedSection_extraInitializers), __runInitializers(this, _selectedType_initializers, 'element'));
        get selectedType() { return this.#selectedType_accessor_storage; }
        set selectedType(value) { this.#selectedType_accessor_storage = value; }
        #selectedItemName_accessor_storage = (__runInitializers(this, _selectedType_extraInitializers), __runInitializers(this, _selectedItemName_initializers, ''));
        get selectedItemName() { return this.#selectedItemName_accessor_storage; }
        set selectedItemName(value) { this.#selectedItemName_accessor_storage = value; }
        #selectedItem_accessor_storage = (__runInitializers(this, _selectedItemName_extraInitializers), __runInitializers(this, _selectedItem_initializers, null));
        get selectedItem() { return this.#selectedItem_accessor_storage; }
        set selectedItem(value) { this.#selectedItem_accessor_storage = value; }
        #selectedDemoIndex_accessor_storage = (__runInitializers(this, _selectedItem_extraInitializers), __runInitializers(this, _selectedDemoIndex_initializers, 0));
        get selectedDemoIndex() { return this.#selectedDemoIndex_accessor_storage; }
        set selectedDemoIndex(value) { this.#selectedDemoIndex_accessor_storage = value; }
        #selectedViewport_accessor_storage = (__runInitializers(this, _selectedDemoIndex_extraInitializers), __runInitializers(this, _selectedViewport_initializers, 'desktop'));
        get selectedViewport() { return this.#selectedViewport_accessor_storage; }
        set selectedViewport(value) { this.#selectedViewport_accessor_storage = value; }
        #selectedTheme_accessor_storage = (__runInitializers(this, _selectedViewport_extraInitializers), __runInitializers(this, _selectedTheme_initializers, 'dark'));
        get selectedTheme() { return this.#selectedTheme_accessor_storage; }
        set selectedTheme(value) { this.#selectedTheme_accessor_storage = value; }
        #searchQuery_accessor_storage = (__runInitializers(this, _selectedTheme_extraInitializers), __runInitializers(this, _searchQuery_initializers, ''));
        get searchQuery() { return this.#searchQuery_accessor_storage; }
        set searchQuery(value) { this.#searchQuery_accessor_storage = value; }
        #pinnedItems_accessor_storage = (__runInitializers(this, _searchQuery_extraInitializers), __runInitializers(this, _pinnedItems_initializers, new Set()));
        // Pinned items as Set of "sectionName::itemName"
        get pinnedItems() { return this.#pinnedItems_accessor_storage; }
        set pinnedItems(value) { this.#pinnedItems_accessor_storage = value; }
        #sidebarWidth_accessor_storage = (__runInitializers(this, _pinnedItems_extraInitializers), __runInitializers(this, _sidebarWidth_initializers, 200));
        // Sidebar width (resizable)
        get sidebarWidth() { return this.#sidebarWidth_accessor_storage; }
        set sidebarWidth(value) { this.#sidebarWidth_accessor_storage = value; }
        // Derived from selectedViewport - no need for separate property
        get isNative() {
            return this.selectedViewport === 'native';
        }
        #warning_accessor_storage = (__runInitializers(this, _sidebarWidth_extraInitializers), __runInitializers(this, _warning_initializers, null));
        get warning() { return this.#warning_accessor_storage; }
        set warning(value) { this.#warning_accessor_storage = value; }
        frameScrollY = (__runInitializers(this, _warning_extraInitializers), 0);
        sidebarScrollY = 0;
        scrollPositionsApplied = false;
        #wccFrame_accessor_storage = __runInitializers(this, _wccFrame_initializers, void 0);
        get wccFrame() { return this.#wccFrame_accessor_storage; }
        set wccFrame(value) { this.#wccFrame_accessor_storage = value; }
        constructor(config) {
            super();
            if (config && config.sections) {
                this.sections = config.sections;
                console.log('got sections:', this.sections.map(s => s.name));
            }
        }
        /**
         * Find an item by name across all sections, returns the item and its section
         */
        findItemByName(name) {
            for (const section of this.sections) {
                const entries = getSectionItems(section);
                const found = entries.find(([itemName]) => itemName === name);
                if (found) {
                    return { item: found[1], section };
                }
            }
            return null;
        }
        /**
         * Find a section by name (URL-decoded)
         */
        findSectionByName(name) {
            return this.sections.find(s => s.name === name) || null;
        }
        render() {
            return html `
      <style>
        :host {
          background: #fcfcfc;
          display: block;
          box-sizing: border-box;
        }
        :host([hidden]) {
          display: none;
        }
      </style>
      <wcc-sidebar
        .dashboardRef=${this}
        .selectedItem=${this.selectedItem}
        .searchQuery=${this.searchQuery}
        .pinnedItems=${this.pinnedItems}
        .sidebarWidth=${this.sidebarWidth}
        .isNative=${this.isNative}
        @selectedType=${(eventArg) => {
                this.selectedType = eventArg.detail;
            }}
        @selectedItemName=${(eventArg) => {
                this.selectedItemName = eventArg.detail;
            }}
        @selectedItem=${(eventArg) => {
                this.selectedItem = eventArg.detail;
            }}
        @searchChanged=${(eventArg) => {
                this.searchQuery = eventArg.detail;
                this.updateUrlWithScrollState();
            }}
        @pinnedChanged=${(eventArg) => {
                this.pinnedItems = eventArg.detail;
                this.updateUrlWithScrollState();
            }}
        @widthChanged=${async (eventArg) => {
                this.sidebarWidth = eventArg.detail;
                this.updateUrlWithScrollState();
                const frame = await this.wccFrame;
                if (frame) {
                    frame.sidebarWidth = eventArg.detail;
                    frame.requestUpdate();
                }
            }}
      ></wcc-sidebar>
      <wcc-properties
        .dashboardRef=${this}
        .warning="${this.warning}"
        .selectedItem=${this.selectedItem}
        .selectedViewport=${this.selectedViewport}
        .selectedTheme=${this.selectedTheme}
        .isNative=${this.isNative}
        .sidebarWidth=${this.sidebarWidth}
        @selectedViewport=${(eventArg) => {
                this.selectedViewport = eventArg.detail;
                this.scheduleUpdate();
            }}
        @selectedTheme=${(eventArg) => {
                this.selectedTheme = eventArg.detail;
            }}
        @editorStateChanged=${async (eventArg) => {
                const frame = await this.wccFrame;
                if (frame) {
                    frame.advancedEditorOpen = eventArg.detail.isOpen;
                    frame.requestUpdate();
                }
            }}
        @toggleNative=${() => {
                this.toggleNative();
            }}
      ></wcc-properties>
      <wcc-frame id="wccFrame" viewport=${this.selectedViewport} .isNative=${this.isNative} .sidebarWidth=${this.sidebarWidth}>
      </wcc-frame>
    `;
        }
        setWarning(warningTextArg) {
            if (this.warning !== warningTextArg) {
                console.log(warningTextArg);
                this.warning = warningTextArg;
                setTimeout(() => {
                    this.scheduleUpdate();
                }, 0);
            }
        }
        toggleNative() {
            // Toggle between 'native' and 'desktop' viewports
            this.selectedViewport = this.selectedViewport === 'native' ? 'desktop' : 'native';
            this.buildUrl();
        }
        async firstUpdated() {
            this.domtools = await plugins.deesDomtools.DomTools.setupDomTools();
            // Add ESC key handler for native mode
            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape' && this.isNative) {
                    this.selectedViewport = 'desktop';
                    this.buildUrl();
                }
            });
            // Set up scroll listeners after DOM is ready
            setTimeout(() => {
                this.setupScrollListeners();
            }, 500);
            // New route format with section name
            this.domtools.router.on('/wcctools-route/:sectionName/:itemName/:demoIndex/:viewport/:theme', async (routeInfo) => {
                const sectionName = decodeURIComponent(routeInfo.params.sectionName);
                this.selectedSection = this.findSectionByName(sectionName);
                this.selectedItemName = routeInfo.params.itemName;
                this.selectedDemoIndex = parseInt(routeInfo.params.demoIndex) || 0;
                this.selectedViewport = routeInfo.params.viewport;
                this.selectedTheme = routeInfo.params.theme;
                if (this.selectedSection) {
                    // Find item within the section
                    const entries = getSectionItems(this.selectedSection);
                    const found = entries.find(([name]) => name === routeInfo.params.itemName);
                    if (found) {
                        this.selectedItem = found[1];
                        this.selectedType = this.selectedSection.type === 'elements' ? 'element' : 'page';
                    }
                }
                else {
                    // Fallback: try legacy format (element/page as section name)
                    const legacyType = routeInfo.params.sectionName;
                    if (legacyType === 'element' || legacyType === 'page') {
                        this.selectedType = legacyType;
                        // Find item in any matching section
                        const result = this.findItemByName(routeInfo.params.itemName);
                        if (result) {
                            this.selectedItem = result.item;
                            this.selectedSection = result.section;
                        }
                    }
                }
                // Restore state from query parameters
                if (routeInfo.queryParams) {
                    const search = routeInfo.queryParams.search;
                    const frameScrollY = routeInfo.queryParams.frameScrollY;
                    const sidebarScrollY = routeInfo.queryParams.sidebarScrollY;
                    const pinned = routeInfo.queryParams.pinned;
                    const sidebarWidth = routeInfo.queryParams.sidebarWidth;
                    if (search) {
                        this.searchQuery = search;
                    }
                    else {
                        this.searchQuery = '';
                    }
                    if (frameScrollY) {
                        this.frameScrollY = parseInt(frameScrollY);
                    }
                    if (sidebarScrollY) {
                        this.sidebarScrollY = parseInt(sidebarScrollY);
                    }
                    if (pinned) {
                        const newPinned = new Set(pinned.split(',').filter(Boolean));
                        // Only update if actually different to avoid update loops
                        if (this.pinnedItems.size !== newPinned.size ||
                            ![...newPinned].every(k => this.pinnedItems.has(k))) {
                            this.pinnedItems = newPinned;
                        }
                    }
                    else if (this.pinnedItems.size > 0) {
                        this.pinnedItems = new Set();
                    }
                    if (sidebarWidth) {
                        this.sidebarWidth = parseInt(sidebarWidth, 10);
                    }
                    // Apply scroll positions and update frame after a short delay to ensure DOM is ready
                    setTimeout(async () => {
                        this.applyScrollPositions();
                        // Ensure frame gets the sidebarWidth
                        const frame = await this.wccFrame;
                        if (frame) {
                            frame.sidebarWidth = this.sidebarWidth;
                            frame.requestUpdate();
                        }
                    }, 100);
                }
                else {
                    this.searchQuery = '';
                    // Only clear if not already empty to avoid update loops
                    if (this.pinnedItems.size > 0) {
                        this.pinnedItems = new Set();
                    }
                }
                const domtoolsInstance = await plugins.deesDomtools.elementBasic.setup();
                this.selectedTheme === 'bright'
                    ? domtoolsInstance.themeManager.goBright()
                    : domtoolsInstance.themeManager.goDark();
            });
            // Legacy route without demo index (for backwards compatibility)
            this.domtools.router.on('/wcctools-route/:sectionName/:itemName/:viewport/:theme', async (routeInfo) => {
                const sectionName = decodeURIComponent(routeInfo.params.sectionName);
                this.selectedSection = this.findSectionByName(sectionName);
                this.selectedItemName = routeInfo.params.itemName;
                this.selectedDemoIndex = 0;
                this.selectedViewport = routeInfo.params.viewport;
                this.selectedTheme = routeInfo.params.theme;
                if (this.selectedSection) {
                    const entries = getSectionItems(this.selectedSection);
                    const found = entries.find(([name]) => name === routeInfo.params.itemName);
                    if (found) {
                        this.selectedItem = found[1];
                        this.selectedType = this.selectedSection.type === 'elements' ? 'element' : 'page';
                    }
                }
                else {
                    // Fallback: try legacy format
                    const legacyType = routeInfo.params.sectionName;
                    if (legacyType === 'element' || legacyType === 'page') {
                        this.selectedType = legacyType;
                        const result = this.findItemByName(routeInfo.params.itemName);
                        if (result) {
                            this.selectedItem = result.item;
                            this.selectedSection = result.section;
                        }
                    }
                }
                // Restore state from query parameters
                if (routeInfo.queryParams) {
                    const search = routeInfo.queryParams.search;
                    const frameScrollY = routeInfo.queryParams.frameScrollY;
                    const sidebarScrollY = routeInfo.queryParams.sidebarScrollY;
                    const pinned = routeInfo.queryParams.pinned;
                    const sidebarWidth = routeInfo.queryParams.sidebarWidth;
                    if (search) {
                        this.searchQuery = search;
                    }
                    else {
                        this.searchQuery = '';
                    }
                    if (frameScrollY) {
                        this.frameScrollY = parseInt(frameScrollY);
                    }
                    if (sidebarScrollY) {
                        this.sidebarScrollY = parseInt(sidebarScrollY);
                    }
                    if (pinned) {
                        const newPinned = new Set(pinned.split(',').filter(Boolean));
                        // Only update if actually different to avoid update loops
                        if (this.pinnedItems.size !== newPinned.size ||
                            ![...newPinned].every(k => this.pinnedItems.has(k))) {
                            this.pinnedItems = newPinned;
                        }
                    }
                    else if (this.pinnedItems.size > 0) {
                        this.pinnedItems = new Set();
                    }
                    if (sidebarWidth) {
                        this.sidebarWidth = parseInt(sidebarWidth, 10);
                    }
                    // Apply scroll positions after a short delay to ensure DOM is ready
                    setTimeout(() => {
                        this.applyScrollPositions();
                    }, 100);
                }
                else {
                    this.searchQuery = '';
                    // Only clear if not already empty to avoid update loops
                    if (this.pinnedItems.size > 0) {
                        this.pinnedItems = new Set();
                    }
                }
                const domtoolsInstance = await plugins.deesDomtools.elementBasic.setup();
                this.selectedTheme === 'bright'
                    ? domtoolsInstance.themeManager.goBright()
                    : domtoolsInstance.themeManager.goDark();
            });
        }
        async updated(changedPropertiesArg) {
            this.domtools = await plugins.deesDomtools.DomTools.setupDomTools();
            await this.domtools.router._handleRouteState();
            const wccFrame = this.shadowRoot.querySelector('wcc-frame');
            if (changedPropertiesArg.has('selectedItemName')) {
                document.title = this.selectedItemName;
            }
            ;
            if (this.selectedType === 'page' && this.selectedItem) {
                if (typeof this.selectedItem === 'function') {
                    console.log('slotting page.');
                    const viewport = await wccFrame.getViewportElement();
                    const pageFactory = this.selectedItem;
                    const pageTemplate = await resolveTemplateFactory(pageFactory);
                    render(pageTemplate, viewport);
                    console.log('rendered page.');
                }
                else {
                    console.error('The selected item looks strange:');
                    console.log(this.selectedItem);
                }
            }
            else if (this.selectedType === 'element' && this.selectedItem) {
                console.log('slotting element.');
                const anonItem = this.selectedItem;
                if (!anonItem.demo) {
                    this.setWarning(`component ${anonItem.name} does not expose a demo property.`);
                    return;
                }
                // Support both single demo (function) and multiple demos (array)
                const isArray = Array.isArray(anonItem.demo);
                const isFunction = typeof anonItem.demo === 'function';
                if (!isArray && !isFunction) {
                    this.setWarning(`component ${anonItem.name} has demo property, but it is not a function or array of functions`);
                    return;
                }
                // Get the specific demo to render
                const demoFactory = getDemoAtIndex(anonItem.demo, this.selectedDemoIndex);
                if (!demoFactory) {
                    this.setWarning(`component ${anonItem.name} does not have a demo at index ${this.selectedDemoIndex + 1}`);
                    return;
                }
                this.setWarning(null);
                const viewport = await wccFrame.getViewportElement();
                const demoTemplate = await resolveTemplateFactory(demoFactory);
                render(demoTemplate, viewport);
            }
        }
        buildUrl() {
            const sectionName = this.selectedSection
                ? encodeURIComponent(this.selectedSection.name)
                : this.selectedType; // Fallback for legacy
            const baseUrl = `/wcctools-route/${sectionName}/${this.selectedItemName}/${this.selectedDemoIndex}/${this.selectedViewport}/${this.selectedTheme}`;
            const queryParams = new URLSearchParams();
            if (this.searchQuery) {
                queryParams.set('search', this.searchQuery);
            }
            if (this.frameScrollY > 0) {
                queryParams.set('frameScrollY', this.frameScrollY.toString());
            }
            if (this.sidebarScrollY > 0) {
                queryParams.set('sidebarScrollY', this.sidebarScrollY.toString());
            }
            if (this.pinnedItems.size > 0) {
                queryParams.set('pinned', Array.from(this.pinnedItems).join(','));
            }
            if (this.sidebarWidth !== 200) {
                queryParams.set('sidebarWidth', this.sidebarWidth.toString());
            }
            const queryString = queryParams.toString();
            const fullUrl = queryString ? `${baseUrl}?${queryString}` : baseUrl;
            this.domtools.router.pushUrl(fullUrl);
        }
        scrollUpdateTimeout = __runInitializers(this, _wccFrame_extraInitializers);
        scrollListenersAttached = false;
        async setupScrollListeners() {
            // Prevent duplicate listeners
            if (this.scrollListenersAttached) {
                return;
            }
            const wccFrame = await this.wccFrame;
            const wccSidebar = this.shadowRoot.querySelector('wcc-sidebar');
            if (wccFrame) {
                // The frame element itself is the scrollable container
                wccFrame.addEventListener('scroll', () => {
                    this.frameScrollY = wccFrame.scrollTop;
                    this.debouncedScrollUpdate();
                });
                this.scrollListenersAttached = true;
            }
            if (wccSidebar) {
                // Use the sidebar's scrollable container (.menu element)
                const scrollContainer = wccSidebar.scrollableContainer;
                if (scrollContainer) {
                    scrollContainer.addEventListener('scroll', () => {
                        this.sidebarScrollY = scrollContainer.scrollTop;
                        this.debouncedScrollUpdate();
                    });
                }
            }
        }
        debouncedScrollUpdate() {
            clearTimeout(this.scrollUpdateTimeout);
            this.scrollUpdateTimeout = setTimeout(() => {
                this.updateUrlWithScrollState();
            }, 300);
        }
        updateUrlWithScrollState() {
            const sectionName = this.selectedSection
                ? encodeURIComponent(this.selectedSection.name)
                : this.selectedType; // Fallback for legacy
            const baseUrl = `/wcctools-route/${sectionName}/${this.selectedItemName}/${this.selectedDemoIndex}/${this.selectedViewport}/${this.selectedTheme}`;
            const queryParams = new URLSearchParams();
            if (this.searchQuery) {
                queryParams.set('search', this.searchQuery);
            }
            if (this.frameScrollY > 0) {
                queryParams.set('frameScrollY', this.frameScrollY.toString());
            }
            if (this.sidebarScrollY > 0) {
                queryParams.set('sidebarScrollY', this.sidebarScrollY.toString());
            }
            if (this.pinnedItems.size > 0) {
                queryParams.set('pinned', Array.from(this.pinnedItems).join(','));
            }
            if (this.sidebarWidth !== 200) {
                queryParams.set('sidebarWidth', this.sidebarWidth.toString());
            }
            const queryString = queryParams.toString();
            const fullUrl = queryString ? `${baseUrl}?${queryString}` : baseUrl;
            // Use replaceState to update URL without navigation
            window.history.replaceState(null, '', fullUrl);
        }
        async applyScrollPositions() {
            // Only apply scroll positions once to avoid interfering with user scrolling
            if (this.scrollPositionsApplied) {
                return;
            }
            const wccFrame = await this.wccFrame;
            const wccSidebar = this.shadowRoot.querySelector('wcc-sidebar');
            if (wccFrame && this.frameScrollY > 0) {
                // The frame element itself is the scrollable container
                wccFrame.scrollTop = this.frameScrollY;
            }
            if (wccSidebar && this.sidebarScrollY > 0) {
                // Use the sidebar's scrollable container (.menu element)
                const scrollContainer = wccSidebar.scrollableContainer;
                if (scrollContainer) {
                    scrollContainer.scrollTop = this.sidebarScrollY;
                }
            }
            this.scrollPositionsApplied = true;
        }
    };
    return WccDashboard = _classThis;
})();
export { WccDashboard };
//# sourceMappingURL=data:application/json;base64, 