'use client';

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

export default function Home() {
  const [loggedIn, setLoggedIn] = useState(false);
  const [password, setPassword] = useState('');

  useEffect(() => {
    if (localStorage.getItem('auth')) setLoggedIn(true);
  }, []);

  const handleLogin = async () => {
    const response = await fetch('/api/auth', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ password }),
    });
    if (response.ok) {
      const auth = btoa(`admin:${password}`);
      localStorage.setItem('auth', auth);
      setLoggedIn(true);
    } else {
      alert('Wrong password');
    }
  };

  if (!loggedIn) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-blue-50 to-gray-100">
        <div className="bg-white p-10 rounded-xl shadow-xl w-96">
          <h1 className="text-3xl font-bold mb-8 text-center text-gray-800">Login to Mail S3 Admin</h1>
          <input 
            type="password" 
            value={password} 
            onChange={e => setPassword(e.target.value)} 
            className="border border-gray-300 p-4 mb-6 w-full rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
            placeholder="Enter password"
          />
          <button 
            onClick={handleLogin} 
            className="bg-blue-600 text-white p-4 rounded-lg w-full hover:bg-blue-700 transition font-medium"
          >
            Login
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-blue-50 to-gray-100 p-8">
      <h1 className="text-4xl font-bold mb-8 text-center text-gray-800">Mail S3 Admin</h1>
      <div className="flex justify-center">
        <Link href="/domains" className="bg-blue-600 text-white px-8 py-4 rounded-lg hover:bg-blue-700 transition shadow-md font-medium">
          Go to Domains
        </Link>
      </div>
    </div>
  );
}