import { h } from "@stencil/core";
export class DgaTableOfContent {
    constructor() {
        this.sections = [];
        this.subTitle = 'sub';
        this.title = 'main';
        this.activeSectionId = '';
        this.tabRefs = new Map();
        this.handleScroll = () => {
            const scrollPosition = window.scrollY || window.pageYOffset;
            const scrollTop = window.scrollY || window.pageYOffset;
            //  console.log(scrollPosition , this.sections , "scrollPosition")
            const positions = {};
            const defineTargetsPositions = (sections) => {
                sections.forEach(section => {
                    const element = document.getElementById(section.Target);
                    if (element) {
                        const rect = element.getBoundingClientRect();
                        const elementTop = rect.top + scrollPosition;
                        positions[section.Target] = elementTop;
                        if (section.Children && section.Children.length > 0) {
                            defineTargetsPositions(section.Children);
                        }
                        // this.titles[section.title] = elementTop
                    }
                });
            };
            defineTargetsPositions(this.sections);
            // this.sections.forEach(section => {
            //   const element = document.getElementById(section.Target);
            //   if (element) {
            //     const rect = element.getBoundingClientRect();
            //     const elementTop = rect.top + scrollPosition; 
            //     positions[section.Target] = elementTop
            //     if(section.Children && section.Children.length > 0) {
            //     }
            //     // this.titles[section.title] = elementTop
            //   }
            // });
            const scrollRanges = this.convertToScrollRanges(positions);
            for (const { title, range } of scrollRanges) {
                const [start, end] = range;
                console.log(start, end, scrollTop, "start , end");
                if (scrollTop >= start && scrollTop < end) {
                    this.activeSectionId = title;
                    console.log(title, "title is set");
                }
            }
            // console.log(positions , scrollRanges , "positions")
            // const activeDivId = this.getActiveDivId();
            // if (activeDivId !== this.activeSectionId) {
            //   this.activeSectionId = activeDivId || '';
            // }
        };
    }
    componentWillLoad() {
        window.addEventListener('scroll', this.handleScroll);
    }
    disconnectedCallback() {
        window.removeEventListener('scroll', this.handleScroll);
    }
    // private defineTargetsPositions() {
    // }
    convertToScrollRanges(positions) {
        const titles = Object.keys(positions).sort((a, b) => positions[a] - positions[b]);
        const scrollRanges = [];
        for (let i = 0; i < titles.length - 1; i++) {
            const title = titles[i];
            const nextTitle = titles[i + 1];
            if (i == 0) {
            }
            // const range = i === 0 ? [0 , positions[nextTitle]] : [positions[title], positions[nextTitle]];
            const range = [positions[title], positions[nextTitle]];
            scrollRanges.push({ title, range });
        }
        // Handle the last title's range to Infinity
        const lastTitle = titles[titles.length - 1];
        const lastRange = [positions[lastTitle], Infinity];
        scrollRanges.push({ title: lastTitle, range: lastRange });
        return scrollRanges;
    }
    moveTOSelectedId(id) {
        try {
            const targetElement = document.getElementById(id);
            targetElement === null || targetElement === void 0 ? void 0 : targetElement.scrollIntoView({ behavior: 'smooth' });
        }
        catch (error) {
            console.error('Error moving to selected ID:', error);
        }
    }
    // private getActiveDivId() {
    //   const divs = document.querySelectorAll('div[id]');
    //   // @ts-ignore
    //   for (const div of divs) {
    //     const rect = div.getBoundingClientRect();
    //     const isInViewport =
    //       rect.top >= 0 &&
    //       rect.left >= 0 &&
    //       rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    //       rect.right <= (window.innerWidth || document.documentElement.clientWidth);
    //     if (isInViewport) {
    //       return div.id;
    //     }
    //   }
    //   return null;
    // }
    handleAddPressed(tabId) {
        const tabElement = this.tabRefs.get(tabId);
        tabElement === null || tabElement === void 0 ? void 0 : tabElement.classList.add('pressed');
    }
    handleRemovePressed(tabId) {
        const tabElement = this.tabRefs.get(tabId);
        tabElement === null || tabElement === void 0 ? void 0 : tabElement.classList.remove('pressed');
    }
    renderTab(tab) {
        return (h("li", null, h("a", { ref: el => el && this.tabRefs.set(tab.Target, el), onClick: () => this.moveTOSelectedId(tab.Target), onMouseDown: () => this.handleAddPressed(tab.Target), onMouseUp: () => this.handleRemovePressed(tab.Target), onMouseOut: () => this.handleRemovePressed(tab.Target), class: `table-of-content__tab ${this.activeSectionId === tab.Target ? 'active' : ''}` }, h("span", { class: "table-of-content__tab-label" }, tab.Name))));
    }
    renderSubTabs(subTab) {
        var _a;
        return (h("ul", { class: "table-of-content__tab-sublist" }, this.renderTab(subTab), (_a = subTab.Children) === null || _a === void 0 ? void 0 :
            _a.map(subSubTab => h("ul", { class: "table-of-content__tab-sub-sublist" }, this.renderTab(subSubTab)))));
    }
    render() {
        return (h("aside", { key: '6d206c83b27e05d1513e0c523808197bbf0c852a', class: "table-of-content" }, h("div", { key: '9fd1ba720475cd33e895fe9589ce2eda9f0ef8e9', class: "table-of-content__header" }, h("p", { key: '4295e541cd8dbb6061ead634e1fa3d0f8fb7eb9b', class: "text-sm-regular" }, this.subTitle), h("h4", { key: '945f888715ddb5f1dc3075663c33d31b9ccf5dc4', class: "text-xl-semibold" }, this.title)), h("div", { key: 'b56e86d0f64dd5e758ebf6b5778ac38671d56183', class: "table-of-content__body" }, h("ul", { key: '60f637f053fb2d2b248ed259f7781a3d7308f1a1', class: "table-of-content__tab-list" }, this.sections.map(tab => tab.Children ? (h("div", null, this.renderTab(tab), tab.Children.map(subTab => this.renderSubTabs(subTab)))) : (this.renderTab(tab)))))));
    }
    static get is() { return "dga-table-of-content"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["dga-table-of-content.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["dga-table-of-content.css"]
        };
    }
    static get properties() {
        return {
            "sections": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "TabType[]",
                    "resolved": "TabType[]",
                    "references": {
                        "TabType": {
                            "location": "local",
                            "path": "/home/mamoud/Documents/temp/components/platform-code-cross-platform-storybook/packages/core/src/components/dga-table-of-content/dga-table-of-content.tsx",
                            "id": "src/components/dga-table-of-content/dga-table-of-content.tsx::TabType"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "subTitle": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "attribute": "sub-title",
                "reflect": false,
                "defaultValue": "'sub'"
            },
            "title": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "attribute": "title",
                "reflect": false,
                "defaultValue": "'main'"
            }
        };
    }
    static get states() {
        return {
            "activeSectionId": {}
        };
    }
}
//# sourceMappingURL=dga-table-of-content.js.map
