import axios from 'axios'

export function themesManager() {
    return {
        themes: [],
        loading: true,
        activating: null,
        thumbErrors: {},

        // Color panel
        colorPanel: false,
        colorTheme: null,
        colorValues: {},
        colorSaving: false,
        colorSaved: false,
        colorMessage: '',

        async init() {
            await this.fetch()
        },

        async fetch() {
            this.loading = true
            try {
                const { data } = await axios.get('/admin/themes', {
                    headers: { Accept: 'application/json' },
                })
                this.themes = data.data
            } finally {
                this.loading = false
            }
        },

        thumbSrc(slug) {
            return `/themes/${slug}.png`
        },

        thumbFailed(slug) {
            this.thumbErrors[slug] = true
        },

        hasThumb(slug) {
            return !this.thumbErrors[slug]
        },

        async activate(slug) {
            this.activating = slug
            try {
                const { data } = await axios.post('/admin/themes/activate', { theme: slug }, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                this.themes.forEach(t => { t.is_active = t.slug === data.active })
            } catch (e) {
                alert(e.response?.data?.message ?? 'Error activating theme.')
            } finally {
                this.activating = null
            }
        },

        async openColorPanel(theme) {
            this.colorTheme = theme
            this.colorValues = {}
            this.colorMessage = ''
            this.colorSaved = false
            try {
                const { data } = await axios.get('/admin/themes/colors', {
                    params: { theme: theme.slug },
                    headers: { Accept: 'application/json' },
                })
                // Merge saved colors over defaults
                const saved = data.colors ?? {}
                ;(data.definitions ?? []).forEach(def => {
                    this.colorValues[def.key] = saved[def.key] ?? def.default
                })
            } catch {}
            this.colorPanel = true
        },

        resetColor(def) {
            this.colorValues[def.key] = def.default
        },

        async saveColors() {
            this.colorSaving = true
            this.colorMessage = ''
            try {
                await axios.post('/admin/themes/colors', {
                    theme: this.colorTheme.slug,
                    colors: this.colorValues,
                }, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                this.colorSaved = true
                this.colorMessage = 'Colors saved successfully.'
                setTimeout(() => { this.colorMessage = ''; this.colorPanel = false }, 1200)
            } catch (e) {
                this.colorSaved = false
                this.colorMessage = e.response?.data?.message ?? 'Error saving colors.'
            } finally {
                this.colorSaving = false
            }
        },
    }
}
