"use client";

import { useState, useEffect } from "react";
import Link from "next/link";

export default function CookieAlert() {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        // Check if cookie exists
        const cookieExists = document.cookie
            .split("; ")
            .find((row) => row.startsWith("acceptCookies="));

        if (!cookieExists) {
            setIsVisible(true);
        }
    }, []);

    const acceptCookies = () => {
        // Set cookie for 365 days
        const date = new Date();
        date.setTime(date.getTime() + 365 * 24 * 60 * 60 * 1000);
        document.cookie = `acceptCookies=true; expires=${date.toUTCString()}; path=/`;

        setIsVisible(false);
    };

    if (!isVisible) return null;

    return (
        <div className="cookiealert shadow-lg show">
            <p className="mb-4">
                We use cookies for the best experience on our website.{" "}
                <Link href="#" target="_blank">
                    Cookies Policy.
                </Link>
            </p>
            <button
                className="btn btn-primary btn-sm acceptcookies"
                type="button"
                aria-label="Close"
                onClick={acceptCookies}
            >
                Accept
            </button>
        </div>
    );
}
