'use client';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

type Role = 'brand' | 'influencer' | 'admin';

const getCookie = (name: string) => {
    if (typeof document === 'undefined') return '';
    const hit = document.cookie.split('; ').find((r) => r.startsWith(`${name}=`));
    return hit ? decodeURIComponent(hit.split('=')[1]) : '';
};

export default function NotFound() {
    const [backHref, setBackHref] = useState('/login');
    const [backLabel, setBackLabel] = useState('Back to login');

    useEffect(() => {
        document.title = '404 - Page Not Found';

        // tokens used in your middleware
        const bat = !!getCookie('bat');
        const iat = !!getCookie('iat');
        const aat = !!getCookie('aat');
        const verifyUAT = !!getCookie('verifyUAT');
        const isLoggedIn = bat || iat || aat || verifyUAT;

        // try to get role from user_info, else infer from token
        let role: Role | undefined;
        const rawUserInfo = getCookie('user_info');
        if (rawUserInfo) {
            try {
                const info = JSON.parse(rawUserInfo);
                if (['brand', 'influencer', 'admin'].includes(info?.role)) {
                    role = info.role as Role;
                }
            } catch {
                /* ignore parse errors */
            }
        }
        if (!role) {
            if (aat || verifyUAT) role = 'admin';
            else if (iat || verifyUAT) role = 'influencer';
            else if (bat || verifyUAT) role = 'brand';
        }

        if (isLoggedIn) {
            setBackHref(role ? `/${role}/dashboard` : '/');
            setBackLabel('Back to dashboard');
        } else {
            setBackHref('/login');
            setBackLabel('Back to login');
        }
    }, []);

    return (
        <div className="min-h-screen flex items-center justify-center bg-gray/10 px-4">
            <div className="text-center max-w-md">
                <div className="mb-6">
                    <Image src="/assets/images/logo.png" width={300} height={50} alt="404" className='mx-auto' />
                </div>
                <h1 className="text-7xl font-bold mb-4 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
                    404
                </h1>
                <h2 className="text-2xl font-semibold text-gray-800 mb-2">Page Not Found</h2>
                <p className="text-black/50 font-medium mb-6 text-lg">
                    Sorry, the page you are looking for doesn't exist
                </p>
                <Link
                    href={backHref}
                    className="inline-block bg-gradient-to-br from-secondary to-primary text-white font-medium px-6 py-3 rounded-full transition"
                >
                    {backLabel}
                </Link>
            </div>
        </div>
    );
}
