const styles = `
/* Postology Styles */

/* Main Container */
#postology-box {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: nowrap;
    width: 100%;
    box-sizing: border-box;
    padding: 9px 12px;
    overflow: hidden;
    margin-block-end: 30px;
    font-family: "Plus Jakarta Sans", serif;

    /* Header Text */
    .postology-header {
        flex-grow: 1;
        overflow: hidden;
        display: flex;
        align-items: center;
    }

    p {
        margin-block: auto;
        font-weight: 600;
    }

    /* Generate Summary Button */
    #generate-summary {
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        padding: 6px 20px;
        transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
        white-space: nowrap;

        &:disabled {
            /* background-color: #9c9c9c; */
            cursor: not-allowed;
            transform: translateY(0px);
        }
        &:hover {
            transform: translateY(-2px);
        }
    }
}


/* Icon */
.icon {
    margin-right: 8px;
    width: 30px;
}



/* Summary Content */

.nav-tab-disabled {
    color: #a0a5aa;
    cursor: not-allowed;
    text-decoration: none;

    &:hover {
        color: #a0a5aa;
    }
}

/* Summary Container */
#summary-content {
    display: none;
    width: 100%;
    box-sizing: border-box;
    padding: 16px 16px 12px 16px;
    font-family: "Plus Jakarta Sans", serif;
    margin-block-end: 30px;

    /* Summary Title */
    #summary-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 15px;

        p {
            margin: 0;
        }
    }

    #summary-content-placeholder {
        background-color: #a3a3a3;
        border-radius: 9px;
        padding: 18px;

        ul {
            list-style-type: disc;
            padding-left: 20px;
            margin: 0;
            
            li {
                margin-bottom: 12px;
            }
        }
    }

    /* "Powered by Postology" Text */
    .postology-powered-by {
        font-size: 12px;
        color: #888888;
        text-align: right;
        margin-top: 12px;
    }
}

/* Loading Placeholder */
#loading-placeholder {
    display: none;
    padding: 20px;
    background-color: #fff;
}

/* Loading Lines */
.loading-line {
    height: 10px;
    background: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
    background-size: 200% 100%;
    margin-bottom: 10px;
    border-radius: 6px;
    animation: shimmer 1.5s infinite linear;
}

/* Mobile Styling */
@media (max-width: 768px) {
    #postology-box {
        flex-direction: column;
        align-items: flex-start;
    }

    .postology-header {
        margin-bottom: 10px;
    }

    #generate-summary {
        width: 100%;
        margin-bottom: 10px;
    }
}

/* Animation Keyframes */
@keyframes shimmer {
    0% {
        background-position: -200% 0;
    }
    100% {
        background-position: 200% 0;
    }
}

`;
/*  assets/js/postology-box.js  */
class PostologyBox extends HTMLElement {

    /* ——————————————————————————————————— */
    /*  1.  Life‑cycle hook                  */
    /* ——————————————————————————————————— */
    connectedCallback() {
        /* Guard against double init */
        if (this.shadowRoot) return;

        /* Create shadow DOM and move markup inside it */
        const shadow = this.attachShadow({ mode: 'open' });
        const style = document.createElement('style');
        style.textContent = styles;
        shadow.append(style);

        const tpl = document.createElement('template');
        tpl.innerHTML = this.innerHTML;          // everything PHP printed
        shadow.appendChild(tpl.content.cloneNode(true));
        this.innerHTML = '';                      // empty light‑DOM

        /* Cache frequently‑used nodes */
        this.$btn = shadow.querySelector('#generate-summary');
        this.$summary = shadow.querySelector('#summary-content');
        this.$loading = shadow.querySelector('#loading-placeholder');
        this.$title = shadow.querySelector('#summary-title');
        this.$placeholder = shadow.querySelector('#summary-content-placeholder');
        this.$poweredBy = shadow.querySelector('.postology-powered-by');
        this.$boxWrapper = shadow.querySelector('#postology-box');

        /* Initial “ready” state (mirrors the old $(document).ready) */
        if (this.$btn) this.$btn.style.display = '';      // show
        if (this.$summary) this.$summary.style.display = 'none';  // hide
        if (this.$poweredBy) this.$poweredBy.style.display = 'none'; // hide

        /* Hook up click */
        this.$btn?.addEventListener('click', () => this.requestSummary());
    }

    /* ——————————————————————————————————— */
    /*  2.  Helper: collect article text     */
    /* ——————————————————————————————————— */
    getArticleContent() {
        if (typeof postologySettings === 'undefined') return null;

        const defaults = postologySettings.selectors || '.article-content';
        const findElements = postologySettings.find_elements || 'p, h2, h3, h4, h5, h6';
        const excludedClasses = postologySettings.excluded_classes || '.related-posts, .ads-section, .banner, .comments';

        /* Build a fast lookup Set of nodes that should be excluded */
        const excludedSel = excludedClasses.split(',')
            .map(cls => cls.trim())
            .filter(Boolean)
            .join(',');
        const isExcluded = excludedSel
            ? (el) => el.closest(excludedSel)
            : () => false;

        let text = '';
        document.querySelectorAll(defaults).forEach(root => {
            root.querySelectorAll(findElements).forEach(node => {
                if (!isExcluded(node)) text += ' ' + node.textContent;
            });
        });
        return text.trim();
    }

    /* ——————————————————————————————————— */
    /*  3.  Main click‑handler               */
    /* ——————————————————————————————————— */
    async requestSummary() {

        /* Safety checks -------------------------------------------------- */
        if (typeof postologySettings === 'undefined') {
            console.error('postologySettings is not defined. Check plugin config.');
            this.$placeholder.innerHTML = `<p>Error: Plugin settings are not configured.</p>`;
            return;
        }

        const content = this.getArticleContent();
        if (!content) {
            console.error('No content found. Check your selectors in plugin settings.');
            this.$placeholder.innerHTML = `<p>Error: No content found in article.</p>`;
            return;
        }

        /* UI state ------------------------------------------------------- */
        this.$btn.disabled = true;
        this.$summary.style.display = 'block';         // show
        this.$loading.style.display = 'block';         // show
        // this.$placeholder.innerHTML = '';         // clear

        /* Helper for POST x‑www‑form‑urlencoded -------------------------- */
        const post = (data) => fetch(
            postologySettings.ajax_url,
            {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams(data)
            }
        ).then(r => r.json());

        /* 1) Analytics: increment clicks -------------------------------- */
        post({
            action: 'postology_increment_clicks',
            nonce: postologySettings.nonce,
            url_path: window.location.href
        }).catch(err => {
            console.error('Failed to increment clicks:', err);
        });

        try {
            /* 2) Generate the summary ---------------------------------- */
            const res = await post({
                action: 'generate_summary',
                nonce: postologySettings.nonce,
                content
            });

            this.$loading.style.display = 'none';

            if (res && res.success) {
                /* Success path */
                this.$placeholder.innerHTML = res.data;    // render summary
                if (this.$poweredBy) this.$poweredBy.style.display = 'block'; // unhide
                this.$boxWrapper?.remove();                      // remove button panel
            } else {
                /* WP returns success:false */
                console.error('Server error:', res?.data);
                this.$placeholder.innerHTML = `<p>Something went wrong. Please try again later.</p>`;
                this.$btn.disabled = false;
            }

        } catch (err) {
            /* Network / fetch error */
            console.error('AJAX request failed:', err);
            this.$loading.style.display = 'none';
            this.$placeholder.innerHTML = `<p>An error occurred while contacting the server. Please try again.</p>`;
            this.$btn.disabled = false;
        }
    }
}

/* Register the component once */
customElements.define('postology-el', PostologyBox);