<template>
    <div class="bm-preview-canvas">
        <header class="bm-preview-canvas__header">
            <span class="bm-preview-canvas__label">Live Preview</span>
            <span v-if="loading" class="bm-preview-canvas__status">rendering…</span>
            <span v-else-if="error" class="bm-preview-canvas__status bm-preview-canvas__status--error">{{ error }}</span>
        </header>

        <div class="bm-preview-canvas__stage" v-if="!error">
            <component :is="'style'">{{ css }}</component>
            <div class="bm-preview-canvas__frame" v-html="html"></div>
        </div>

        <ul v-if="warnings.length" class="bm-preview-canvas__warnings">
            <li v-for="(w, i) in warnings" :key="i">{{ w }}</li>
        </ul>
    </div>
</template>

<script>
const ENDPOINT = (id) => `/api/block-manager/variants/${id}/preview`;
const DEBOUNCE_MS = 250;

export default {
    name: 'PreviewCanvas',
    props: {
        draftId:        { type: Number, default: null },
        propertiesJson: { type: Object, default: () => ({}) },
        sampleContent:  { type: String, default: '' },
        state:          { type: String, default: 'default' },
        breakpoint:     { type: String, default: 'desktop' },
    },
    data() {
        return {
            html:     '',
            css:      '',
            warnings: [],
            loading:  false,
            error:    null,
            _timer:   null,
        };
    },
    watch: {
        draftId() { this.schedule(); },
        propertiesJson: { deep: true, handler() { this.schedule(); } },
        sampleContent() { this.schedule(); },
        state()      { this.schedule(); },
        breakpoint() { this.schedule(); },
    },
    mounted() {
        this.schedule();
    },
    beforeDestroy() {
        if (this._timer) clearTimeout(this._timer);
    },
    methods: {
        schedule() {
            if (!this.draftId) return;
            if (this._timer) clearTimeout(this._timer);
            this._timer = setTimeout(() => this.fetchPreview(), DEBOUNCE_MS);
        },
        async fetchPreview() {
            if (!this.draftId) return;
            this.loading = true;
            this.error = null;
            try {
                const res = await fetch(ENDPOINT(this.draftId), {
                    method: 'POST',
                    headers: {
                        'Content-Type':     'application/json',
                        'Accept':           'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    body: JSON.stringify({
                        properties_json: this.propertiesJson,
                        sample_content:  this.sampleContent || undefined,
                        state:           this.state,
                        breakpoint:      this.breakpoint,
                    }),
                    credentials: 'same-origin',
                });
                if (!res.ok) throw new Error(`status ${res.status}`);
                const { data } = await res.json();
                this.html     = data.html || '';
                this.css      = data.css  || '';
                this.warnings = data.warnings || [];
            } catch (err) {
                this.error = `Preview failed: ${err.message}`;
            } finally {
                this.loading = false;
            }
        },
    },
};
</script>
