/**
 * Kripanov Anticopia - Frontend protection script.
 *
 * @package KripanovAnticopia
 * @since   1.0.0
 */
(function () {
    'use strict';

    var opts = window.KripanovAnticopia || {};
    var LONG_PRESS_MS = 480;
    var touchTimer = null;
    var touchMoved = false;

    function isEditable(el) {
        if (!el) return false;
        var node = el.nodeType === 3 ? el.parentElement : el;
        if (!node || !node.tagName) return false;
        var tag = node.tagName;
        if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
        if (node.isContentEditable) return true;
        if (typeof node.closest === 'function' && node.closest('[contenteditable="true"]')) return true;
        return false;
    }

    function isImageTarget(el) {
        if (!el) return false;
        var node = el.nodeType === 3 ? el.parentElement : el;
        if (!node) return false;
        if (node.tagName === 'IMG' || node.tagName === 'PICTURE' || node.tagName === 'SVG') return true;
        if (typeof node.closest === 'function' && node.closest('img, picture, svg, figure')) return true;
        return false;
    }

    function showNotice(msg) {
        if (!opts.showMessage) return;
        var existing = document.getElementById('kripanov-anticopia-notice');
        if (existing) {
            existing.classList.add('anticopia-show');
            clearTimeout(existing._hideTimer);
            existing._hideTimer = setTimeout(function () {
                existing.classList.remove('anticopia-show');
            }, 1800);
            return;
        }
        var el = document.createElement('div');
        el.id = 'kripanov-anticopia-notice';
        el.className = 'anticopia-notice anticopia-show';
        el.setAttribute('role', 'alert');
        el.textContent = msg || 'Protected content.';
        document.body.appendChild(el);
        el._hideTimer = setTimeout(function () {
            el.classList.remove('anticopia-show');
        }, 1800);
    }

    function block(e) {
        if (e && e.preventDefault) e.preventDefault();
        if (e && e.stopPropagation) e.stopPropagation();
        showNotice(opts.customMessage);
        return false;
    }

    function poisonClipboard(e) {
        var text = opts.clipboardText || opts.customMessage || 'Protected content.';
        try {
            if (e && e.clipboardData && typeof e.clipboardData.setData === 'function') {
                e.clipboardData.setData('text/plain', text);
                if (e.clipboardData.types && e.clipboardData.clearData) {
                    try { e.clipboardData.clearData('text/html'); } catch (err) { /* noop */ }
                }
            }
        } catch (err) { /* noop */ }

        if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
            try {
                navigator.clipboard.writeText(text).catch(function () { /* noop */ });
            } catch (err2) { /* noop */ }
        }
    }

    // Block right-click.
    if (opts.disableRightClick) {
        document.addEventListener('contextmenu', function (e) {
            if (isEditable(e.target)) return true;
            return block(e);
        }, true);
    }

    // Block mouse selection.
    if (opts.disableSelection) {
        document.addEventListener('selectstart', function (e) {
            if (isEditable(e.target)) return true;
            e.preventDefault();
            return false;
        }, true);

        document.addEventListener('mousedown', function (e) {
            if (e.detail > 1) {
                if (isEditable(e.target)) return true;
                e.preventDefault();
            }
        }, true);
    }

    // Block copy.
    if (opts.disableCopy) {
        document.addEventListener('copy', function (e) {
            if (isEditable(e.target)) return true;
            if (opts.emptyClipboard) {
                poisonClipboard(e);
            }
            return block(e);
        }, true);
    }

    // Block cut.
    if (opts.disableCut) {
        document.addEventListener('cut', function (e) {
            if (isEditable(e.target)) return true;
            if (opts.emptyClipboard) {
                poisonClipboard(e);
            }
            return block(e);
        }, true);
    }

    // Block paste.
    if (opts.disablePaste) {
        document.addEventListener('paste', function (e) {
            if (isEditable(e.target)) return true;
            return block(e);
        }, true);
    }

    // Block image dragging / drop.
    if (opts.disableDragImg || opts.protectImages) {
        document.addEventListener('dragstart', function (e) {
            if (isImageTarget(e.target) || (e.target && e.target.tagName === 'A' && e.target.querySelector('img'))) {
                e.preventDefault();
                showNotice(opts.customMessage);
                return false;
            }
        }, true);

        document.addEventListener('drop', function (e) {
            if (isImageTarget(e.target)) {
                e.preventDefault();
                return false;
            }
        }, true);
    }

    // Extra image protection: block open-in-new-tab style middle clicks on images.
    if (opts.protectImages) {
        document.addEventListener('auxclick', function (e) {
            if (e.button === 1 && isImageTarget(e.target)) {
                return block(e);
            }
        }, true);

        document.addEventListener('click', function (e) {
            if (!e.ctrlKey && !e.metaKey) return;
            if (isImageTarget(e.target)) {
                return block(e);
            }
        }, true);
    }

    // Mobile long-press / callout protection.
    if (opts.disableMobileGestures) {
        document.addEventListener('touchstart', function (e) {
            if (isEditable(e.target)) return;
            touchMoved = false;
            clearTimeout(touchTimer);
            touchTimer = setTimeout(function () {
                if (!touchMoved) {
                    showNotice(opts.customMessage);
                }
            }, LONG_PRESS_MS);
        }, { passive: true, capture: true });

        document.addEventListener('touchmove', function () {
            touchMoved = true;
            clearTimeout(touchTimer);
        }, { passive: true, capture: true });

        document.addEventListener('touchend', function () {
            clearTimeout(touchTimer);
        }, { passive: true, capture: true });

        document.addEventListener('touchcancel', function () {
            clearTimeout(touchTimer);
        }, { passive: true, capture: true });

        document.addEventListener('gesturestart', function (e) {
            if (isEditable(e.target)) return;
            e.preventDefault();
        }, true);
    }

    // Block keyboard shortcuts and inspection tools.
    if (opts.disableShortcuts || opts.disableDevtools || opts.disablePrint) {
        document.addEventListener('keydown', function (e) {
            var key = (e.key || '').toLowerCase();
            var code = e.keyCode || e.which;
            var ctrl = e.ctrlKey || e.metaKey;
            var shift = e.shiftKey;
            var alt = e.altKey;

            // DevTools: F12.
            if (opts.disableDevtools && (code === 123 || key === 'f12')) {
                return block(e);
            }

            // DevTools: Ctrl/Cmd+Shift+I / J / C / K.
            if (opts.disableDevtools && ctrl && shift && ['i', 'j', 'c', 'k'].indexOf(key) !== -1) {
                return block(e);
            }

            // macOS DevTools: Cmd+Option+I / J / C / U.
            if (opts.disableDevtools && e.metaKey && alt && ['i', 'j', 'c', 'u'].indexOf(key) !== -1) {
                return block(e);
            }

            // View source: Ctrl/Cmd+U.
            if (opts.disableDevtools && ctrl && key === 'u') {
                return block(e);
            }

            if (opts.disableShortcuts && ctrl) {
                // Copy / Cut / Paste / Select all / Save.
                if (['c', 'x', 'v', 'a', 's'].indexOf(key) !== -1) {
                    if (isEditable(e.target)) {
                        if (key === 's') {
                            return block(e);
                        }
                        return true;
                    }
                    if ((key === 'c' || key === 'x') && opts.emptyClipboard) {
                        poisonClipboard(e);
                    }
                    return block(e);
                }
            }

            // Print: Ctrl/Cmd+P.
            if (opts.disablePrint && ctrl && key === 'p') {
                return block(e);
            }
        }, true);
    }

    // Block printing via window.print.
    if (opts.disablePrint) {
        try {
            window.print = function () {
                showNotice(opts.customMessage);
            };
        } catch (err) { /* noop */ }

        window.addEventListener('beforeprint', function (e) {
            if (e && e.preventDefault) e.preventDefault();
            showNotice(opts.customMessage);
        });
    }

    // Basic DevTools open detection (heuristic only).
    if (opts.disableDevtools) {
        var devtoolsOpen = false;
        var threshold = 160;

        function checkDevtools() {
            var widthDiff = window.outerWidth - window.innerWidth;
            var heightDiff = window.outerHeight - window.innerHeight;
            var open = widthDiff > threshold || heightDiff > threshold;
            if (open && !devtoolsOpen) {
                devtoolsOpen = true;
                showNotice(opts.customMessage);
            } else if (!open) {
                devtoolsOpen = false;
            }
        }

        setInterval(checkDevtools, 1200);
    }
})();
