"use client"
import Image from 'next/image'
import SiteLogo from "@/public/images/site-logo.webp";
import { useAuthStore } from '@/zustand/auth/useAuthStore';
import { getCookie, setCookie } from "cookies-next";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

type Props = {
    children: React.ReactNode
}

const layout = ({ children }: Props) => {
    const { language, setLanguage } = useAuthStore();
    const router = useRouter()

    useEffect(() => {
        const lang = getCookie('language') as string || 'en';
        setLanguage(lang);
    }, []);

    const handleLanguage = () => {
        const html = document.documentElement;
        const lang = language === 'en' ? 'ar' : 'en';

        setLanguage(lang);

        if (lang === 'ar') {
            html.classList.add('rtl');
            html.setAttribute('dir', 'rtl');
            html.setAttribute('lang', 'ar');
        } else {
            html.classList.remove('rtl');
            html.setAttribute('dir', 'ltr');
            html.setAttribute('lang', 'en');
        }

        setCookie('language', lang, {
            path: '/',
            maxAge: 60 * 60 * 24 * 365,
        });
        router.refresh();
    };
    return (
        <div className="flex flex-col justify-center max-w-[580px] mx-auto py-4 md:py-6 xl:py-12 px-4">
            <div className='flex justify-between items-center mb-5 lg:mb-8 2xl:mb-15'>
                <div className='min-w-12 opacity-0'></div>

                <div className="max-h-20 flex justify-center">
                    <Image src={SiteLogo} width={169} height={63} alt="SiteLogo" />
                </div>
                <div className="relative inline-block group">
                    <button
                        type="button"
                        className=" inline-flex items-center gap-2 rounded-md border border-grey2b bg-secondary px-3 py-1.5 text-sm font-medium text-light focus:outline-none cursor-pointer duration-300 ease-in-out hover:bg-primary hover:text-white"
                        onClick={handleLanguage}
                    >
                        {`${language === 'en' ? 'AR' : 'EN'}`}
                    </button>
                </div>
            </div>

            <div className="border bg-secondary border-grey2b p-4 lg:p-5 xl:p-7.5 rounded-md">
                {children}
            </div>
        </div>
    )
}

export default layout