import axios from 'axios';
import { ready, slideFadeToggle } from '@site/js/utils/dom.js';

/**
 * Members module — front-end is fully vanilla.
 *
 * This file is loaded from two places:
 *  1. The site bundle (sites/default/js/app.js) — front-end.
 *  2. modules/Members/admin/manage_member.php — a raw <script> tag in the admin.
 *
 * Admin-only behaviour (country/state cascade, jquery-ui tagit inputs) stays in
 * here so the admin keeps a single entry point. The tagit init is gated behind
 * `window['$']` so it only fires when the admin's jquery + jquery-ui globals
 * are present; on the front-end those selectors never render, so the front-end
 * path is a no-op even after the bundle drops jquery in a later phase.
 */

// Admin: cascade the state dropdown from the country selector.
async function toggleStates() {
    const stateRow = document.getElementById('state_row');
    if (!stateRow) {
        return;
    }

    const memberId = document.getElementById('member_id')?.value ?? '';
    const country = document.getElementById('country')?.value ?? '';

    try {
        const { data } = await axios.get('ajax/state_list.php', {
            params: { id: memberId, country },
        });
        stateRow.innerHTML = data;
    } catch (err) {
        const status = err.response?.status ?? 'network error';
        const message = err.response?.data?.message ?? err.message;
        console.error(`[toggleStates] ${status}: ${message}`);
    }
}

// Front-end: hide the billing-state row unless the country is US.
function checkBillingSelect() {
    const select = document.querySelector('select[name="billing_country"]');
    const billState = document.getElementById('bill-state');
    if (!select || !billState) {
        return;
    }
    billState.style.display = (select.value === 'US') ? '' : 'none';
}

// Front-end: handle a satisfactory-rating change (show/hide the comment box).
function onSatisfactoryChange() {
    const checked = document.querySelector('input[name=satisfactory]:checked');
    const selected = checked ? checked.value : null;

    document.querySelectorAll('.satisfactoryOption').forEach((opt) => {
        const messageId = opt.getAttribute('data-message_id');
        if (!messageId) {
            return;
        }
        const commentEl = document.getElementById(`satisfactoryComment-${messageId}`);
        if (!commentEl) {
            return;
        }
        commentEl.style.display = (selected === '3') ? '' : 'none';
    });
}

// Front-end: submit a satisfactory rating without leaving the page.
async function onSatisfactorySubmit(event) {
    event.preventDefault();
    const form = event.currentTarget;

    const formData = new URLSearchParams(new FormData(form));
    formData.append('action', 'satisfactory');

    try {
        const { data } = await axios.post('/members/messages/view_thread.php', formData, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        });
        const response = (typeof data === 'string') ? JSON.parse(data) : data;
        const container = document.getElementById(`satisfactoryContainer-${response.message_id}`);
        if (container) {
            container.innerHTML = response.success;
        }
    } catch (err) {
        const status = err.response?.status ?? 'network error';
        const message = err.response?.data?.message ?? err.message;
        console.error(`[satisfactoryForm] ${status}: ${message}`);
    }
}

// Front-end: toggle the rate-reply form on a message thread.
function onRateReplyClick(event) {
    event.preventDefault();
    const link = event.currentTarget;
    // .js_rateReply lives two levels deep from the wrapper that also holds the form.
    const wrapper = link.parentElement?.parentElement;
    const form = wrapper?.querySelector('.sastisfactoryForm');
    if (form) {
        slideFadeToggle(form, 200);
    }
}

ready(() => {

    // Admin: country/state cascade (manage_member.php).
    const countrySelect = document.getElementById('country');
    if (countrySelect && document.getElementById('state_row')) {
        toggleStates();
        countrySelect.addEventListener('change', toggleStates);
    }

    // Front-end: register/details billing-country US toggle.
    if (document.querySelector('.membersWrap, #memberRegister')) {
        checkBillingSelect();
        const billingCountry = document.querySelector('select[name="billing_country"]');
        billingCountry?.addEventListener('change', checkBillingSelect);
    }

    // Front-end member forms — submitForm is still a global from core/js/functions.js.
    [
        '.js_memberSignin',
        '.js_registerMember',
        '.js_registerExpressMember',
        '.js_reminder',
        '.js_resetPassword',
        '.js_memberContactDetails',
    ].forEach((selector) => {
        if (document.querySelector(selector) && typeof submitForm === 'function') {
            submitForm(selector);
        }
    });

    // Health profile bootstrap data — consumed by the Vue tag-input component.
    window.all_medications = [];
    window.all_medical_conditions = [];

    const medsEl = document.querySelector('.js_meds');
    if (medsEl) {
        try {
            window.all_medications = JSON.parse(medsEl.getAttribute('data-all-medications'));
        } catch (err) {
            console.error('[js_meds] could not parse data-all-medications', err.message);
        }
        try {
            window.all_medical_conditions = JSON.parse(medsEl.getAttribute('data-all-medical-conditions'));
        } catch (err) {
            console.error('[js_meds] could not parse data-all-medical-conditions', err.message);
        }
    }

    // Admin-only: jquery-ui tagit init.
    // Gated by the presence of the jquery global so this is a no-op on the
    // front-end bundle (where these selectors never render anyway).
    const jq = window['$'];
    if (typeof jq === 'function') {
        document.querySelectorAll('input.js_medications_tagit').forEach((input) => {
            jq(input).tagit({
                allowSpaces: true,
                availableTags: window.all_medications,
            });
        });

        document.querySelectorAll('input.js_medical_conditions_tagit').forEach((input) => {
            jq(input).tagit({
                allowSpaces: true,
                availableTags: window.all_medical_conditions,
            });
        });

        document.querySelectorAll('input.js_allergies_tagit').forEach((input) => {
            jq(input).tagit({
                allowSpaces: true,
            });
        });
    }

    // Front-end: message thread rating widget (view_thread.twig).
    if (document.getElementById('chat-log')) {
        document.querySelectorAll('.satisfactoryOption').forEach((opt) => {
            opt.addEventListener('change', onSatisfactoryChange);
        });
        // Initialise comment-box visibility based on the currently-checked radio.
        onSatisfactoryChange();

        document.querySelectorAll('.sastisfactoryForm').forEach((form) => {
            form.addEventListener('submit', onSatisfactorySubmit);
        });
    }

    // Front-end: rate-reply toggle on message threads.
    document.querySelectorAll('.js_rateReply').forEach((link) => {
        link.addEventListener('click', onRateReplyClick);
    });

});
