import { useState, useEffect } from "react"
import { __ } from '@wordpress/i18n'

const App = () => {    

    const storeUrl = vajofoCartWidgetLocalizer.storeUrl

    const cartUrl = storeUrl + '/#/cart'

    if (storeUrl.length === 0) {
        return null
    }

    const [cartItemsCount, setCartItemsCount] = useState(0)
    const [isCartPage, setIsCartPage] = useState(false)

    const getCartItemsCount = () => {

        // Get initial cart items count from localStorage
        const cartData = localStorage.getItem('olenaCartItems')

        if (cartData) {
            const items = JSON.parse(cartData)            

            setCartItemsCount(Array.isArray(items) ? items.length : 0)
        } else {
            setCartItemsCount(0)
        }
    }
    
    const handleRouterChangedEvent = (event) => {

        if (event.detail.type === 'OLENA_ROUTER_CHANGED') {

            getCartItemsCount()            
            
            if (window.location.href.includes(cartUrl)) {

                setIsCartPage(true)
            } else {

                setIsCartPage(false)
            }
        }
    }    

    const handleStoreChangedEvent = (event) => {

        if (event.detail.type === 'OLENA_STORE_CHANGED') {
            
            getCartItemsCount()
        }
    };

    useEffect(() => {

        getCartItemsCount();

        // Add event listener
        document.addEventListener('olenaStoreChangedEvent', handleStoreChangedEvent);
        document.addEventListener('olenaRouterChangedEvent', handleRouterChangedEvent);
    }, []);

    return (
        isCartPage ? null : (
        <div className="ofo-cart-button-wrapper">
            <a href={cartUrl} className="ofo-cart-button">
                <span className="ofo-cart-button-amount-number">{cartItemsCount}</span>
                <svg className="cart-icon" viewBox="0 0 24 24"><path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"></path></svg>
                </a>
            </div>
        )
    )
}

export default App
