import { useState, useEffect, ReactNode } from 'react';
import styles from './password-gate.module.scss';
import Head from 'next/head';
import { useRouter } from 'next/router';

const HARDCODED_PASSWORD = 'GONI';
const STORAGE_KEY = 'site-authenticated';

interface Props {
  children: ReactNode;
}

export default function PasswordGate({ children }: Props) {
  const [authenticated, setAuthenticated] = useState(false);
  const [checked, setChecked] = useState(false);
  const [password, setPassword] = useState('');
  const [error, setError] = useState(false);
  const router = useRouter();

  const checkAuth = () => {
    const stored = sessionStorage.getItem(STORAGE_KEY);
    setAuthenticated(stored === 'true');
    setChecked(true);
  };

    useEffect(() => {
        checkAuth();
        // Revalida en cada cambio de ruta (navegación con Link)
        router.events.on('routeChangeStart', checkAuth);

        return () => {
        router.events.off('routeChangeStart', checkAuth);
        };
    }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (password === HARDCODED_PASSWORD) {
        sessionStorage.setItem(STORAGE_KEY, 'true');
        setAuthenticated(true);
        setError(false);
        setPassword('');
    } else {
        setError(true);
    }
  };

  // evita parpadeo mientras se verifica sessionStorage
  if (!checked) return null;

  if (!authenticated) {
    return (
        <>
            <Head>
                <title>Arturo Goñi</title>
                <link rel="shortcut icon" href="/favicon.ico?v=1" />
                <link
                    href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,100;1,200;1,300;1,400;1,500;1,600&display=swap"
                    rel="stylesheet"
                />
            </Head>
            <div className={ styles.passwordGate }>
                <header className={styles.passwordGate__header}>
                    <div className="header-logo">
                        Goñi
                    </div>
                </header>
                <form onSubmit={ handleSubmit }>
                    <h2>Content Protected</h2>
                    <p>Unlock content</p>
                    <input
                        id="password"
                        type="password"
                        value={ password }
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder='Enter Password'
                        autoFocus
                    />
                    {error && <span>Incorrect Password</span>}
                    <button type="submit">
                        Send
                        <svg width="12" height="19" viewBox="0 0 12 19" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 8V11L0 19V16L9.75 9.5L0 3V0L12 8Z" fill="black"/>
                        </svg>
                    </button>
                </form>
            </div>
        </>
    );
  }

  return <>{children}</>;
}