/**
 * AIEO Magic Link modal — opens a small dialog when the customer
 * clicks the "Σύνδεση με email" SSO button.
 *
 * Flow:
 *   1. Click on `.aieo-sso-btn--magic_link` (or any `<a>` whose href
 *      starts with `#aieo-magic-link`).
 *   2. Modal renders inside `<body>` with an email input + submit.
 *   3. Submit POSTs to `/wp-json/aieo/v1/social-login/magic-link/request`
 *      with `{email, redirect_to, intent}`.
 *   4. Server response is generic-success regardless of whether the
 *      account existed (privacy / no enumeration). UI shows a "check
 *      your email" success state.
 *
 * Server-localised globals (set by AIEO_Runtime_SSO_Surfaces):
 *   - aieoMagicLinkCfg.endpoint     — REST URL
 *   - aieoMagicLinkCfg.intent       — 'login' | 'register' | 'checkout'
 *   - aieoMagicLinkCfg.redirectTo   — current URL the customer should
 *                                     return to after they click the link
 *   - aieoMagicLinkCfg.i18n         — translatable strings
 *
 * @package ai-eshop-optimizer
 * @since   5.4
 */
(function () {
    'use strict';

    if (typeof window === 'undefined') { return; }

    var cfg = window.aieoMagicLinkCfg || {};
    var i18n = cfg.i18n || {};
    var modalEl = null;

    function $(sel, root) {
        return (root || document).querySelector(sel);
    }

    function buildModal() {
        if (modalEl) { return modalEl; }
        var html = '' +
            '<div class="aieo-ml-overlay" data-aieo-ml-overlay aria-hidden="true">' +
              '<div class="aieo-ml-dialog" role="dialog" aria-modal="true" aria-labelledby="aieo-ml-title">' +
                '<button type="button" class="aieo-ml-close" data-aieo-ml-close aria-label="' + escapeAttr(i18n.close || 'Close') + '">×</button>' +
                '<h3 id="aieo-ml-title" class="aieo-ml-title">' + escapeHtml(i18n.title || 'Σύνδεση με email') + '</h3>' +
                '<p class="aieo-ml-intro">' + escapeHtml(i18n.intro || 'Δώσε το email σου και θα σου στείλουμε σύνδεσμο σύνδεσης. Δεν χρειάζεται κωδικός.') + '</p>' +
                '<form class="aieo-ml-form" data-aieo-ml-form>' +
                  '<label class="aieo-ml-label" for="aieo-ml-email">' + escapeHtml(i18n.emailLabel || 'Email') + '</label>' +
                  '<input id="aieo-ml-email" type="email" name="email" required autocomplete="email" inputmode="email" class="aieo-ml-input" placeholder="' + escapeAttr(i18n.emailPh || 'name@example.com') + '">' +
                  '<button type="submit" class="aieo-ml-submit">' + escapeHtml(i18n.submit || 'Στείλε μου σύνδεσμο') + '</button>' +
                '</form>' +
                '<div class="aieo-ml-status" data-aieo-ml-status aria-live="polite"></div>' +
              '</div>' +
            '</div>';
        var wrapper = document.createElement('div');
        wrapper.innerHTML = html;
        modalEl = wrapper.firstElementChild;
        document.body.appendChild(modalEl);

        // Close behaviours.
        modalEl.addEventListener('click', function (e) {
            if (e.target === modalEl || e.target.hasAttribute('data-aieo-ml-close')) {
                close();
            }
        });
        document.addEventListener('keydown', function (e) {
            if (modalEl && modalEl.classList.contains('is-open') && e.key === 'Escape') {
                close();
            }
        });

        // Submit handler.
        var form = $('[data-aieo-ml-form]', modalEl);
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            submitForm();
        });

        return modalEl;
    }

    function open() {
        var el = buildModal();
        el.classList.add('is-open');
        el.setAttribute('aria-hidden', 'false');
        // Focus the email input on the next tick (after browsers
        // finish their own focus management for modal elements).
        setTimeout(function () {
            var input = $('#aieo-ml-email', el);
            if (input) { input.focus(); }
        }, 50);
    }

    function close() {
        if (!modalEl) { return; }
        modalEl.classList.remove('is-open');
        modalEl.setAttribute('aria-hidden', 'true');
        // Reset status so a re-open doesn't show stale messages.
        var status = $('[data-aieo-ml-status]', modalEl);
        if (status) { status.textContent = ''; status.className = 'aieo-ml-status'; }
        var form = $('[data-aieo-ml-form]', modalEl);
        if (form) { form.style.display = ''; }
    }

    function setStatus(kind, message) {
        var status = $('[data-aieo-ml-status]', modalEl);
        if (!status) { return; }
        status.className = 'aieo-ml-status aieo-ml-status--' + kind;
        status.textContent = message || '';
    }

    function submitForm() {
        if (!cfg.endpoint) {
            setStatus('error', i18n.failed || 'Κάτι πήγε στραβά. Δοκίμασε ξανά.');
            return;
        }
        var emailInput = $('#aieo-ml-email', modalEl);
        var email = emailInput ? String(emailInput.value || '').trim() : '';
        if (!email || email.indexOf('@') < 1) {
            setStatus('error', i18n.invalidEmail || 'Παρακαλώ δώσε έγκυρο email.');
            return;
        }

        setStatus('info', i18n.sending || 'Αποστολή...');
        var submitBtn = modalEl.querySelector('.aieo-ml-submit');
        if (submitBtn) { submitBtn.disabled = true; }

        var payload = {
            email:       email,
            intent:      cfg.intent || 'login',
            redirect_to: cfg.redirectTo || window.location.href
        };

        fetch(cfg.endpoint, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: JSON.stringify(payload)
        }).then(function (r) {
            return r.json().then(function (j) {
                return { ok: r.ok, status: r.status, body: j };
            });
        }).then(function (resp) {
            if (submitBtn) { submitBtn.disabled = false; }
            if (resp.ok) {
                // Success — hide the form, show "check your email"
                // confirmation. Same UX whether the account existed,
                // was created, or was role-blocked (privacy).
                var form = $('[data-aieo-ml-form]', modalEl);
                if (form) { form.style.display = 'none'; }
                setStatus('success', (resp.body && resp.body.message)
                    || i18n.sent
                    || 'Σου στείλαμε σύνδεσμο σύνδεσης. Έλεγξε το email σου.');
            } else if (resp.status === 429) {
                setStatus('error', (resp.body && resp.body.message)
                    || i18n.rateLimited
                    || 'Πολλές προσπάθειες. Δοκίμασε ξανά σε λίγο.');
            } else {
                setStatus('error', (resp.body && resp.body.message)
                    || i18n.failed
                    || 'Κάτι πήγε στραβά. Δοκίμασε ξανά.');
            }
        }).catch(function () {
            if (submitBtn) { submitBtn.disabled = false; }
            setStatus('error', i18n.failed || 'Κάτι πήγε στραβά. Δοκίμασε ξανά.');
        });
    }

    function escapeHtml(s) {
        return String(s || '').replace(/[&<>"']/g, function (c) {
            return ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' })[c];
        });
    }
    function escapeAttr(s) { return escapeHtml(s); }

    // Bind clicks on any magic-link button. Accepts both the
    // `data-provider="magic_link"` attribute and the sentinel
    // `href="#aieo-magic-link"` for safety across renderers.
    document.addEventListener('click', function (e) {
        var t = e.target;
        while (t && t !== document.body) {
            if (t.getAttribute) {
                var prov = t.getAttribute('data-provider');
                var href = t.getAttribute('href');
                if (prov === 'magic_link' || (href && href.indexOf('#aieo-magic-link') === 0)) {
                    e.preventDefault();
                    e.stopPropagation();
                    open();
                    return;
                }
            }
            t = t.parentNode;
        }
    });
})();
