import EventBus, { Events, Event} from "../Events/EventBus";
import AppData from "../Common/AppData";

class BaseComponent {

    _component_base_ui;
    _isInitialized = false;
    is_recaptcha_active = false;
    recaptchaSiteKey;
    componentRequiresRecaptcha;
    turnstileWidgetId = null;


    constructor(component_base_ui) {
        this._component_base_ui = component_base_ui;
        this.is_recaptcha_active = AppData.getInstance().get('is_recaptcha_active');
        this.recaptchaSiteKey = AppData.getInstance().get('recaptcha_site_key');
        this.componentRequiresRecaptcha = this._component_base_ui.attr('data-recaptcha') === 'true';

        this._setInitializied();
    }

    _setInitializied() {
        if (this._component_base_ui) {
            this._component_base_ui.attr('data-initializied', 'true');
            this._isInitialized = true;
        }
    }

    checkRecaptcha() {
        if (this._shouldAddRecaptcha()) {
            this.loadRecaptcha();
        } else {
            this.removeRecaptcha();
        }
    }

    _shouldAddRecaptcha() {
        return this.is_recaptcha_active && this.componentRequiresRecaptcha;
    }

    loadRecaptcha() {
        if (document.getElementById('turnstile-script')) return;

        const script = document.createElement('script');
        script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
        script.id = 'turnstile-script';
        script.async = true;
        script.defer = true;
        document.body.appendChild(script);
    }

    removeRecaptcha() {
        const script = document.getElementById('turnstile-script');
        if (script) {
            script.remove();
        }
        const turnstileContainer = document.getElementById('turnstile-container');
        if (turnstileContainer) {
            turnstileContainer.remove();
        }
    }

    async executeRecaptcha(action = 'submit') {
        if (!window.turnstile) {
            console.error('Turnstile not loaded');
            return null;
        }

        return new Promise((resolve, reject) => {
            let container = this._component_base_ui.find('.turnstile-ui')[0];

            if (!container) {
                container = document.createElement('div');
                container.id = 'turnstile-container';
                container.style.position = 'fixed';
                container.style.zIndex = '-1';
                container.style.opacity = '0';
                document.body.appendChild(container);
            }

            if (this.turnstileWidgetId !== null) {
                window.turnstile.reset(this.turnstileWidgetId);
            }

            this.turnstileWidgetId = window.turnstile.render(container, {
                sitekey: this.recaptchaSiteKey,
                theme: 'light',
                callback: function(token) {
                    resolve(token);
                },
                'error-callback': function() {
                    reject(new Error('Turnstile verification failed'));
                }
            });
        });
    }

    show() {
        this._component_base_ui.removeClass('hidden');
    }

    hide() {
        this._component_base_ui.addClass('hidden');
    }

    fadeIn() {
        this._component_base_ui.find('.popup-content').css('opacity', '0');
        this._component_base_ui.find('.popup-content').animate({ opacity: 1 }, 100, () => {});
    }

    fadeOut() {
        this._component_base_ui.find('.popup-content').animate({ opacity: 0 }, 20, () => {
            this._component_base_ui.find('.popup-content').css('opacity', '0');
        });
    }

    handleRouteChange() {
        const hashChageEvent = new Event(
            Events.HASH_CHANGE,
            (payload) => {
                this.onRouteChange(payload);
            }
        );
        EventBus.getInstance().registerEvent(hashChageEvent);
    }

    hideFormErrorOnLoad() {
        this._component_base_ui.find('.form-error').addClass('hidden');
    }

    hideFormSuccessOnLoad() {
        this._component_base_ui.find('.form-success').addClass('hidden');
    }

    showFormError() {
        this._component_base_ui.find('.form-error').removeClass('hidden');
    }

    showFormSuccess() {
        this._component_base_ui.find('.form-success').removeClass('hidden');
    }

    hideForm() {
        this._component_base_ui.find('form').addClass('hidden');
    }

    showForm() {
        this._component_base_ui.find('form').removeClass('hidden');
    }

    handlePopupClickOutside(options = {}) {
        this._component_base_ui.find('.pupup-background-ui').on('click', (event) => {
            event.preventDefault();
            this._closePopup();
            if (options.newHash || options.newHash === '') {
                window.location.hash = options.newHash;
            }
        });
    }

    _closePopup() {}

    onRouteChange() {}

    checkIfIsLoggedIn() {}
}
export default BaseComponent;