import { createApp } from 'vue'
import Sidebar from './Sidebar.vue'
import '../assets/tailwind.css' // We might need to handle this specially for Shadow DOM

const MOUNT_ID = 'insight-reply-sidebar-root'

function initSidebar(tweetData?: any) {
    let host = document.getElementById(MOUNT_ID)

    if (host) return;

    // 1. Create Host Element
    host = document.createElement('div')
    host.id = MOUNT_ID
    host.style.cssText = `
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 2147483647;
        pointer-events: none;
    `
    document.body.appendChild(host)

    // 2. Create Shadow Root
    const shadowRoot = host.attachShadow({ mode: 'open' })

    // 3. Create Container
    const container = document.createElement('div')
    container.id = 'app'
    container.style.cssText = `
        pointer-events: auto;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    `
    shadowRoot.appendChild(container)

    // 4. Inject Styles
    const injectStyles = () => {
        const styles = document.querySelectorAll('style, link[rel="stylesheet"]')
        styles.forEach(style => {
            shadowRoot.appendChild(style.cloneNode(true))
        })
    }
    injectStyles()

    // 5. Create Vue App
    const app = createApp(Sidebar, { tweetData })
    app.mount(container)
}

// Ensure it mounts on load if needed, but primarily triggered by messages
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
    if (message.type === 'SHOW_INSIGHT' || message.type === 'TOGGLE_SIDEBAR') {
        initSidebar(message.payload);
        // The component itself listens for TOGGLE_SIDEBAR to show/hide
        sendResponse({ received: true });
    }
    return true;
});
