'use client';

import { useState, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Heart, KeyRound } from 'lucide-react';
import { toast } from '@/hooks/use-toast';

const CORRECT_PASSWORD = '040125';
const STORAGE_KEY = 'app_authenticated_v2';

export default function PasswordGate({ children }: { children: React.ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    try {
      const storedAuth = localStorage.getItem(STORAGE_KEY);
      if (storedAuth === 'true') {
        setIsAuthenticated(true);
      }
    } catch (error) {
      console.error("Could not access local storage", error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const handlePasswordSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (password === CORRECT_PASSWORD) {
      try {
        localStorage.setItem(STORAGE_KEY, 'true');
      } catch (error) {
         console.error("Could not write to local storage", error);
      }
      setIsAuthenticated(true);
       toast({
        title: "¡Bienvenida, mi amor!",
        description: "Espero que te guste este pequeño rincón para nosotros.",
      });
    } else {
      toast({
        variant: "destructive",
        title: "Código Incorrecto",
        description: "Inténtalo de nuevo. ¡Piensa en una fecha especial!",
      });
      setPassword('');
    }
  };

  if (isLoading) {
    return (
        <div className="h-screen w-screen flex items-center justify-center bg-background">
            <Heart className="w-16 h-16 text-primary animate-pulse" />
        </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-hero-gradient flex items-center justify-center p-4">
        <Card className="max-w-sm w-full bg-card/90 backdrop-blur-lg shadow-2xl animate-in fade-in zoom-in-95">
          <CardHeader className="text-center">
            <div className="flex justify-center mb-4">
              <div className="relative">
                <Heart className="w-12 h-12 text-gradient drop-shadow-lg animate-heart-beat" />
                 <KeyRound className="w-5 h-5 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white/80"/>
              </div>
            </div>
            <CardTitle className="font-headline text-2xl text-gradient">
              Un Lugar Solo Para Nosotros
            </CardTitle>
            <CardDescription className="font-body text-foreground/70 pt-1">
              Introduce el código secreto para entrar.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handlePasswordSubmit} className="space-y-4">
              <Input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Código"
                className="text-center text-lg font-mono tracking-widest h-12 placeholder:text-foreground/40"
                autoFocus
              />
              <Button type="submit" className="w-full font-body text-lg" size="lg">
                Entrar
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    );
  }

  return <>{children}</>;
}
