class OtpAuth {
    constructor() {
        this.init();
    }

    init() {
        this.modal = document.getElementById('otpModal');
        this.step1 = document.getElementById('otpStep1');
        this.step2 = document.getElementById('otpStep2');
        this.otpForm = document.getElementById('otpForm');
        this.otpVerifyForm = document.getElementById('otpVerifyForm');
        this.otpBtn = document.getElementById('otpCheckoutBtn');
        this.otpError = document.getElementById('otpError');
        this.otpVerifyError = document.getElementById('otpVerifyError');

        if (!this.modal) return;

        this.attachEvents();
    }

    attachEvents() {
        this.otpBtn?.addEventListener('click', () => this.openModal());

        document.getElementById('otpModalClose')?.addEventListener('click', () => this.closeModal());
        document.getElementById('otpModalClose2')?.addEventListener('click', () => this.closeModal());
        document.getElementById('otpModalBackdrop')?.addEventListener('click', () => this.closeModal());

        this.otpForm?.addEventListener('submit', (e) => this.handleRequestOtp(e));
        this.otpVerifyForm?.addEventListener('submit', (e) => this.handleVerifyOtp(e));
    }

    openModal() {
        this.modal.classList.remove('hidden');
        this.step1.classList.remove('hidden');
        this.step2.classList.add('hidden');
        this.otpError.classList.add('hidden');
        this.otpVerifyError.classList.add('hidden');
        document.getElementById('otpCode').value = '';
        document.body.style.overflow = 'hidden';
    }

    closeModal() {
        this.modal.classList.add('hidden');
        document.body.style.overflow = '';
    }

    async handleRequestOtp(e) {
        e.preventDefault();
        const submitBtn = this.otpForm.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.textContent = 'Mengirim...';

        this.otpError.classList.add('hidden');

        try {
            const response = await fetch('/auth/request-otp', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content
                },
                body: JSON.stringify({
                    name: document.getElementById('otpName').value,
                    phone: document.getElementById('otpPhone').value,
                })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.message || 'Gagal mengirim OTP');
            }

            document.getElementById('verifyPhone').value = document.getElementById('otpPhone').value;
            document.getElementById('verifyName').value = document.getElementById('otpName').value;
            document.getElementById('otpPhoneDisplay').textContent = document.getElementById('otpPhone').value;

            this.step1.classList.add('hidden');
            this.step2.classList.remove('hidden');
            document.getElementById('otpCode').focus();

        } catch (error) {
            this.otpError.textContent = error.message;
            this.otpError.classList.remove('hidden');
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = 'Kirim Kode OTP';
        }
    }

    async handleVerifyOtp(e) {
        e.preventDefault();
        const submitBtn = this.otpVerifyForm.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.textContent = 'Memverifikasi...';

        this.otpVerifyError.classList.add('hidden');

        try {
            const response = await fetch('/auth/verify-otp', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content
                },
                body: JSON.stringify({
                    phone: document.getElementById('verifyPhone').value,
                    otp: document.getElementById('otpCode').value,
                    name: document.getElementById('verifyName').value,
                })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.message || 'Gagal verifikasi OTP');
            }

            this.closeModal();
            window.location.reload();

        } catch (error) {
            this.otpVerifyError.textContent = error.message;
            this.otpVerifyError.classList.remove('hidden');
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = 'Verifikasi & Masuk';
        }
    }
}

export default OtpAuth;
