<template>
    <!-- This component is invisible but handles Live Preview communication -->
    <div style="display: none"></div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'

const STRAPI_ORIGIN = 'https://cms.takerofnotes.com'

/**
 * Handle messages from Strapi's Live Preview
 */
const handleMessage = async (message) => {
    const { origin, data } = message

    // Only accept messages from our Strapi instance
    if (origin !== STRAPI_ORIGIN) {
        return
    }

    try {
        switch (data.type) {
            case 'strapiUpdate':
                // Content has been updated in Strapi, refresh the page to show changes
                console.log('Strapi content updated, refreshing preview...')
                window.location.reload()
                break

            case 'strapiScript':
                // Inject the Live Preview script for interactive editing
                console.log('Injecting Live Preview script...')
                const script = document.createElement('script')
                script.textContent = data.payload.script
                document.head.appendChild(script)
                break

            default:
                // Unknown message type, ignore
                break
        }
    } catch (error) {
        console.error('Error handling Live Preview message:', error)
    }
}

onMounted(() => {
    // Add event listener for messages from Strapi
    window.addEventListener('message', handleMessage)

    // Signal to Strapi that we're ready to receive Live Preview scripts
    try {
        window.parent?.postMessage({ type: 'previewReady' }, STRAPI_ORIGIN)
        console.log('Live Preview: Signaled ready to parent window')
    } catch (error) {
        console.error('Error signaling Live Preview readiness:', error)
    }
})

onUnmounted(() => {
    // Clean up event listener
    window.removeEventListener('message', handleMessage)
})
</script>
