/**
 * LoginCraft — Yeti Character Animation
 *
 * Vanilla JS adaptation of the original CodePen by tsouhaieb.
 * No GSAP/TweenMax dependency — uses CSS transitions instead.
 * Connects to WordPress login form IDs: #user_login, #user_pass, #wp-submit.
 *
 * @package LoginPageCustomizerAndDesigner
 */

(function () {
    'use strict';

    /* ── Element references ── */
    var mySVG, svgContainer;
    var eyeL, eyeR, nose, mouth, chin, face, eyebrow;
    var outerEarL, outerEarR, earHairL, earHairR, hair;
    var armL, armR, bodyBG, bodyBGchanged;
    var mouthBG, mouthSmallBG, mouthMediumBG, mouthLargeBG, mouthOutline, mouthMaskPath, tooth, tongue;

    var email, password;
    var svgCoords, emailCoords, screenCenter, emailScrollMax;
    var eyeLCoords, eyeRCoords, noseCoords, mouthCoords;
    var activeElement, curEmailIndex;
    var mouthStatus = 'small';
    var eyesCovered = false;
    var blinkTimer = null;
    var chinMin = 0.5;
    var eyeScale = 1;
    var dFromC;

    /* ── Smooth animate helper (replaces TweenMax.to) ── */
    function animateTo(el, props, dur) {
        if (!el) {
            return;
        }
        dur = dur || 0.6;
        el.style.transition = 'transform ' + dur + 's cubic-bezier(0.16,1,0.3,1)';
        var tx = props.x || 0;
        var ty = props.y || 0;
        var r = props.rotation || 0;
        var sx = props.scaleX !== undefined ? props.scaleX : '';
        var sy = props.scaleY !== undefined ? props.scaleY : '';
        var skX = props.skewX || 0;

        var parts = [];
        parts.push('translate(' + tx + 'px,' + ty + 'px)');
        if (r) {
            parts.push('rotate(' + r + 'deg)');
        }
        if (sx !== '' || sy !== '') {
            parts.push('scale(' + (sx !== '' ? sx : 1) + ',' + (sy !== '' ? sy : 1) + ')');
        }
        if (skX) {
            parts.push('skewX(' + skX + 'deg)');
        }
        el.style.transform = parts.join(' ');
    }

    /* ── Get angle between two points (original) ── */
    function getAngle(x1, y1, x2, y2) {
        return Math.atan2(y1 - y2, x1 - x2);
    }

    /* ── Get absolute position (original method — offset parent chain) ── */
    function getPosition(el) {
        var xPos = 0;
        var yPos = 0;
        while (el) {
            if (el.tagName === 'BODY') {
                var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
                var yScroll = el.scrollTop || document.documentElement.scrollTop;
                xPos += (el.offsetLeft - xScroll + el.clientLeft);
                yPos += (el.offsetTop - yScroll + el.clientTop);
            } else {
                xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
                yPos += (el.offsetTop - el.scrollTop + el.clientTop);
            }
            el = el.offsetParent;
        }
        return { x: xPos, y: yPos };
    }

    /* ── Mouth state (show/hide different SVG paths) ── */
    function setMouthState(state) {
        if (mouthBG) {
            mouthBG.style.display = state === 'small' ? '' : 'none';
        }
        if (mouthSmallBG) {
            mouthSmallBG.style.display = state === 'small' ? '' : 'none';
        }
        if (mouthMediumBG) {
            mouthMediumBG.style.display = state === 'medium' ? '' : 'none';
        }
        if (mouthLargeBG) {
            mouthLargeBG.style.display = state === 'large' ? '' : 'none';
        }
        if (mouthOutline) {
            mouthOutline.style.display = state === 'small' ? '' : 'none';
        }
        if (tooth) {
            var tOff = state === 'large' ? { x: 3, y: -2 } : { x: 0, y: 0 };
            animateTo(tooth, tOff, 0.4);
        }
        if (tongue) {
            var tY = state === 'large' ? 2 : state === 'medium' ? 1 : 0;
            animateTo(tongue, { y: tY }, 0.4);
        }
        mouthStatus = state;
    }

    /* ── Face tracking — matches the original exactly ── */
    function calculateFaceMove(e) {
        if (!email || !mySVG) {
            return;
        }

        var carPos = email.selectionEnd;
        if (carPos === null || carPos === 0) {
            carPos = email.value.length;
        }

        var div = document.createElement('div');
        var span = document.createElement('span');
        var copyStyle = getComputedStyle(email);

        [].forEach.call(copyStyle, function (prop) {
            div.style[prop] = copyStyle[prop];
        });
        div.style.position = 'absolute';
        document.body.appendChild(div);
        div.textContent = email.value.substr(0, carPos);
        span.textContent = email.value.substr(carPos) || '.';
        div.appendChild(span);

        var caretCoords, eyeLAngle, eyeRAngle, noseAngle, mouthAngle;

        if (email.scrollWidth <= emailScrollMax) {
            caretCoords = getPosition(span);
            dFromC = screenCenter - (caretCoords.x + emailCoords.x);
            eyeLAngle = getAngle(eyeLCoords.x, eyeLCoords.y, emailCoords.x + caretCoords.x, emailCoords.y + 25);
            eyeRAngle = getAngle(eyeRCoords.x, eyeRCoords.y, emailCoords.x + caretCoords.x, emailCoords.y + 25);
            noseAngle = getAngle(noseCoords.x, noseCoords.y, emailCoords.x + caretCoords.x, emailCoords.y + 25);
            mouthAngle = getAngle(mouthCoords.x, mouthCoords.y, emailCoords.x + caretCoords.x, emailCoords.y + 25);
        } else {
            eyeLAngle = getAngle(eyeLCoords.x, eyeLCoords.y, emailCoords.x + emailScrollMax, emailCoords.y + 25);
            eyeRAngle = getAngle(eyeRCoords.x, eyeRCoords.y, emailCoords.x + emailScrollMax, emailCoords.y + 25);
            noseAngle = getAngle(noseCoords.x, noseCoords.y, emailCoords.x + emailScrollMax, emailCoords.y + 25);
            mouthAngle = getAngle(mouthCoords.x, mouthCoords.y, emailCoords.x + emailScrollMax, emailCoords.y + 25);
        }

        var eyeLX = Math.cos(eyeLAngle) * 20;
        var eyeLY = Math.sin(eyeLAngle) * 10;
        var eyeRX = Math.cos(eyeRAngle) * 20;
        var eyeRY = Math.sin(eyeRAngle) * 10;
        var noseX = Math.cos(noseAngle) * 23;
        var noseY = Math.sin(noseAngle) * 10;
        var mouthX = Math.cos(mouthAngle) * 23;
        var mouthY = Math.sin(mouthAngle) * 10;
        var mouthR = Math.cos(mouthAngle) * 6;
        var chinX = mouthX * 0.8;
        var chinY = mouthY * 0.5;
        var chinS = 1 - ((dFromC * 0.15) / 100);
        if (chinS > 1) {
            chinS = 1 - (chinS - 1);
            if (chinS < chinMin) {
                chinS = chinMin;
            }
        }
        var faceX = mouthX * 0.3;
        var faceY = mouthY * 0.4;
        var faceSkew = Math.cos(mouthAngle) * 5;
        var eyebrowSkew = Math.cos(mouthAngle) * 25;
        var outerEarX = Math.cos(mouthAngle) * 4;
        var outerEarY = Math.cos(mouthAngle) * 5;
        var hairX = Math.cos(mouthAngle) * 6;

        animateTo(eyeL, { x: -eyeLX, y: -eyeLY });
        animateTo(eyeR, { x: -eyeRX, y: -eyeRY });
        animateTo(nose, { x: -noseX, y: -noseY, rotation: mouthR });
        animateTo(mouth, { x: -mouthX, y: -mouthY, rotation: mouthR });
        animateTo(chin, { x: -chinX, y: -chinY, scaleY: chinS });
        animateTo(face, { x: -faceX, y: -faceY, skewX: -faceSkew });
        animateTo(eyebrow, { x: -faceX, y: -faceY, skewX: -eyebrowSkew });
        animateTo(outerEarL, { x: outerEarX, y: -outerEarY });
        animateTo(outerEarR, { x: outerEarX, y: outerEarY });
        animateTo(earHairL, { x: -outerEarX, y: -outerEarY });
        animateTo(earHairR, { x: -outerEarX, y: outerEarY });
        animateTo(hair, { x: hairX, scaleY: 1.2 });

        document.body.removeChild(div);
    }

    /* ── Email input handlers (matches original) ── */
    function onEmailInput(e) {
        calculateFaceMove(e);
        var value = email.value;
        curEmailIndex = value.length;

        if (curEmailIndex > 0) {
            if (value.indexOf('@') !== -1) {
                if (mouthStatus !== 'large') {
                    setMouthState('large');
                    eyeScale = 0.65;
                }
            } else {
                if (mouthStatus !== 'medium') {
                    setMouthState('medium');
                    eyeScale = 0.85;
                }
            }
        } else {
            if (mouthStatus !== 'small') {
                setMouthState('small');
                eyeScale = 1;
            }
        }
    }

    /* ── Look at field (for initial focus — face looks down at the input) ── */
    function lookAtField() {
        if (!email || !mySVG) {
            return;
        }
        /* Fixed "look down" values matching the original CodePen appearance */
        animateTo(eyeL, { x: 2, y: 10 });
        animateTo(eyeR, { x: -2, y: 10 });
        animateTo(nose, { x: 0, y: 8, rotation: 0 });
        animateTo(mouth, { x: 0, y: 6, rotation: 0 });
        animateTo(chin, { x: 0, y: 3, scaleY: 0.95 });
        animateTo(face, { x: 0, y: 3, skewX: 0 });
        animateTo(eyebrow, { x: 0, y: 2, skewX: 0 });
        animateTo(outerEarL, { x: 0, y: -2 });
        animateTo(outerEarR, { x: 0, y: -2 });
        animateTo(earHairL, { x: 0, y: 1 });
        animateTo(earHairR, { x: 0, y: 1 });
        animateTo(hair, { x: 0, scaleY: 1.1 });
    }

    function onEmailFocus(e) {
        activeElement = 'email';
        if (email.value.length === 0) {
            lookAtField();
        } else {
            onEmailInput(e);
        }
    }

    function onEmailBlur(e) {
        activeElement = null;
        setTimeout(function () {
            if (activeElement === 'email') {
                // still focused
            } else {
                resetFace();
                setMouthState('small');
            }
        }, 100);
    }

    /* ── Password input handlers ── */
    function onPasswordFocus() {
        activeElement = 'password';
        if (!eyesCovered) {
            coverEyes();
        }
    }

    function onPasswordBlur() {
        activeElement = null;
        setTimeout(function () {
            if (activeElement === 'password' || activeElement === 'toggle') {
                // still in password area
            } else {
                uncoverEyes();
            }
        }, 100);
    }

    /* ── Reset face ── */
    function resetFace() {
        var z = { x: 0, y: 0 };
        animateTo(eyeL, z);
        animateTo(eyeR, z);
        animateTo(nose, { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 });
        animateTo(mouth, { x: 0, y: 0, rotation: 0 });
        animateTo(chin, { x: 0, y: 0, scaleY: 1 });
        animateTo(face, { x: 0, y: 0, skewX: 0 });
        animateTo(eyebrow, { x: 0, y: 0, skewX: 0 });
        animateTo(outerEarL, z);
        animateTo(outerEarR, z);
        animateTo(earHairL, z);
        animateTo(earHairR, z);
        animateTo(hair, { x: 0, scaleY: 1 });
    }

    /* ── Cover / Uncover eyes ── */
    function coverEyes() {
        if (mySVG) {
            mySVG.classList.add('lpcd-eyes-covered');
        }
        eyesCovered = true;
    }

    function uncoverEyes() {
        if (mySVG) {
            mySVG.classList.remove('lpcd-eyes-covered');
        }
        eyesCovered = false;
    }

    /* ── Blinking ── */
    function doBlink() {
        if (eyeL) {
            eyeL.classList.add('lpcd-blink');
        }
        if (eyeR) {
            eyeR.classList.add('lpcd-blink');
        }
        setTimeout(function () {
            if (eyeL) {
                eyeL.classList.remove('lpcd-blink');
            }
            if (eyeR) {
                eyeR.classList.remove('lpcd-blink');
            }
        }, 200);
    }

    function startBlinking(delay) {
        if (delay) {
            delay = Math.floor(Math.random() * Math.floor(delay)) * 1000;
        } else {
            delay = 1000;
        }
        blinkTimer = setTimeout(function () {
            doBlink();
            startBlinking(12);
        }, delay);
    }

    function stopBlinking() {
        if (blinkTimer) {
            clearTimeout(blinkTimer);
            blinkTimer = null;
        }
    }

    /* ── Init ── */
    function initLoginForm() {
        svgContainer = document.querySelector('.lpcd-yeti-container');
        if (!svgContainer) {
            return;
        }

        mySVG = document.querySelector('.lpcd-yeti-svg');
        if (!mySVG) {
            return;
        }

        /* Get SVG child elements */
        eyeL = mySVG.querySelector('.eyeL');
        eyeR = mySVG.querySelector('.eyeR');
        nose = mySVG.querySelector('.nose');
        mouth = mySVG.querySelector('.mouth');
        chin = mySVG.querySelector('.chin');
        face = mySVG.querySelector('.face');
        eyebrow = mySVG.querySelector('.eyebrow');
        outerEarL = mySVG.querySelector('.earL .outerEar');
        outerEarR = mySVG.querySelector('.earR .outerEar');
        earHairL = mySVG.querySelector('.earL .earHair');
        earHairR = mySVG.querySelector('.earR .earHair');
        hair = mySVG.querySelector('.hair');
        armL = mySVG.querySelector('.armL');
        armR = mySVG.querySelector('.armR');
        bodyBG = mySVG.querySelector('.bodyBGnormal');
        bodyBGchanged = mySVG.querySelector('.bodyBGchanged');
        mouthBG = mySVG.querySelector('.mouthBG');
        mouthSmallBG = mySVG.querySelector('.mouthSmallBG');
        mouthMediumBG = mySVG.querySelector('.mouthMediumBG');
        mouthLargeBG = mySVG.querySelector('.mouthLargeBG');
        mouthOutline = mySVG.querySelector('.mouthOutline');
        mouthMaskPath = document.querySelector('#mouthMaskPath');
        tooth = mySVG.querySelector('.tooth');
        tongue = mySVG.querySelector('.tongue');

        /* WordPress form fields */
        email = document.getElementById('user_login');
        password = document.getElementById('user_pass');

        /* Fallbacks for register / lostpassword */
        if (!email) {
            email = document.querySelector('#registerform #user_login');
        }
        if (!email) {
            email = document.querySelector('#lostpasswordform #user_login');
        }

        if (email) {
            /* Calculate coordinate measurements */
            svgCoords = getPosition(mySVG);
            emailCoords = getPosition(email);
            screenCenter = svgCoords.x + (mySVG.offsetWidth / 2);
            eyeLCoords = { x: svgCoords.x + 84, y: svgCoords.y + 76 };
            eyeRCoords = { x: svgCoords.x + 113, y: svgCoords.y + 76 };
            noseCoords = { x: svgCoords.x + 97, y: svgCoords.y + 81 };
            mouthCoords = { x: svgCoords.x + 100, y: svgCoords.y + 100 };

            /* Bind events */
            email.addEventListener('focus', onEmailFocus);
            email.addEventListener('blur', onEmailBlur);
            email.addEventListener('input', onEmailInput);

            /* Get max scroll width for email tracking limit */
            emailScrollMax = email.scrollWidth;
        }

        if (password) {
            password.addEventListener('focus', onPasswordFocus);
            password.addEventListener('blur', onPasswordBlur);
        }

        /* Set initial mouth state */
        setMouthState('small');

        /* Activate blinking */
        startBlinking(5);

        /* Recalc on resize */
        window.addEventListener('resize', function () {
            if (email && mySVG) {
                svgCoords = getPosition(mySVG);
                emailCoords = getPosition(email);
                screenCenter = svgCoords.x + (mySVG.offsetWidth / 2);
                eyeLCoords = { x: svgCoords.x + 84, y: svgCoords.y + 76 };
                eyeRCoords = { x: svgCoords.x + 113, y: svgCoords.y + 76 };
                noseCoords = { x: svgCoords.x + 97, y: svgCoords.y + 81 };
                mouthCoords = { x: svgCoords.x + 100, y: svgCoords.y + 100 };
                emailScrollMax = email.scrollWidth;
            }
        });
    }

    /* Wait for DOM */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initLoginForm);
    } else {
        initLoginForm();
    }
})();
