/*!
 * BookiFlex Radio Card Field for Carbon Fields
 * License: GPL-2.0-or-later
 * © 2026 BookiFlex
 */
(function () {
    'use strict';

    class RadioCardManager {
        constructor() {
            this.isInitialized = false;
            this.containers = [];
        }

        init() {
            if (!this.validateCarbonFields()) {
                return;
            }

            if (this.isCarbonFieldsReady()) {
                this.setup();
            } else {
                const { addAction } = window.cf.hooks;
                addAction('carbon-fields.init', 'bookiflex/radio-card', () => {
                    setTimeout(() => this.setup(), 100);
                });
            }
        }

        validateCarbonFields() {
            return window.cf?.hooks?.addAction &&
                window.cf?.vendor?.['@wordpress/data'];
        }

        isCarbonFieldsReady() {
            try {
                const { select } = window.cf.vendor['@wordpress/data'];
                // Check if at least one radio card container's CF parent has fields loaded
                const el = document.querySelector('.bflex-radio-cards');
                if (!el) return false;
                const containerId = this.getContainerIdFromDom(el);
                if (!containerId) return false;
                const fields = select('carbon-fields/metaboxes').getFieldsByContainerId(containerId);
                return fields && fields.length > 0;
            } catch {
                return false;
            }
        }

        setup() {
            if (this.isInitialized) return;
            this.isInitialized = true;

            const { subscribe, select, dispatch } = window.cf.vendor['@wordpress/data'];

            document.querySelectorAll('.bflex-radio-cards').forEach(container => {
                const fieldName = container.dataset.field;
                if (!fieldName) return;

                const containerId = this.getContainerIdFromDom(container);
                if (!containerId) return;

                const info = this.findFieldInContainer(fieldName, containerId, select);
                if (!info) return;

                this.containers.push({ el: container, fieldName, containerId: info.containerId });
                this.bindClicks(container, info, select, dispatch);
                this.syncActiveState(container, info, select);
            });

            subscribe(() => {
                this.containers.forEach(({ el, fieldName, containerId }) => {
                    const info = this.findFieldInContainer(fieldName, containerId, select);
                    if (info) {
                        this.syncActiveState(el, info, select);
                    }
                });
            }, 'carbon-fields/metaboxes');
        }

        /**
         * Get the Carbon Fields container ID from the DOM hierarchy.
         */
        getContainerIdFromDom(element) {
            const containerEl = element.closest('[id^="carbon_fields_container_"]');
            return containerEl ? containerEl.id : null;
        }

        /**
         * Find a field by base_name within a specific container.
         */
        findFieldInContainer(fieldName, containerId, select) {
            const fields = select('carbon-fields/metaboxes').getFieldsByContainerId(containerId);
            if (!fields) return null;

            const field = fields.find(f => f.base_name === fieldName);
            if (!field) return null;

            return { field, containerId };
        }

        bindClicks(container, info, select, dispatch) {
            container.querySelectorAll('.bflex-radio-card').forEach(card => {
                card.addEventListener('click', () => {
                    const value = card.dataset.value;
                    this.setFieldValue(info.fieldName || info.field.base_name, info.containerId, value, select, dispatch);
                });
            });
        }

        async setFieldValue(fieldName, containerId, value, select, dispatch) {
            const fields = select('carbon-fields/metaboxes').getFieldsByContainerId(containerId);
            if (!fields) return;

            const field = fields.find(f => f.base_name === fieldName);
            if (!field) return;

            try {
                await dispatch('carbon-fields/metaboxes').addFields([{ ...field, value }]);
            } catch (error) {
                console.error('RadioCard: Failed to update field value:', error);
            }
        }

        syncActiveState(container, info, select) {
            const fields = select('carbon-fields/metaboxes').getFieldsByContainerId(info.containerId);
            if (!fields) return;

            const field = fields.find(f => f.base_name === info.field.base_name);
            if (!field) return;

            const currentValue = String(field.value || '');

            container.querySelectorAll('.bflex-radio-card').forEach(card => {
                card.classList.toggle('bflex-radio-card--active', card.dataset.value === currentValue);
            });
        }
    }

    new RadioCardManager().init();
})();
