(function () {
    'use strict';

    /**
     * CONTACT FORM ENDPOINT — NOT WIRED UP YET
     *
     * This site is hosted on Azure Storage static website hosting, which
     * has no compute of its own (no /api routing like Static Web Apps
     * provides). The plan is to back this with a Logic App HTTP trigger.
     *
     * IMPORTANT: a Logic App's "When an HTTP request is received" trigger
     * URL embeds a SAS signature in the query string (...&sig=...). That
     * signature is a bearer credential, functionally the same exposure
     * problem the old Azure Function key had — if this constant is ever
     * set directly to that raw trigger URL, anyone who views source gets
     * a working, replayable link to your Logic App, bypassing the form
     * entirely. A purely static frontend has no build step to keep that
     * secret out of the shipped JS, so the fix isn't in this file — it's
     * to never call the raw Logic App URL from the browser at all.
     *
     * Recommended setup: put Azure Front Door in front of both this static
     * site and the Logic App (you'll likely want Front Door anyway, for a
     * custom domain + TLS + the response-header rules noted in index.html).
     * Route the site's default path to Storage, and route /api/* on the
     * SAME custom domain to the Logic App as a second origin. The browser
     * then only ever sees /api/cv-request on your own domain — the real
     * Logic App hostname and sig stay server-side in Front Door's origin
     * config and are never shipped to the client. As defense in depth,
     * also restrict the Logic App trigger's "Allowed inbound IP addresses"
     * to Front Door's backend IP range, so even a leaked trigger URL can't
     * be called directly from anywhere else.
     *
     * Left as a same-origin relative path below so no code change is
     * needed once that routing exists. Until then, form submissions will
     * fail closed and the catch block already falls back to pointing
     * visitors at the email address instead — that's expected, not a bug.
     */
    const CV_REQUEST_ENDPOINT = '/api/cv-request';

    const modal = document.getElementById('modalOverlay');
    const openBtn = document.getElementById('openCvModalBtn');
    const closeBtn = document.getElementById('closeModalBtn');
    const form = document.getElementById('cvRequestForm');
    const statusDiv = document.getElementById('formStatus');

    let lastFocusedElement = null;

    function getFocusableModalElements() {
        return modal.querySelectorAll(
            'a[href], button:not([disabled]), input, textarea, select, [tabindex]:not([tabindex="-1"])'
        );
    }

    function openModal() {
        lastFocusedElement = document.activeElement;
        modal.classList.add('is-open');
        modal.setAttribute('aria-hidden', 'false');
        document.addEventListener('keydown', handleModalKeydown);
        const focusable = getFocusableModalElements();
        if (focusable.length) {
            focusable[0].focus();
        }
    }

    function closeModal() {
        modal.classList.remove('is-open');
        modal.setAttribute('aria-hidden', 'true');
        document.removeEventListener('keydown', handleModalKeydown);
        setStatus('', null);
        form.reset();
        if (lastFocusedElement) {
            lastFocusedElement.focus();
        }
    }

    function handleModalKeydown(e) {
        if (e.key === 'Escape') {
            closeModal();
            return;
        }
        if (e.key !== 'Tab') return;

        // Simple focus trap so Tab/Shift+Tab stay inside the open dialog
        const focusable = Array.from(getFocusableModalElements());
        if (!focusable.length) return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];

        if (e.shiftKey && document.activeElement === first) {
            e.preventDefault();
            last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
            e.preventDefault();
            first.focus();
        }
    }

    function setStatus(message, kind) {
        statusDiv.textContent = message;
        statusDiv.classList.remove('status-msg--info', 'status-msg--success', 'status-msg--error', 'hidden');
        if (!message) {
            statusDiv.classList.add('hidden');
            return;
        }
        if (kind) {
            statusDiv.classList.add('status-msg--' + kind);
        }
    }

    openBtn.addEventListener('click', openModal);
    closeBtn.addEventListener('click', closeModal);

    // Close modal if clicking outside content
    modal.addEventListener('click', (event) => {
        if (event.target === modal) closeModal();
    });

    // Handle Form Submission
    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        const name = document.getElementById('name').value.trim();
        const email = document.getElementById('email').value.trim();
        const message = document.getElementById('message').value.trim();

        if (!name || !email) {
            setStatus('Please fill in required fields.', 'error');
            return;
        }

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            setStatus('Please enter a valid email address.', 'error');
            return;
        }

        setStatus('Sending request...', 'info');

        const payload = {
            name: name,
            email: email,
            message: message,
            timestamp: new Date().toISOString()
        };

        try {
            const response = await fetch(CV_REQUEST_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            if (response.ok) {
                setStatus('Request sent successfully! I will be in touch.', 'success');
                setTimeout(closeModal, 3000);
            } else {
                throw new Error('Server responded with status ' + response.status);
            }
        } catch (error) {
            console.error('CV request failed:', error);
            setStatus('Something went wrong — please email me directly instead.', 'error');
        }
    });

    // Build the mailto link client-side so the plain address isn't sitting
    // as raw text in the page source for basic scrapers to harvest. This is
    // a mild deterrent, not real privacy protection — anyone inspecting the
    // rendered DOM or running this script still gets the address, and the
    // <noscript> fallback below intentionally contains the plain address
    // for accessibility and no-JS visitors.
    const contactLink = document.getElementById('contactEmail');
    if (contactLink) {
        const user = contactLink.getAttribute('data-user');
        const domain = contactLink.getAttribute('data-domain');
        if (user && domain) {
            const address = user + '@' + domain;
            contactLink.href = 'mailto:' + address;
            contactLink.textContent = address;
        }
    }

    // Scroll Animations: Reveal sections as they enter viewport
    const observerOptions = {
        threshold: 0.15
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
            }
        });
    }, observerOptions);

    document.querySelectorAll('section').forEach(section => {
        observer.observe(section);
    });

    // Active Nav Link Highlighting
    const navLinks = document.querySelectorAll('.nav-link');
    const sections = document.querySelectorAll('section');

    window.addEventListener('scroll', () => {
        let current = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            if (window.pageYOffset >= (sectionTop - 200)) {
                current = section.getAttribute('id');
            }
        });

        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href').includes(current)) {
                link.classList.add('active');
            }
        });
    });
})();