import { HeadingTag } from "../../../globals/HeadingTag";
import { Host, h, Fragment } from "@stencil/core";
import { ScreenWidth, DEFAULT_BREAKPOINTS } from "../../../globals/ScreensizeDetect";
import { angle_down, angle_up } from "pn-design-assets/pn-assets/icons.js";
import { PnChatService } from "../pn-chat/pn-chat.service";
import { translations } from "./translations";
import { MarketwebTableService } from "./pn-marketweb-table.service";
export class PnMarketWebTable {
    constructor() {
        this.mainHeading = undefined;
        this.mainHeadingLevel = 'h2';
        this.preamble = undefined;
        this.subHeadingLevel = 'h3';
        this.headers = undefined;
        this.rows = undefined;
        this.showHeadersInCells = false;
        this.cellHeaderLevel = 'h3';
        this.tableRowCtaActionLabel = undefined;
        this.imageColAriaHeader = undefined;
        this.ctaColAriaHeader = undefined;
        this.checkForNewShipments = false;
        this.endpoint = undefined;
        this.language = 'sv';
        this.market = undefined;
        this.toggleDetailLabel = 'View details';
        this.checkForChat = false;
        this.value = '';
        this.shipmentType = undefined;
        this.contentId = '';
        this.takeAmountRow = 2;
        this.shipmentCount = 2;
        this.i18n = undefined;
        this._headers = [];
        this._rows = [];
        this._allKeys = new Set();
        this.screenInfo = undefined;
    }
    screenWidth = ScreenWidth.getInstance();
    cleanup;
    _chatService;
    _chatSegment = "#chat";
    _marketwebTableService;
    componentWillLoad() {
        this.setInitialValues();
        this.setTranslations();
        this._marketwebTableService = new MarketwebTableService(this.endpoint, this.language);
        this.cleanup = this.screenWidth.subscribe(info => {
            this.screenInfo = info;
        });
        if (this.checkForNewShipments) {
            this._chatService = new PnChatService(this.endpoint, this.market, this.language);
            setInterval(() => {
                this.checkForNewMessages();
            }, 60000);
        }
    }
    setTranslations() {
        if (translations[this.language]) {
            this.i18n = translations[this.language];
        }
        else {
            const fallbackLang = 'sv';
            this.i18n = translations[fallbackLang];
        }
    }
    onLanguageChange() {
        this.setTranslations();
    }
    async componentDidLoad() {
        if (this.checkForChat) {
            const thisTable = document.querySelector('pn-marketweb-table.' + this.shipmentType);
            const chatHrefs = thisTable.querySelectorAll('[href*="#chat"]');
            const openChatATags = Array.from(chatHrefs).filter((el) => el instanceof HTMLAnchorElement);
            this.OpenChatEvent(openChatATags);
        }
    }
    componentDidRender() {
        const thisTable = document.querySelector('pn-marketweb-table[shipment-type=' + this.shipmentType + ']');
        const toggleButtons = thisTable?.querySelectorAll('pn-button.toggle-widget');
        toggleButtons?.forEach(pnButton => {
            const btnText = pnButton.querySelector('.pn-button-text');
            if (btnText && btnText.innerHTML !== this.i18n.toggleButtonOn) {
                btnText.innerHTML = this.i18n.toggleButtonOn;
            }
            const button = pnButton.querySelector('button');
            if (button && !button.hasAttribute('data-toggle-initialized')) {
                button.addEventListener('click', this.toggleButton.bind(this));
                button.setAttribute('data-toggle-initialized', 'true');
            }
        });
    }
    toggleButton(event) {
        const button = event.currentTarget;
        const parentRow = button.closest('tr');
        const parentPnButton = button.closest('pn-button');
        const isActive = parentRow.classList.contains("shipment-id-active");
        const existingWidgetRows = document.querySelectorAll('.widget-row');
        existingWidgetRows.forEach(row => row.remove());
        const allRows = document.querySelectorAll('tr');
        allRows.forEach(row => row.classList.remove("shipment-id-active"));
        const allPnButtons = document.querySelectorAll('pn-button.toggle-widget');
        allPnButtons.forEach(pnBtn => {
            pnBtn.setAttribute('icon', angle_down);
            pnBtn.querySelector('.pn-button-text').innerHTML = this.i18n.toggleButtonOn;
        });
        if (isActive) {
            return;
        }
        button.querySelector('.pn-button-text').innerHTML = this.i18n.toggleButtonOff;
        parentRow.classList.add("shipment-id-active");
        const widgetRow = document.createElement('tr');
        widgetRow.classList.add('widget-row');
        const tdElement = document.createElement('td');
        tdElement.colSpan = parentRow.children.length;
        const divEl = document.createElement('div');
        divEl.classList.add('pn-widget-wrapper');
        const widget = document.createElement('pn-widget');
        widget.setAttribute('locale', this.language);
        widget.setAttribute('shipment-id', button.id);
        divEl.appendChild(widget);
        tdElement.appendChild(divEl);
        widgetRow.appendChild(tdElement);
        parentRow.parentNode.insertBefore(widgetRow, parentRow.nextSibling);
        parentPnButton.setAttribute('icon', angle_up);
    }
    handleShowMore = async () => {
        let skip = this._rows.length;
        let data = await this._marketwebTableService.getUserShipments(this.contentId, skip, this.takeAmountRow, this.checkForChat);
        if (data) {
            this._rows = [...this._rows, ...data];
        }
    };
    async waitForComponent(selector, maxRetries = 10, delay = 300) {
        for (let i = 0; i < maxRetries; i++) {
            const element = document.querySelector(selector);
            if (element) {
                return element;
            }
            await new Promise(resolve => setTimeout(resolve, delay));
        }
        return null;
    }
    disconnectedCallback() {
        if (this.cleanup) {
            this.cleanup();
        }
    }
    async checkForNewMessages() {
        for (let i = 0; i < this._rows.length; i++) {
            const row = this._rows[i];
            const itemId = row.id;
            if (itemId) {
                const hasNewMessages = await this._chatService.hasNewMessages(itemId);
                if (row.hasNewMessages !== hasNewMessages) {
                    this._rows[i] = { ...row, hasNewMessages: hasNewMessages };
                }
            }
        }
        this._rows = [...this._rows];
    }
    setInitialValues() {
        try {
            this.parseRows();
            this.parseHeaders();
        }
        catch (error) {
            console.error('Error parsing table data:', error);
            this._rows = [];
            this._headers = [];
        }
    }
    parseRows() {
        this._rows = typeof this.rows === 'string' ? JSON.parse(this.rows) : this.rows;
        this._allKeys = new Set(this._rows.flatMap(row => Object.keys(row)));
    }
    parseHeaders() {
        if (typeof this.headers === 'string') {
            this._headers = JSON.parse(this.headers);
        }
        else if (this.headers) {
            this._headers = this.headers;
        }
        else {
            this._headers = Array.from(this._allKeys).map(key => ({ key, label: key }));
        }
    }
    renderCellContent(header, row) {
        const content = header.render ? header.render(row) : row[header.key] ?? '-';
        return content;
    }
    renderCell(header, row) {
        const content = this.renderCellContent(header, row);
        if (this.showHeadersInCells || this.screenInfo.width <= DEFAULT_BREAKPOINTS.tablet) {
            return (h("div", { class: "cell-content", role: "cell" }, h(HeadingTag, { level: this.cellHeaderLevel, cssClass: "cell-heading", additionalProps: {
                    'aria-hidden': 'true',
                    'role': 'presentation',
                } }, header.label), h("span", { class: "cell-value" }, content)));
        }
        return h(Fragment, null, content);
    }
    handleToggleClick = () => {
        const areaToggle = document.querySelector('.trackandtracewidgetblock');
        if (areaToggle?.parentElement) {
            areaToggle.parentElement.classList.toggle('hideRow');
        }
    };
    renderActionButtons(row) {
        if (!row.actionButtons)
            return null;
        return (h("td", { class: "actions", role: "cell" }, h("div", { class: "button-wrapper", role: "group", "aria-label": this.tableRowCtaActionLabel, "data-label": this.i18n.newMessage }, row.actionButtons.map(btn => (h("pn-button", { appearance: btn.appearance, class: btn.class, variant: btn.variant, small: btn.small, loading: btn.loading, icon: btn.icon, leftIcon: btn.leftIcon, tooltip: btn.tooltip, href: btn.href, rel: btn.rel, download: btn.download, form: btn.form, buttonId: btn.buttonId, "icon-only": btn.iconOnly, arialabel: btn.content, "data-chat": btn.customAttribute }, btn.content))))));
    }
    async OpenChatEvent(aTags) {
        aTags.forEach((aTag) => {
            aTag.addEventListener("click", (e) => {
                e.preventDefault();
                const previousLocationHash = window?.location?.hash ?? "";
                const findShipmentIdInUrlRegex = /#chat:([a-zA-Z0-9]+)(?=#|$)/;
                const match = aTag.href.match(findShipmentIdInUrlRegex);
                const shipmentId = match ? match[1] : "";
                const shipmentHash = `${this._chatSegment}:${shipmentId}`;
                window.location.hash = shipmentHash;
                this.waitForComponent('pn-chat').then((chat) => {
                    if (shipmentId) {
                        chat.setAttribute('item-id', shipmentId);
                    }
                    else {
                        chat.setAttribute('item-id', "");
                    }
                    let oldInitChatId = chat.getAttribute('pn-chat-id');
                    const _defaultChatId = "00000000-0000-0000-0000-000000000000";
                    const _defaultAlternativeChatId = "1";
                    const _defaultTriggerChatId = oldInitChatId === _defaultChatId ? _defaultAlternativeChatId : _defaultChatId;
                    let chatId = _defaultTriggerChatId;
                    const reversedChatId = aTag?.parentElement?.getAttribute('data-chat');
                    if (reversedChatId) {
                        chatId = reversedChatId.split('').reverse().join('');
                    }
                    chat.setAttribute('is-logged-in', 'true');
                    chat.setAttribute('pn-chat-id', chatId);
                    if (previousLocationHash.includes(shipmentHash)) {
                        let forceOpen = chat.getAttribute('force-open') ?? 'true';
                        forceOpen = forceOpen === 'true' ? 'false' : 'true';
                        chat.setAttribute('force-open', forceOpen);
                    }
                });
            });
        });
    }
    render() {
        const tableId = `table-${Math.random().toString(36)}`;
        const headingId = `${tableId}-main-heading`;
        return (h(Host, { key: '950fd9ad38ecc50412dfb2df76f688974bf64ddf', language: this.language }, h("div", { key: '7b3f92c37b733086cbb7e856afaf29a8b8e6f5e7', class: 'pn-marketweb-table' }, h("div", { key: '30fbecba91a38f48ed4e73f8b830ea761b15be23', role: 'region', "aria-labelledby": this.mainHeading ? headingId : undefined }, h("div", { key: '54e70278aa15e18917d9f14655dd79deb3c7ed7b', class: 'heading-section' }, h("div", { key: 'b1c4067f96442c00a1a95cef60b9e0bd77805506', class: 'heading-wrapper' }, this.mainHeading && (h(HeadingTag, { key: '9b6e742f06dfdc830702489248fdff87e8795217', level: this.mainHeadingLevel, cssClass: 'main-heading', id: headingId }, this.mainHeading)), this.preamble && (h("div", { key: 'cb94134690458850ee2e79a79cec5a9c7d11d0aa', class: "preamble-section" }, this.preamble)))), this._rows.length > 0 && (h("table", { key: '72714b2a74f4de7bbf35db41f2eca9c7223acc6d', class: 'pn-marketweb-table__table', "aria-labelledby": this.mainHeading ? `${tableId}-main-heading` : undefined }, this._headers && (h("thead", { key: '228695887f5852747c699ece16fe33d5c3586f8a', class: this.showHeadersInCells ? 'sr-only' : undefined }, h("tr", { key: 'a63ca166aacc8632b17a1b8ff65407290e843246' }, this._rows.some((row) => row.imageUrl) && this.imageColAriaHeader && (h("th", { key: '9c10a0a04134e63653816a5bf5f0e102d917bada', scope: 'col', class: 'sr-only' }, this.imageColAriaHeader)), this._headers.map((header) => (h("th", { key: header.key, scope: 'col', class: 'sr-only-mobile' }, header.label))), this._rows.some((row) => row.link1 || row.link2) && this.ctaColAriaHeader && (h("th", { key: '77678ed9f13b256f031c1485da24d2524e2eafeb', scope: 'col', class: 'sr-only' }, this.ctaColAriaHeader))))), h("tbody", { key: 'ee6bc0563ea7220c433b34b9c86e9ece61a7e765', class: "pn-marketweb-table__table-body" }, this._rows.slice(0, this.shipmentCount).map((row, rowIndex) => (h("tr", { key: rowIndex, class: `cell-row ${row.hasNewMessages ? "row-new-message" : ''}` }, row.imageUrl && (h("td", { class: 'cell-image' }, h("div", { class: 'image-container' }, h("img", { src: row.imageUrl, alt: '', class: 'row-image' })))), this._headers.map((header) => (h("td", { key: `${rowIndex}-${header.key}`, class: 'cell-content' }, this.renderCell(header, row)))), this.renderActionButtons(row))))))), this.shipmentCount > this._rows.length && (h("div", { key: 'f67de7b07bc7641337dbe12275d70ae7bf6c95a2', class: "pn-market-table__show-more-wrapper" }, h("pn-button", { key: 'e4db3a7b5cf499afb6a064621d003cb305555090', variant: "outlined", appearance: "light", label: this.i18n?.showMoreLabel || 'Show More', onClick: () => this.handleShowMore() })))))));
    }
    static get is() { return "pn-marketweb-table"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-marketweb-table.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-marketweb-table.css"]
        };
    }
    static get properties() {
        return {
            "mainHeading": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "main-heading",
                "reflect": false
            },
            "mainHeadingLevel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "HeadingLevel",
                    "resolved": "\"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\"",
                    "references": {
                        "HeadingLevel": {
                            "location": "import",
                            "path": "@/globals/types",
                            "id": "src/globals/types.ts::HeadingLevel"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "main-heading-level",
                "reflect": false,
                "defaultValue": "'h2'"
            },
            "preamble": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "preamble",
                "reflect": false
            },
            "subHeadingLevel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "HeadingLevel",
                    "resolved": "\"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\"",
                    "references": {
                        "HeadingLevel": {
                            "location": "import",
                            "path": "@/globals/types",
                            "id": "src/globals/types.ts::HeadingLevel"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "sub-heading-level",
                "reflect": false,
                "defaultValue": "'h3'"
            },
            "headers": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | HeaderConfig[]",
                    "resolved": "HeaderConfig[] | string",
                    "references": {
                        "HeaderConfig": {
                            "location": "import",
                            "path": "./types",
                            "id": "src/components/widgets/pn-marketweb-table/types.ts::HeaderConfig"
                        }
                    }
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "headers",
                "reflect": false
            },
            "rows": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | TableRowData[]",
                    "resolved": "TableRowData[] | string",
                    "references": {
                        "TableRowData": {
                            "location": "import",
                            "path": "./types",
                            "id": "src/components/widgets/pn-marketweb-table/types.ts::TableRowData"
                        }
                    }
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "rows",
                "reflect": false
            },
            "showHeadersInCells": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "show-headers-in-cells",
                "reflect": false,
                "defaultValue": "false"
            },
            "cellHeaderLevel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "HeadingLevel",
                    "resolved": "\"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\"",
                    "references": {
                        "HeadingLevel": {
                            "location": "import",
                            "path": "@/globals/types",
                            "id": "src/globals/types.ts::HeadingLevel"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "cell-header-level",
                "reflect": false,
                "defaultValue": "'h3'"
            },
            "tableRowCtaActionLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "table-row-cta-action-label",
                "reflect": false
            },
            "imageColAriaHeader": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "image-col-aria-header",
                "reflect": false
            },
            "ctaColAriaHeader": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "cta-col-aria-header",
                "reflect": false
            },
            "checkForNewShipments": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "check-for-new-shipments",
                "reflect": false,
                "defaultValue": "false"
            },
            "endpoint": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "endpoint",
                "reflect": false
            },
            "language": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "language",
                "reflect": false,
                "defaultValue": "'sv'"
            },
            "market": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "market",
                "reflect": false
            },
            "toggleDetailLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "toggle-detail-label",
                "reflect": false,
                "defaultValue": "'View details'"
            },
            "checkForChat": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "check-for-chat",
                "reflect": false,
                "defaultValue": "false"
            },
            "value": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "value",
                "reflect": true,
                "defaultValue": "''"
            },
            "shipmentType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "shipment-type",
                "reflect": false
            },
            "contentId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "content-id",
                "reflect": false,
                "defaultValue": "''"
            },
            "takeAmountRow": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "take-amount-row",
                "reflect": false,
                "defaultValue": "2"
            },
            "shipmentCount": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "shipment-count",
                "reflect": false,
                "defaultValue": "2"
            }
        };
    }
    static get states() {
        return {
            "i18n": {},
            "_headers": {},
            "_rows": {},
            "_allKeys": {},
            "screenInfo": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "onLanguageChange"
            }];
    }
}
//# sourceMappingURL=pn-marketweb-table.js.map
