'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-gray-100">
        <div className="bg-white p-8 rounded-lg shadow-md w-96">
          <h1 className="text-2xl font-bold mb-6 text-center">Login</h1>
          <input 
            type="password" 
            value={password} 
            onChange={e => setPassword(e.target.value)} 
            className="border border-gray-300 p-3 mb-4 w-full rounded focus:outline-none focus:ring-2 focus:ring-blue-500" 
            placeholder="Enter password"
          />
          <button 
            onClick={handleLogin} 
            className="bg-blue-500 text-white p-3 rounded w-full hover:bg-blue-600 transition"
          >
            Login
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 p-8">
      <h1 className="text-3xl font-bold mb-6 text-center">Mail S3 Admin</h1>
      <div className="flex justify-center">
        <Link href="/domains" className="bg-blue-500 text-white px-6 py-3 rounded hover:bg-blue-600 transition">
          Go to Domains
        </Link>
      </div>
    </div>
  );
}