import { useState, useEffect } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import Navigation from './nav/Navigation.tsx';
const LOGO_WHITE = import.meta.env.VITE_LOGO_WHITE; 
interface HeaderProperties {
    facebook: string;
    twitter: string;
    instagram: string;
    youtube: string;
    tiktok: string;
    pintrest: string;
    about: string;
    address: string;
    phone: string;
    email: string;
    copy: string;
    whatsapp: string;
    whatsappMessage: string;
}
const Header = ({ LOGO, apiUrl }: { LOGO: string, apiUrl: string; }) => {
    const [properties, setHeaderProperties] = useState<HeaderProperties | null>(null);
    const [loading, setLoading] = useState(true);
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [isSticky, setIsSticky] = useState<boolean>(false);
    const location = useLocation();
    const isHomePage = location.pathname === '/';;

    const toggleMenu = () => {
        setIsMenuOpen((prevState) => !prevState);
        document.body.classList.toggle('fix', !isMenuOpen);
    };
    const hidePopup = () => {
        setIsMenuOpen(false);
        document.body.classList.remove('fix');
    };
    useEffect(() => {
         const fetchHeaderProperties = async () => {
            try {
                const response = await fetch(apiUrl);
                const data = await response.json();
                setHeaderProperties(data); // Assuming the data is in the expected format
                setLoading(false);
            } catch (error) {
                console.error("Error fetching properties:", error);
                setLoading(false);
            }
        };

        fetchHeaderProperties();

        const handleScroll = () => {
            if (isHomePage) {
                if (window.scrollY > 80) {
                    setIsSticky(true);
                } else {
                    setIsSticky(false);
                }
            }
        };

        // Check scroll position on first load
        handleScroll();

        // Attach scroll listener
        window.addEventListener('scroll', handleScroll);

        // Cleanup listener on component unmount
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, [isHomePage, apiUrl]); // Ensure effect runs when `isHomePage` changes
    if (loading || !properties) return null;
    const isActiveLink = (path: string) => location.pathname.startsWith(path);

    return (
        <header
            id="header"
            className={`header ${isSticky ? 'sticky' : ''} ${isHomePage ? 'no-inner   inner-home' : 'inner-page sticky '} ${
            ['/es', '/en', '/ru', '/fr'].some((prefix) => location.pathname === prefix || location.pathname.startsWith(`${prefix}/`)) ? 'logo-content-center' : ''
            } clearfix`}
        >
            <div className="header the-new-header">
                <div className="container11 auto-container111  pl15 pr15">
                    <div className="row item-list-header">
                        <div className="col col-sm-12 col-md-12 header-left">
                            <NavLink 
                                to={['/es', '/en', '/ru', '/fr'].find((prefix) => location.pathname === prefix || location.pathname.startsWith(`${prefix}/`)) || "/"} 
                                className="logo"
                            >
                                <img
                                    width="710"
                                    height="96"
                                    src={!isSticky && isHomePage ? LOGO_WHITE : LOGO}
                                    className="attachment-full size-full"
                                    alt=""
                                />
                            </NavLink>


                            {!['/es', '/en', '/ru', '/fr'].some((prefix) => location.pathname === prefix || location.pathname.startsWith(`${prefix}/`)) && (
                                <>
                                    <ul className="items hide-on-mobile">
                                     
                                        <li>
                                            <NavLink
                                                to="/for-sale"
                                                className={({ isActive }) => isActive || isActiveLink('/sale/') ? 'active' : ''}
                                            >
                                                Buy
                                            </NavLink>
                                        </li>
                                        <li>
                                            <NavLink
                                                to="/for-rent"
                                                className={({ isActive }) => isActive || isActiveLink('/rent/') ? 'active' : ''}
                                            >
                                                Rent
                                            </NavLink>
                                        </li>
                                        <li>
                                            <NavLink
                                                to="/offplan-properties-for-sale"
                                                className={({ isActive }) => isActive || isActiveLink('/offplan-project/') ? 'active' : ''}

                                            >
                                                Off-Plan
                                            </NavLink>
                                        </li>
                                        <li>
                                            <NavLink
                                                to="/property-management-services"
                                                className={({ isActive }) => (isActive ? 'active' : '')}
                                            >
                                                Property Management
                                            </NavLink>
                                        </li>
                                        <li>
                                            <NavLink
                                                to="/faqs"
                                                className={({ isActive }) => (isActive ? 'active' : '')}
                                            >
                                                FAQ's
                                            </NavLink>
                                        </li>
                                        <li>
                                            <NavLink
                                                to="article/about-us"
                                                className={({ isActive }) => (isActive ? 'active' : '')}
                                            >
                                                About Us
                                            </NavLink>
                                        </li>
                                        <li>
                                            <NavLink
                                                to="/contact-us"
                                                className={({ isActive }) => (isActive ? 'active' : '')}
                                            >
                                                Contact Us
                                            </NavLink>
                                        </li>
                                    </ul>

                                    <div className="header__content">
                                        <div className="whatsapp-burger">
                                            <NavLink
                                                to={`https://wa.me/${properties?.whatsapp?.replace('+', '')}?text=${encodeURIComponent(properties.whatsappMessage)}`}
                                                className={({ isActive }) => (isActive ? 'active' : '')}
                                            >
                                                <img src="/assets/images/whatsapp.png" alt="WhatsApp Us" />
                                                <span className="whats_app-text">WhatsApp</span>
                                            </NavLink>
                                        </div>
                                        <div className="header__menu">
                                            <div id="google_translate_element"></div>
                                            <div
                                                className="header__menu-burger btn-menu"
                                                onClick={toggleMenu}
                                                data-burger-menu=""
                                            >
                                                <div className="header__menu-burger-container">
                                                    <div className="header__menu-burger">
                                                        <svg xmlns="http://www.w3.org/2000/svg"
                                                            className="attachment-full size-full"
                                                            width="40" height="40" viewBox="0 0 20 20"
                                                        >
                                                            <g>
                                                                <path
                                                                    fill="currentColor"
                                                                    d="M3 5a1 1 0 0 1 1-1h12a1 1 0 1 1 0 2H4a1 1 0 0 1-1-1zm0 5a1 1 0 0 1 1-1h6a1 1 0 1 1 0 2H4a1 1 0 0 1-1-1zm0 5a1 1 0 0 1 1-1h12a1 1 0 0 1 0 2H4a1 1 0 0 1-1-1z"
                                                                    opacity="1"
                                                                />
                                                            </g>
                                                        </svg>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </>
                            )}

                        </div>
                    </div>
                </div>
            </div>

            <div
                className={`full-block mobile-nav ${isMenuOpen ? 'open' : ''}`}
                style={{ display: 'none' }}
            >
                <div className="full-block overlay">
                    <div className="mobile-nav-inner">
                        <div className="menu-holder-inside">
                            <div className="inner-header-1">
                                <a href="/" className="logo">
                                    <img
                                        width="710"
                                        height="96"
                                        src={LOGO}
                                        className="attachment-full size-full"
                                        alt=""
                                    />
                                </a>

                                <div className="mobile-buttons">
                                    <a
                                        href="#"
                                        className="btn-menu open"
                                        onClick={toggleMenu}
                                    >
                                        <span className="menu-icon">
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                        </span>
                                    </a>
                                </div>
                            </div>
                            <Navigation hidePopup={hidePopup}  />

                            
                        </div>
                    </div>
                </div>
            </div>
        </header>
    );
};

export default Header;
