// Written by retoor@molodetz.nl

// The following JavaScript code defines a custom HTML element `<html-frame>` that loads and displays HTML content from a specified URL. If the URL is provided as a markdown file, it attempts to render it as HTML.

// Uses the `HTMLElement` class and the methods `attachShadow`, `createElement`, `fetch`, and `define` to extend and manipulate HTML elements.

// MIT License

class HTMLFrame extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.container = document.createElement('div');
        this.shadowRoot.appendChild(this.container);
    }

    connectedCallback() {
        this.container.classList.add("html_frame");
        let url = this.getAttribute('url');
        if (!url.startsWith("https")) {
            url = "https://" + url;
        }
        if (url) {
            const fullUrl = url.startsWith("/") ? window.location.origin + url : new URL(window.location.origin + "/http-get");
            if (!url.startsWith("/")) {
                fullUrl.searchParams.set('url', url);
            }
            this.loadAndRender(fullUrl.toString());
        } else {
            this.container.textContent = "No source URL!";
        }
    }

    async loadAndRender(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Error: ${response.status} ${response.statusText}`);
            }
            const html = await response.text();
            if (url.endsWith(".md")) {
                const markdownElement = document.createElement('div');
                markdownElement.innerHTML = html;
                this.outerHTML = html;
            } else {
                this.container.innerHTML = html;
            }
        } catch (error) {
            this.container.textContent = `Error: ${error.message}`;
        }
    }
}

customElements.define('html-frame', HTMLFrame);