class CopyToClipboardComponent extends HTMLElement {
    static STYLE = `
            <style>
            .clickable {
                cursor: pointer;
            }
            </style>
            <link rel="stylesheet" href="../static/icons/font/bootstrap-icons.css">
        `;
    static IN_ACTIVE = CopyToClipboardComponent.STYLE + `<div class="clickable"><i class="bi bi-clipboard"></i> copy</div>`;
    static ACTIVE    = CopyToClipboardComponent.STYLE + `<div class="clickable"><i class="bi bi-clipboard-check"></i> copied</div>`;

    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
    }

    connectedCallback() {
        this.render(CopyToClipboardComponent.IN_ACTIVE);
        this.addEventListeners();
    }

    render(value) {
        this.shadowRoot.innerHTML = value;
    }

    addEventListeners() {
        this.addEventListener('click', this.copyToClipboard.bind(this));
    }

    copyToClipboard() {
        const fromElement = document.getElementById(this.getAttribute('from'));
        if (fromElement) {
            navigator.clipboard.writeText(fromElement.innerText)
                .then(() => {
                    console.log('Content copied to clipboard');
                    this.render(CopyToClipboardComponent.ACTIVE)
                    setTimeout((target) => {
                        this.render(CopyToClipboardComponent.IN_ACTIVE)
                    }, 3000, this);
                })
                .catch(err => {
                    console.error('Failed to copy: ', err);
                });
        } else {
            console.error('Element not found');
        }
    }
}



customElements.define('copy-to-clipboard', CopyToClipboardComponent);




class CodeSampleComponent extends HTMLElement {
    connectedCallback() {
        this.render();
    }

    render() {
        let id = this.getAttribute("id");
        let html = "<div class='small ps-5'><copy-to-clipboard from='" + id + "'></copy-to-clipboard></div>";
        html += "<p class='font-monospace small ps-5' id='" +id + "' >" + this.innerHTML + "</p>";
        console.log("html=" + html);
        this.innerHTML = html;
    }
}

customElements.define('code-sample', CodeSampleComponent);