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) {
    if (document.getElementById(MOUNT_ID)) return

    // 1. Create Host Element
    const host = document.createElement('div')
    host.id = MOUNT_ID
    document.body.appendChild(host)

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

    // 3. Create Container for Vue
    const container = document.createElement('div')
    container.id = 'app'
    shadowRoot.appendChild(container)

    // 4. Inject Styles into Shadow DOM
    // Note: In development/build, we need to find the generated CSS and inject it.
    // CRXJS usually puts CSS in <link> tags in the head for content scripts.
    // For Shadow DOM, we need to move or clone them into the shadow root.
    const injectStyles = () => {
        const styles = document.querySelectorAll('style, link[rel="stylesheet"]')
        styles.forEach(style => {
            // Only clone styles that look like they belong to our extension
            // This is a heuristic, in a real build we'd use the asset URL
            shadowRoot.appendChild(style.cloneNode(true))
        })
    }

    // Initial injection
    injectStyles()

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

    console.log('InsightReply Sidebar Mounted in Shadow DOM');
}

// Listen for messages to show/hide or update data
chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'SHOW_INSIGHT') {
        initSidebar(message.payload)
    }
});
