interface SiteConfig {
    phoneDigits: string;
    phoneIntlDigits: string;
    phoneDisplay: string;
    email: string;
    websiteUrl: string;
    websiteDisplay: string;
    facebookUrl: string;
    instagramUrl: string;
    addressHtml: string;
    nextUrl: string;
}

const SITE_CONFIG: SiteConfig = {
    phoneDigits: '9549806839',
    phoneIntlDigits: '19549806839',
    phoneDisplay: '(954) 980-6839',
    email: 'sac@goldensunshinepool.com',
    websiteUrl: 'https://www.goldensunshinepool.com',
    websiteDisplay: 'www.goldensunshinepool.com',
    facebookUrl: '',
    instagramUrl: '',
    addressHtml: '13820 Alexandria Ct<br>Davie, Florida - 33325',
    nextUrl: 'https://www.goldensunshinepool.com'
};

function resolveContactLink(linkType: string): string {
    switch (linkType) {
        case 'phone':    return `tel:${SITE_CONFIG.phoneDigits}`;
        case 'whatsapp': return `https://wa.me/${SITE_CONFIG.phoneIntlDigits}`;
        case 'email':    return `mailto:${SITE_CONFIG.email}`;
        case 'website':  return SITE_CONFIG.websiteUrl;
        case 'facebook': return SITE_CONFIG.facebookUrl;
        case 'instagram': return SITE_CONFIG.instagramUrl;
        default: return '';
    }
}

function applySiteConfig(): void {
    document.querySelectorAll<HTMLAnchorElement>('[data-contact-link]').forEach((element) => {
        const linkType = element.dataset.contactLink ?? '';
        const href = resolveContactLink(linkType);

        if (href) {
            element.setAttribute('href', href);
            element.removeAttribute('aria-hidden');
            element.style.removeProperty('display');
        } else if (linkType === 'facebook' || linkType === 'instagram') {
            element.setAttribute('aria-hidden', 'true');
            element.style.display = 'none';
        }

        if (element.getAttribute('target') === '_blank') {
            element.setAttribute('rel', 'noopener noreferrer');
        }
    });

    document.querySelectorAll<HTMLElement>('[data-contact-text]').forEach((element) => {
        const key = element.dataset.contactText as keyof SiteConfig | undefined;
        if (key && key in SITE_CONFIG) {
            element.textContent = SITE_CONFIG[key];
        }
    });

    document.querySelectorAll<HTMLElement>('[data-contact-html]').forEach((element) => {
        const key = element.dataset.contactHtml as keyof SiteConfig | undefined;
        if (key && key in SITE_CONFIG) {
            element.innerHTML = SITE_CONFIG[key];
        }
    });

    document.querySelectorAll<HTMLInputElement>('[data-contact-value]').forEach((element) => {
        const key = element.dataset.contactValue as keyof SiteConfig | undefined;
        if (key && key in SITE_CONFIG) {
            element.value = SITE_CONFIG[key];
        }
    });
}

function setupMobileNavigation(): void {
    const nav = document.getElementById('nav');
    const mobileMenuButton = document.getElementById('mobile-menu-btn');

    if (!nav || !mobileMenuButton) return;

    function setMenuState(isOpen: boolean): void {
        nav!.classList.toggle('active', isOpen);
        mobileMenuButton!.setAttribute('aria-expanded', String(isOpen));
    }

    mobileMenuButton.addEventListener('click', () => {
        setMenuState(!nav!.classList.contains('active'));
    });

    document.addEventListener('keydown', (event: KeyboardEvent) => {
        if (event.key === 'Escape') setMenuState(false);
    });

    document.addEventListener('click', (event: MouseEvent) => {
        if (!nav!.classList.contains('active')) return;
        const target = event.target as Element | null;
        if (target?.closest('#nav') || target?.closest('#mobile-menu-btn')) return;
        setMenuState(false);
    });

    document.querySelectorAll<HTMLAnchorElement>('a[href^="#"]').forEach((anchor) => {
        anchor.addEventListener('click', function (event: MouseEvent) {
            event.preventDefault();
            const href = this.getAttribute('href');
            const target = href ? document.querySelector<HTMLElement>(href) : null;
            if (target) {
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                setMenuState(false);
            }
        });
    });
}

function setupHeaderScrollEffect(): void {
    const header = document.getElementById('header');
    if (!header) return;

    let ticking = false;
    window.addEventListener('scroll', () => {
        if (ticking) return;
        ticking = true;
        requestAnimationFrame(() => {
            header.classList.toggle('scrolled', window.scrollY > 50);
            ticking = false;
        });
    }, { passive: true });
}

function setupContactForm(): void {
    const form = document.getElementById('contact-form') as HTMLFormElement | null;
    const status = document.getElementById('contact-form-status');

    if (!form || !status) return;

    form.addEventListener('submit', async (event: SubmitEvent) => {
        event.preventDefault();

        const submitButton = form.querySelector<HTMLButtonElement>('button[type="submit"]');
        const data = new FormData(form);

        status.style.display = 'block';
        status.style.color = '';
        status.textContent = 'Sending your message...';
        if (submitButton) submitButton.disabled = true;

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                body: data,
                headers: { Accept: 'application/json' }
            });

            if (response.ok) {
                form.reset();
                status.style.color = '#1f7a3a';
                status.textContent = "Thanks! Your message has been sent. We'll be in touch soon.";
            } else {
                const result = await response.json().catch(() => ({})) as { errors?: { message: string }[] };
                const message = Array.isArray(result.errors) && result.errors.length
                    ? result.errors.map((err) => err.message).join(', ')
                    : 'Something went wrong. Please try again or call us directly.';
                status.style.color = '#b00020';
                status.textContent = message;
            }
        } catch {
            status.style.color = '#b00020';
            status.textContent = 'Network error. Please try again or call us directly.';
        } finally {
            if (submitButton) submitButton.disabled = false;
        }
    });
}

applySiteConfig();
setupMobileNavigation();
setupHeaderScrollEffect();
setupContactForm();
