/**
 * Safety Tips Page JavaScript
 * Handles animations, counters, video player, and checklist downloads
 */

(function() {
    'use strict';

    // Initialize WOW.js for animations
    if (typeof WOW !== 'undefined') {
        new WOW().init();
    }

    /**
     * Animated Counter
     * @param {HTMLElement} element - The element to animate
     * @param {number} target - The target number to count to
     * @param {number} duration - Animation duration in milliseconds
     */
    function animateCounter(element, target, duration = 2000) {
        const start = 0;
        const increment = target / (duration / 16);
        let current = start;

        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                element.textContent = target.toLocaleString();
                clearInterval(timer);
            } else {
                if (target > 1000) {
                    element.textContent = Math.floor(current).toLocaleString();
                } else {
                    element.textContent = Math.floor(current);
                }
            }
        }, 16);
    }

    /**
     * Initialize Counter Animation with Intersection Observer
     */
    function initCounters() {
        const observerOptions = {
            threshold: 0.5,
            rootMargin: '0px'
        };

        const observerCallback = (entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const counters = entry.target.querySelectorAll('.stat-number[data-count]');
                    counters.forEach(counter => {
                        const target = parseInt(counter.getAttribute('data-count'));
                        animateCounter(counter, target);
                        counter.removeAttribute('data-count'); // Prevent re-animation
                    });
                }
            });
        };

        const observer = new IntersectionObserver(observerCallback, observerOptions);
        const statsSection = document.querySelector('.safety-stats-section');
        if (statsSection) {
            observer.observe(statsSection);
        }
    }

    /**
     * Video Player Function
     * Replaces placeholder with YouTube embed
     */
    window.playVideo = function() {
        const placeholder = document.getElementById('videoPlaceholder');
        if (placeholder) {
            // Replace with actual video embed or player
            placeholder.innerHTML = `
                <div style="padding:56.25% 0 0 0;position:relative;">
                    <iframe 
                        src="https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1" 
                        style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" 
                        allow="autoplay; fullscreen; picture-in-picture" 
                        allowfullscreen>
                    </iframe>
                </div>
            `;
        }
    };

    /**
     * Checklist Download Function
     * Creates and downloads a text file with safety checklist
     */
    function downloadTextFile(filename, content, successMessage) {
        const blob = new Blob([content], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        if (successMessage) {
            alert(successMessage);
        }
    }

    window.downloadChecklist = function() {
        const checklistContent = `
DatePress Safety Checklist
========================

BEFORE YOUR DATE:
□ Tell a friend or family member where you're going
□ Share your date's profile information with someone you trust
□ Plan to meet in a public place
□ Arrange your own transportation
□ Charge your phone fully
□ Have emergency contacts readily available

DURING YOUR DATE:
□ Stay in public areas
□ Keep your drink in sight at all times
□ Trust your instincts - if something feels wrong, leave
□ Don't share personal information (address, workplace details)
□ Keep your phone accessible
□ Stay sober enough to make good decisions

RED FLAGS TO WATCH FOR:
□ Person asks for money or financial help
□ Stories seem inconsistent or don't add up
□ They avoid answering direct questions
□ Pressure to leave public place or go somewhere private
□ Disrespectful or aggressive behavior
□ Reluctance to share basic information about themselves

AFTER YOUR DATE:
□ Let your friend know you're safe
□ Report any concerning behavior to DatePress
□ Block and report if you experienced harassment
□ Trust your gut about meeting again

EMERGENCY CONTACTS:
• Emergency Services: 911
• DatePress Safety Team: support@datepress.com
• National Domestic Violence Hotline: 1-800-799-7233
• Crisis Text Line: Text HOME to 741741

Remember: Your safety is the top priority. Never feel obligated to continue a date that makes you uncomfortable.

Download this checklist from: www.datepress.com/safety-tips
        `;

        downloadTextFile(
            'DatePress-Safety-Checklist.txt',
            checklistContent,
            'Safety checklist downloaded! Keep it handy on your phone for reference.'
        );
    };

    window.downloadScripts = function() {
        const scriptsContent = `
DatePress Safety Conversation Scripts
===================================

BOUNDARY SETTING:
• "I'm enjoying getting to know you here. Let's keep chatting in the app until we meet in person."
• "I'm not comfortable sharing that yet. How about we plan something public first?"

DECLINING INVITATIONS:
• "Thanks for the invite! I'd prefer a daytime meetup at a cafe for our first meeting."
• "Tonight doesn't work for me, but I'm still interested. Let's revisit later this week."

HANDLING PRESSURE:
• "I move at my own pace. If that's not okay, it's best we pause here."
• "I'm not sending money or codes. That's a strict boundary for me."

ESCALATION LANGUAGE:
• "This feels uncomfortable. I'm going to take a break from this conversation."
• "I'm reporting this behavior to the DatePress safety team."

Remember to trust your intuition and use the built-in report feature whenever something feels wrong.
        `;

        downloadTextFile(
            'DatePress-Safety-Scripts.txt',
            scriptsContent,
            'Safety scripts downloaded! Use them as quick prompts when setting boundaries.'
        );
    };

    window.downloadEmergencyDirectory = function() {
        const directoryContent = `
DatePress Global Emergency Directory (Quick Reference)
===================================================

UNITED STATES:
• Emergency Services: 911
• National Sexual Assault Hotline: 1-800-656-HOPE
• National Domestic Violence Hotline: 1-800-799-7233

UNITED KINGDOM:
• Emergency Services: 999
• National Domestic Abuse Helpline: 0808 2000 247
• Samaritans: 116 123

CANADA:
• Emergency Services: 911
• VictimLinkBC: 1-800-563-0808
• Kids Help Phone: 1-800-668-6868

AUSTRALIA:
• Emergency Services: 000
• 1800RESPECT: 1800 737 732
• Lifeline: 13 11 14

GLOBAL DIGITAL RESOURCES:
• Crisis Text Line: Text HOME to 741741 (US/CA/UK/IE)
• DatePress Safety Team: support@datepress.com

Always verify regional numbers before traveling and add them to your phone contacts for fast access.
        `;

        downloadTextFile(
            'DatePress-Global-Emergency-Directory.txt',
            directoryContent,
            'Emergency directory downloaded! Add key numbers to your contacts for quick access.'
        );
    };

    /**
     * Add smooth scrolling for internal links
     */
    function initSmoothScrolling() {
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                const href = this.getAttribute('href');
                if (href !== '#' && document.querySelector(href)) {
                    e.preventDefault();
                    document.querySelector(href).scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }

    /**
     * Enhanced tab switching with animation
     */
    function initTabAnimations() {
        const tabButtons = document.querySelectorAll('.safety-nav-tabs .nav-link');
        tabButtons.forEach(button => {
            button.addEventListener('shown.bs.tab', function (e) {
                const targetPane = document.querySelector(e.target.getAttribute('data-bs-target'));
                if (targetPane) {
                    targetPane.style.opacity = '0';
                    targetPane.style.transform = 'translateY(20px)';
                    setTimeout(() => {
                        targetPane.style.transition = 'all 0.5s ease';
                        targetPane.style.opacity = '1';
                        targetPane.style.transform = 'translateY(0)';
                    }, 10);
                }
            });
        });
    }

    /**
     * Add click handler for video placeholder
     */
    function initVideoPlaceholder() {
        const videoPlaceholder = document.getElementById('videoPlaceholder');
        if (videoPlaceholder) {
            videoPlaceholder.addEventListener('click', window.playVideo);
        }
    }

    /**
     * Initialize all safety tips features
     */
    function init() {
        initCounters();
        initSmoothScrolling();
        initTabAnimations();
        initVideoPlaceholder();
    }

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
