import * as React from 'react';
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { EyeOff, Eye, ArrowUpRight, ShieldCheck, Mail, Lock } from 'lucide-react';

// @ts-ignore
import bridgeBg from './assets/images/danish_bridge_background_1781723138961_1781724106159.jpg';

// Static Data & Translations
import { 
  translations, Language, initialBizzDevices, initialTripHistory, BizzDevice, TripHistory 
} from './types';

// Subcomponents
import LanguageSelector from './components/LanguageSelector';
import MitIDModal from './components/MitIDModal';
import ForgotPasswordModal from './components/ForgotPasswordModal';
import CreateAccountModal from './components/CreateAccountModal';
import HelpPanel from './components/HelpPanel';
import Dashboard from './components/Dashboard';

export default function App() {
  // Locale / Language State
  const [currentLang, setCurrentLang] = useState<Language>('da');
  const t = translations[currentLang];

  // Overlay / Drawer Visibility States
  const [isMitIdOpen, setIsMitIdOpen] = useState(false);
  const [isForgotOpen, setIsForgotOpen] = useState(false);
  const [isRegisterOpen, setIsRegisterOpen] = useState(false);
  const [isHelpOpen, setIsHelpOpen] = useState(false);

  // Authentication State
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userEmail, setUserEmail] = useState('');
  const [userDisplayName, setUserDisplayName] = useState('');

  // Form input States
  const [emailInput, setEmailInput] = useState('');
  const [passwordInput, setPasswordInput] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loginError, setLoginError] = useState('');

  // Memory User Store (Updates dynamically when registering a new user)
  const [registeredUsers, setRegisteredUsers] = useState<Record<string, { pass: string; name: string }>>({
    'test@brobizz.dk': { pass: 'password', name: 'Søren Jensen' },
    'amzod@gmail.com': { pass: 'password', name: 'Geroe Amzod' },
  });

  // Self-Service data states to pass down to Dashboard
  const [bizzDevices, setBizzDevices] = useState<BizzDevice[]>(initialBizzDevices);
  const [tripHistory, setTripHistory] = useState<TripHistory[]>(initialTripHistory);

  // Auto-fill test credentials tip helper (User-friendly feature)
  const handleAutoFill = () => {
    setEmailInput('test@brobizz.dk');
    setPasswordInput('password');
    setLoginError('');
  };

  // Handle standard mail signature login
  const handleLoginSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError('');

    const cleanEmail = emailInput.trim().toLowerCase();
    const userRecord = registeredUsers[cleanEmail];

    if (userRecord && userRecord.pass === passwordInput) {
      setUserEmail(cleanEmail);
      setUserDisplayName(userRecord.name);
      setIsLoggedIn(true);
    } else {
      setLoginError(
        currentLang === 'da'
          ? 'Forkert e-mailadresse eller adgangskode. Prøv igen.'
          : currentLang === 'de'
          ? 'Ungültige E-Mail-Adresse oder Passwort. Bitte versuchen Sie es erneut.'
          : 'Invalid email address or password. Please try again.'
      );
    }
  };

  // Sign out
  const handleSignOut = () => {
    setIsLoggedIn(false);
    setEmailInput('');
    setPasswordInput('');
  };

  // On successful MitID verification
  const handleMitIDSuccess = (fullName: string) => {
    setIsMitIdOpen(false);
    setUserEmail(`${fullName.toLowerCase().replace(/[^a-z0-9]/g, '')}@mitid.dk`);
    setUserDisplayName(fullName);
    setIsLoggedIn(true);
  };

  // Registration callback
  const handleRegisterUser = (email: string, pass: string, name: string) => {
    setRegisteredUsers((prev) => ({
      ...prev,
      [email]: { pass, name },
    }));
    // Pre-fill email for immediate satisfaction
    setEmailInput(email);
    setPasswordInput(pass);
  };

  // If logged in, show the beautiful mock self-service dashboard
  if (isLoggedIn) {
    return (
      <Dashboard
        userEmail={userEmail}
        userDisplayName={userDisplayName}
        bizzDevices={bizzDevices}
        setBizzDevices={setBizzDevices}
        tripHistory={tripHistory}
        setTripHistory={setTripHistory}
        onSignOut={handleSignOut}
        t={t}
        currentLang={currentLang}
        onLanguageChange={setCurrentLang}
        onFAQOpen={() => setIsHelpOpen(true)}
      />
    );
  }

  return (
    <div className="min-h-screen relative flex items-center justify-center font-sans overflow-all selection:bg-emerald-100 p-4 sm:p-6 md:p-8">
      
      {/* PERFECT FULL-SCREEN BACKGROUND IMAGE (Behind the form card) */}
      <div className="absolute inset-0 bg-neutral-950 z-0 overflow-hidden">
        <img
          src={bridgeBg}
          alt="Scenic Storebælt highway bridge crossing in Denmark"
          referrerPolicy="no-referrer"
          className="w-full h-full object-cover opacity-60 scale-100 z-0"
        />
        {/* Deep, highly professional color grading overlay to merge the background with the dark/green Denmark branding */}
        <div className="absolute inset-0 bg-gradient-to-tr from-neutral-950 via-[#031d13]/70 to-neutral-900/50" />
      </div>

      {/* Floating help launcher, bottom-right on dekstop */}
      <div className="absolute bottom-6 right-6 z-10 hidden sm:flex items-center gap-2 bg-neutral-900/40 backdrop-blur-md px-4 py-2 rounded-xl border border-white/10 text-white/80 test-xs">
        <button
          onClick={() => setIsHelpOpen(true)}
          className="hover:text-emerald-400 font-semibold flex items-center gap-1 transition"
        >
          <span>{t.helpLinkText}</span>
          <ArrowUpRight className="w-3.5 h-3.5" />
        </button>
      </div>

      {/* CENTERED LOGIN CARD */}
      <div className="w-full max-w-[460px] bg-white/95 backdrop-blur-lg rounded-2xl flex flex-col justify-between p-6 sm:p-10 z-10 shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] border border-white/20 relative">
        
        {/* Card Header (Logo & Language switcher) */}
        <header className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="font-display font-black text-2xl tracking-tighter text-[#00965e]">Brobizz</span>
          </div>

          <div className="flex items-center gap-2.5">
            <a
              href="/index2.html"
              className="text-[10px] font-mono font-semibold text-[#00965e] hover:text-[#007a4c] bg-emerald-50 hover:bg-emerald-100/70 px-2 py-1.5 rounded-lg transition flex items-center gap-1 border border-emerald-100"
              title="Gå til static HTML Profil"
            >
              <span>Profil HTML</span>
              <ArrowUpRight className="w-2.5 h-2.5" />
            </a>
            <a
              href="/index3.html"
              className="text-[10px] font-mono font-semibold text-[#00965e] hover:text-[#007a4c] bg-emerald-50 hover:bg-emerald-100/70 px-2 py-1.5 rounded-lg transition flex items-center gap-1 border border-emerald-100"
              title="Gå til static HTML Betaling"
            >
              <span>Kort HTML</span>
              <ArrowUpRight className="w-2.5 h-2.5" />
            </a>
            <a
              href="/index1.html"
              className="text-[10px] font-mono font-semibold text-neutral-500 hover:text-[#00965e] bg-neutral-50 hover:bg-neutral-100 px-2 py-1.5 rounded-lg transition flex items-center gap-1 border border-neutral-200"
              title="Skift til den statiske HTML-version"
            >
              <span>HTML</span>
              <ArrowUpRight className="w-2.5 h-2.5" />
            </a>
            <LanguageSelector currentLang={currentLang} onLanguageChange={setCurrentLang} />
          </div>
        </header>

        {/* Central self-service login forms */}
        <div className="my-8 space-y-5">
          <div className="space-y-1">
            <h1 className="text-2xl font-display font-bold text-neutral-900 tracking-tight leading-tight">
              {t.loginHeader}
            </h1>
            <p className="text-[10px] text-neutral-400 font-mono tracking-wider">DENMARK GATEWAY SELF-SERVICE</p>
          </div>

          {/* MitID Login Primary Button */}
          <button
            onClick={() => setIsMitIdOpen(true)}
            className="w-full bg-[#005df9] hover:bg-[#004dc6] text-white font-semibold py-3 px-4 rounded-xl flex items-center justify-center gap-2.5 transition duration-200 shadow-md transform hover:-translate-y-0.5 active:translate-y-0 cursor-pointer text-sm"
          >
            <div className="h-5 w-5 rounded-sm bg-white flex items-center justify-center text-[#005df9] font-black text-[9px] tracking-tighter shrink-0 select-none">
              Mit
            </div>
            <span>{t.mitIdBtn}</span>
          </button>

          {/* Divider with ELLER / OR */}
          <div className="relative flex py-1 items-center">
            <div className="flex-grow border-t border-neutral-200"></div>
            <span className="flex-shrink mx-4 text-[10px] font-mono font-bold text-neutral-400 tracking-widest">{t.dividerOr}</span>
            <div className="flex-grow border-t border-neutral-200"></div>
          </div>

          {/* Email / Password Option Title */}
          <div className="space-y-4">
            <p className="text-xs font-semibold text-neutral-500 text-center uppercase tracking-wide">
              {t.loginSub}
            </p>

            {loginError && (
              <div className="p-3 bg-red-50 border border-red-100 rounded-xl text-xs font-medium text-red-600 animate-pulse">
                {loginError}
              </div>
            )}

            <form onSubmit={handleLoginSubmit} className="space-y-3.5">
              {/* Email Input */}
              <div className="space-y-1">
                <label htmlFor="login-email" className="block text-[10px] font-semibold text-neutral-400 font-mono uppercase tracking-wider">
                  {t.emailLabel}
                </label>
                <div className="relative flex items-center">
                  <Mail className="absolute left-3 w-4 h-4 text-neutral-300" />
                  <input
                    id="login-email"
                    type="email"
                    required
                    value={emailInput}
                    onChange={(e) => {
                      setEmailInput(e.target.value);
                      setLoginError('');
                    }}
                    placeholder={t.emailPlaceholder}
                    className="w-full bg-neutral-50 border border-neutral-200 hover:border-neutral-300 focus:border-neutral-900 focus:bg-white rounded-xl py-2.5 pl-10 pr-4 text-sm text-neutral-800 placeholder-neutral-400 outline-hidden transition duration-150"
                  />
                </div>
              </div>

              {/* Password Input */}
              <div className="space-y-1">
                <label htmlFor="login-pass" className="block text-[10px] font-semibold text-neutral-400 font-mono uppercase tracking-wider">
                  {t.passwordLabel}
                </label>
                <div className="relative flex items-center">
                  <Lock className="absolute left-3 w-4 h-4 text-neutral-300" />
                  <input
                    id="login-pass"
                    type={showPassword ? 'text' : 'password'}
                    required
                    value={passwordInput}
                    onChange={(e) => {
                      setPasswordInput(e.target.value);
                      setLoginError('');
                    }}
                    placeholder={t.passwordPlaceholder}
                    className="w-full bg-neutral-50 border border-neutral-200 hover:border-neutral-300 focus:border-neutral-900 focus:bg-white rounded-xl py-2.5 pl-10 pr-10 text-sm text-neutral-800 placeholder-neutral-400 outline-hidden transition duration-150"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 p-1 text-neutral-400 hover:text-neutral-600 focus:outline-hidden"
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {/* Forgot password */}
              <div className="text-right">
                <button
                  type="button"
                  onClick={() => setIsForgotOpen(true)}
                  className="text-xs font-semibold text-[#00965e] hover:text-[#007a4c] hover:underline"
                >
                  {t.forgotPasswordLink}
                </button>
              </div>

              {/* Next Submit button */}
              <button
                type="submit"
                className="w-full bg-[#00965e] hover:bg-[#007a4c] text-white font-semibold py-3 px-4 rounded-xl flex items-center justify-center transition duration-200 shadow-md mt-4 cursor-pointer text-sm"
              >
                {t.btnNext}
              </button>
            </form>
          </div>
        </div>

        {/* Card Footer: Register user & copyright */}
        <footer className="border-t border-neutral-100 pt-4 flex flex-col sm:flex-row items-center justify-between text-[11px] gap-2">
          <div>
            <span className="text-neutral-400">{t.newCustomerPrefix}</span>
            <button
              onClick={() => setIsRegisterOpen(true)}
              className="font-bold text-[#00965e] hover:text-[#007a4c] hover:underline cursor-pointer"
            >
              {t.newCustomerAction}
            </button>
          </div>

          <span className="font-mono text-[9px] text-neutral-400">© 2026 Brobizz A/S</span>
        </footer>

      </div>

      {/* PORTAL MODALS AND DRAWERS (AnimatePresence allows clean entrances) */}
      <AnimatePresence>
        {isMitIdOpen && (
          <MitIDModal
            isOpen={isMitIdOpen}
            onClose={() => setIsMitIdOpen(false)}
            onSuccess={handleMitIDSuccess}
            t={t}
          />
        )}

        {isForgotOpen && (
          <ForgotPasswordModal
            isOpen={isForgotOpen}
            onClose={() => setIsForgotOpen(false)}
            t={t}
          />
        )}

        {isRegisterOpen && (
          <CreateAccountModal
            isOpen={isRegisterOpen}
            onClose={() => setIsRegisterOpen(false)}
            onRegister={handleRegisterUser}
            t={t}
          />
        )}

        {isHelpOpen && (
          <HelpPanel
            isOpen={isHelpOpen}
            onClose={() => setIsHelpOpen(false)}
            t={t}
          />
        )}
      </AnimatePresence>

    </div>
  );
}
