/**
 * Tassos Code Snippets — Copy-to-clipboard helpers
 *
 * Shared behaviours used by:
 *  - The Shortcode Display form field (ShortcodeDisplayField).
 *  - The Snippets list view (clickable shortcode badge in the Location column).
 *
 * Bindings (selector → behaviour):
 *  - `.tcs-copy-shortcode` (button)
 *      Copies the value of the input referenced by `data-field-id`.
 *  - `.tcs-shortcode-wrapper .tcs-shortcode-display input[readonly]`
 *      Clicking the read-only input copies its value and flashes the sibling
 *      `.tcs-copy-shortcode` button.
 *  - `[data-tcs-copy]`
 *      Any element that should copy its own text (or `data-tcs-copy-value`)
 *      on click and briefly show a "Copied" badge.
 *
 * The file also keeps the field-specific edit/modal handlers (Save / Cancel /
 * Modal Confirm) so the field continues to work without inline JS.
 */
(function ()
{
    'use strict';

    /**
     * Copy a string to the clipboard. Tries the async Clipboard API first
     * and falls back to a hidden <input> + execCommand('copy') for browsers
     * that block writeText outside secure contexts.
     */
    function copyText(text)
    {
        if (!text)
        {
            return false;
        }

        if (navigator.clipboard && window.isSecureContext)
        {
            navigator.clipboard.writeText(text).catch(function () {});
            return true;
        }

        var temp = document.createElement('input');
        temp.value = text;
        temp.style.position = 'absolute';
        temp.style.left = '-9999px';
        document.body.appendChild(temp);
        temp.select();
        temp.setSelectionRange(0, 99999);

        var ok = false;

        try
        {
            ok = document.execCommand('copy');
        }
        catch (err)
        {
            ok = false;
        }

        document.body.removeChild(temp);
        return ok;
    }

    /** Briefly replace an element's contents, then restore the original markup. */
    function flashContent(el, html, duration)
    {
        var original = el.innerHTML;
        el.innerHTML = html;
        setTimeout(function () { el.innerHTML = original; }, duration || 2000);
    }

    /** Show a green check inside the given button/element. */
    function flashCheck(el)
    {
        flashContent(el, '<span class="icon-check text-success" aria-hidden="true"></span>');
    }

    function init()
    {
        // ── Copy buttons inside the Shortcode Display field ─────────────────
        document.querySelectorAll('.tcs-copy-shortcode').forEach(function (btn)
        {
            btn.addEventListener('click', function ()
            {
                var input = document.getElementById(this.getAttribute('data-field-id'));

                if (!input || !input.value)
                {
                    return;
                }

                if (copyText(input.value))
                {
                    flashCheck(this);
                }
            });
        });

        // ── Clicking the readonly input copies its value ────────────────────
        document.querySelectorAll('.tcs-shortcode-wrapper .tcs-shortcode-display input[readonly]').forEach(function (input)
        {
            input.addEventListener('click', function ()
            {
                var btn = this.closest('.position-relative').querySelector('.tcs-copy-shortcode');

                if (!btn || !this.value)
                {
                    return;
                }

                if (copyText(this.value))
                {
                    flashCheck(btn);
                }
            });
        });

        // ── Generic clickable copy (used by the Snippets list view) ─────────
        document.querySelectorAll('[data-tcs-copy]').forEach(function (el)
        {
            el.addEventListener('click', function ()
            {
                var value = this.getAttribute('data-tcs-copy-value');

                if (value === null)
                {
                    value = this.textContent.trim();
                }

                if (!copyText(value))
                {
                    return;
                }

                var label = this.getAttribute('data-tcs-copy-label') || 'Copied';
                var html  = '<span class="icon-check text-success" aria-hidden="true"></span> ' + label;

                this.classList.add('tcs-copied');
                flashContent(this, html, 1500);
                setTimeout((function (node) { return function () { node.classList.remove('tcs-copied'); }; })(this), 1500);
            });
        });

        // ── Modal confirm → reveal inline edit (Layer B of ShortcodeDisplayField) ──
        document.querySelectorAll('.tcs-modal-confirm-btn').forEach(function (btn)
        {
            btn.addEventListener('click', function ()
            {
                var fieldId = this.getAttribute('data-field-id');
                var wrapper = document.getElementById(fieldId).closest('.tcs-shortcode-wrapper');

                wrapper.querySelector('.tcs-shortcode-display').classList.add('d-none');
                wrapper.querySelector('.tcs-shortcode-edit').classList.remove('d-none');
                wrapper.querySelector('.tcs-shortcode-key-input').focus();

                var desc = document.getElementById(fieldId + '-desc');

                if (desc)
                {
                    desc.classList.add('d-none');
                }
            });
        });

        // ── Inline edit: Save ───────────────────────────────────────────────
        document.querySelectorAll('.tcs-shortcode-save-btn').forEach(function (btn)
        {
            btn.addEventListener('click', function ()
            {
                var wrapper  = this.closest('.tcs-shortcode-wrapper');
                var keyInput = wrapper.querySelector('.tcs-shortcode-key-input');
                var key      = keyInput.value.trim();

                if (!key)
                {
                    return;
                }

                var aliasField = document.getElementById('jform_alias');

                if (aliasField)
                {
                    aliasField.value = key;
                }

                var fieldId      = wrapper.querySelector('.tcs-copy-shortcode').getAttribute('data-field-id');
                var displayInput = document.getElementById(fieldId);

                displayInput.value = '{tcs snippet.' + key + '}';
                keyInput.value     = key;

                wrapper.querySelector('.tcs-shortcode-edit').classList.add('d-none');
                wrapper.querySelector('.tcs-shortcode-display').classList.remove('d-none');

                var desc = document.getElementById(fieldId + '-desc');

                if (desc)
                {
                    desc.classList.remove('d-none');
                }
            });
        });

        // ── Inline edit: Cancel ─────────────────────────────────────────────
        document.querySelectorAll('.tcs-shortcode-cancel-btn').forEach(function (btn)
        {
            btn.addEventListener('click', function ()
            {
                var wrapper = this.closest('.tcs-shortcode-wrapper');

                wrapper.querySelector('.tcs-shortcode-edit').classList.add('d-none');
                wrapper.querySelector('.tcs-shortcode-display').classList.remove('d-none');

                var fieldId = wrapper.querySelector('.tcs-copy-shortcode').getAttribute('data-field-id');
                var desc    = document.getElementById(fieldId + '-desc');

                if (desc)
                {
                    desc.classList.remove('d-none');
                }
            });
        });
    }

    if (document.readyState === 'loading')
    {
        document.addEventListener('DOMContentLoaded', init);
    }
    else
    {
        init();
    }
})();
