import Plugin from 'src/plugin-system/plugin.class';

export default class BcContactFormPlugin extends Plugin {
    init() {
        this.form = this.el.querySelector('.bc-contact-us-form');
        if (!this.form) return;

        this.urlInput = this.form.querySelector('.url');
        this.responseEl = this.form.querySelector('.response');
        this.sendButton = this.form.querySelector('.sendEmail');

        this._onSubmit = this._onSubmit.bind(this);
        this.form.addEventListener('submit', this._onSubmit);

        if (this.sendButton) {
            this.sendButton.addEventListener('click', (e) => {
                e.preventDefault();
                if (typeof this.form.requestSubmit === 'function') {
                    this.form.requestSubmit();
                } else {
                    this.form.dispatchEvent(new Event('submit', { cancelable: true }));
                }
            });
        }
    }

    async _onSubmit(event) {
        event.preventDefault();

        const fullnameEl = this.form.querySelector('.fullname');
        const emailEl = this.form.querySelector('.email');
        const contactEl = this.form.querySelector('.contact');
        const messageEl = this.form.querySelector('.message');

        const emailVal = emailEl ? emailEl.value.trim() : '';
        const messageVal = messageEl ? messageEl.value.trim() : '';

        const honeypotEl = this.form.querySelector('.bc-honeypot');

        if (emailVal.length < 1 || messageVal.length < 1) {
            this._showResponse(window.bcAquaContactSnippets.requiredFields, false);
            return;
        }

        const payload = {
            name: fullnameEl ? fullnameEl.value.trim() : '',
            phone: contactEl ? contactEl.value.trim() : '',
            email: emailVal,
            message: messageVal,
            company: honeypotEl ? honeypotEl.value.trim() : ''
        };

        const url = this.urlInput ? this.urlInput.value : '';

        if (!url) {
            this._showResponse(window.bcAquaContactSnippets.missingUrl, false);
            return;
        }

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(payload),
                credentials: 'same-origin'
            });

            if (response.ok) {
                this._showResponse(window.bcAquaContactSnippets.success, true);
                setTimeout(() => {
                    this._hideResponse();
                    this.form.reset();
                }, 5000);
            } else {
                const headerMsg = response.headers.get('bcErrorText');
                let bodyMsg = '';
                try {
                    const json = await response.json();
                    bodyMsg = json && (json.message || JSON.stringify(json));
                } catch (err) {
                    try { bodyMsg = await response.text(); } catch (_) { bodyMsg = ''; }
                }

                const errText = headerMsg || bodyMsg || `Request failed (${response.status})`;
                this._showResponse(errText, false);
                setTimeout(() => this._hideResponse(), 2000);
            }
        } catch (err) {
            this._showResponse(window.bcAquaContactSnippets.networkError, false);
            setTimeout(() => this._hideResponse(), 2000);
        }
    }

    _showResponse(text, success) { 
        if (!this.responseEl) return;
        
        this.responseEl.textContent = text;
        this.responseEl.style.display = 'block';
        this.responseEl.classList.remove('bg-success', 'bg-danger');
        
        if (success) {
            this.responseEl.classList.add('bg-success');
            this.responseEl.classList.remove('bg-danger');
        } else {
            this.responseEl.classList.add('bg-danger');
            this.responseEl.classList.remove('bg-success');
        }
    }

    _hideResponse() {
        if (!this.responseEl) return;
        this.responseEl.style.display = 'none';
        this.responseEl.textContent = '';
        this.responseEl.classList.remove('bg-success', 'bg-danger');
    }

    destroy() {
        if (this.form) {
            this.form.removeEventListener('submit', this._onSubmit);
        }
    }
}