import {
	Links, 
	LiveReload,
	Meta,
	Outlet,
	Scripts,
	ScrollRestoration,
} from "@remix-run/react"
import { useState, useEffect } from "react"

import Header from "~/components/header"
import Footer from "~/components/footer"

import stylesheet from "~/tailwind.css"

export const meta = () => {
	return {
		charset: "utf-8",
		title: "Eversafe",
		viewport: "width=device-width,initial-scale=1",
	}
}

export const links = () => [
	{ 
		rel: "stylesheet", 
		href: stylesheet 
	}
]

export default function App() {
	const [ carrito, setCarrito ] = useState(typeof window !== 'undefined' && JSON.parse(localStorage.getItem('carrito')) || [])
	const [ carritoMedida, setCarritoMedida ] = useState(typeof window !== 'undefined' && JSON.parse(localStorage.getItem('carritoMedida')) || [])
	const [ cantCarrito, setCantCarrito ] = useState(0)
	const [ cantCarritoMedida, setCantCarritoMedida ] = useState(0)

	const [ seguridad, setSeguridad ] = useState(false)
    const [ acorazada, setAcorazada ] = useState(false)
    const [ balistica, setBalistica ] = useState(false)
	const [ granero, setGranero ] = useState(false)
    const [ deck, setDeck ] = useState(false)
    const [ pisoLaminado, setPisoLaminado ] = useState(false)
    const [ otros, setOtros ] = useState(false)
	const [ cpEntrega, setCpEntrega ] = useState("")
    
    useEffect(() => {
        if (typeof window !== 'undefined') {
            localStorage.setItem('carrito', JSON.stringify(carrito))
        }
		setCantCarrito(carrito.length)
    }, [carrito])

	useEffect(() => {
        if (typeof window !== 'undefined') {
            localStorage.setItem('carritoMedida', JSON.stringify(carritoMedida))
        }
		if( typeof carritoMedida.length === 'undefined' || carritoMedida.length < 14 ) {
			setCantCarritoMedida(0)
		} else {
			setCantCarritoMedida(1)
		}
    }, [carritoMedida])

    const agregarCarrito = puerta => {
        if ( carrito?.some( puertaState => puertaState.id === puerta.id ) ){
            // Identifiacar elemento duplicado
            const carritoActualizado = carrito?.map( puertaState => {
                if(puertaState.id === puerta.id) {
                    puertaState.cantidad = puerta.cantidad
                }
                return puertaState
            })
            setCarrito(carritoActualizado)
        } else {
            setCarrito([...carrito, puerta])
        }
    }
    const actualizarCantidad = puerta => {
        const carritoActualizado = carrito?.map(puertaState => {
            if(puertaState.id === puerta.id) {
                puertaState.cantidad = puerta.cantidad
            }
            return puertaState
        })
        setCarrito(carritoActualizado)
    }
    const eliminarPuerta = id => {
        const carritoActualizado = carrito?.filter( puertaState => puertaState.id !== id )
        setCarrito(carritoActualizado)
    }
	const eliminarPuertaMedida = id => {
		setCarritoMedida([])
		setCantCarritoMedida(0)
	}
	const eliminarSmart = id => {
        const carritoActualizado = carrito?.filter( puertaState => {
			if ( puertaState.id === id ) {
				puertaState.smart = {}
				return puertaState
			} else {
				return puertaState
			} 
		})
        setCarrito(carritoActualizado)
    }

	useEffect(() => {
		const importTE = async () => {
			await import("tw-elements")
		}
		importTE()
	}, [])
	
	return(
		<Document cantCarrito={cantCarrito} cantCarritoMedida={cantCarritoMedida}>
			<Outlet
                context={{
                    agregarCarrito,
					cantCarrito,
					cantCarritoMedida,
                    carrito,
					setCarrito,
					carritoMedida, 
					setCarritoMedida, 
                    actualizarCantidad,
					cpEntrega, 
					setCpEntrega,
                    eliminarPuerta, 
					eliminarPuertaMedida, 
					eliminarSmart, 
					seguridad, 
					setSeguridad, 
					acorazada, 
					setAcorazada, 
					balistica, 
					setBalistica, 
					granero, 
					setGranero, 
					deck, 
					setDeck, 
					pisoLaminado, 
					setPisoLaminado, 
					otros, 
					setOtros
                }}
            />
		</Document>
	)
} 

const Document = ({children, cantCarrito, cantCarritoMedida}) => {
	useEffect( () => {
		/* Cliengo */
		const cliengo = () => { 
			const ldk = document.createElement('script'); 
			ldk.type = 'text/javascript'; 
			ldk.async = true; 
			ldk.src = 'https://s.cliengo.com/weboptimizer/64a98bd5061e550032c5824f/64a98bd7061e550032c58252.js?platform=dashboard'; 
			var s = document.getElementsByTagName('script')[0]; 
			s.parentNode.insertBefore(ldk, s); 
		}

		/* Analytics */
		window.dataLayer = window.dataLayer || []; 
		function gtag(){
			dataLayer.push(arguments);
		} 
		gtag('js', new Date()); 
		gtag('config', 'G-9CSCM1Z6VW'); 
		

		cliengo()
	}, [])
	return (
		<html lang="es">
			<head>
				<Meta />
				<Links />
				{/* Código de instalación Cliengo para https://eversafe.com.mx/ */} 
			</head>
			<body>
				<Header cantCarrito={cantCarrito} cantCarritoMedida={cantCarritoMedida} />
				{children}
				<Footer />
				<ScrollRestoration />
				<Scripts />
				<LiveReload />
				<script type="text/javascript" src="https://cdn.conekta.io/js/latest/conekta.js"></script>
				<script async src="https://www.googletagmanager.com/gtag/js?id=G-9CSCM1Z6VW"></script>
			</body>
		</html>
	)
}