// Game chrome components: login, menu, toggles, status bars
const { useState } = React;

function LoginOverlay({ onSignIn, isLoading }) {
    const [showEmailForm, setShowEmailForm] = useState(false);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isSignUp, setIsSignUp] = useState(false);
    const [authError, setAuthError] = useState('');
    const [submitting, setSubmitting] = useState(false);

    const handleEmailSubmit = async (e) => {
        e.preventDefault();
        setAuthError('');
        setSubmitting(true);
        try {
            if (isSignUp) {
                await firebaseClient.signUpWithEmail(email, password);
                if (typeof gtag === 'function') gtag('event', 'sign_up', { method: 'email' });
            } else {
                await firebaseClient.signInWithEmail(email, password);
                if (typeof gtag === 'function') gtag('event', 'login', { method: 'email' });
            }
            setShowEmailForm(false);
        } catch (error) {
            setAuthError(error.message);
            if (typeof gtag === 'function') gtag('event', 'auth_error', { method: 'email', action: isSignUp ? 'sign_up' : 'login', error_code: error.code || 'unknown' });
        } finally {
            setSubmitting(false);
        }
    };

    const handleGoogleSignIn = async () => {
        setAuthError('');
        setSubmitting(true);
        try {
            await onSignIn('google');
        } catch (error) {
            console.error('[LoginOverlay] Google sign-in error:', error);
            setAuthError(error.message);
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <div className="login-overlay">
            <div className="login-modal">
                <h1>RISK</h1>
                <div className="tagline">Simulate anything, anywhere</div>

                {!showEmailForm ? (
                    <>
                        <button
                            onClick={handleGoogleSignIn}
                            disabled={isLoading || submitting}
                            className="login-btn-google"
                        >
                            <svg className="w-5 h-5" viewBox="0 0 24 24">
                                <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                                <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                                <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                                <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                            </svg>
                            Continue with Google
                        </button>

                        <div className="divider">or</div>

                        <button
                            onClick={() => setShowEmailForm(true)}
                            className="login-btn-email"
                        >
                            Sign in with email
                        </button>

                        {authError && (
                            <div className="login-error mt-4">{authError}</div>
                        )}

                    </>
                ) : (
                    <form onSubmit={handleEmailSubmit} className="login-form">
                        <input
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            placeholder="Email address"
                            required
                            disabled={submitting}
                        />
                        <input
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder="Password"
                            required
                            disabled={submitting}
                        />

                        {authError && (
                            <div className="login-error">{authError}</div>
                        )}

                        <button
                            type="submit"
                            disabled={submitting}
                            className="login-submit-btn"
                        >
                            {submitting ? 'Loading...' : (isSignUp ? 'Create account' : 'Sign in')}
                        </button>

                        <button
                            type="button"
                            onClick={() => {
                                setShowEmailForm(false);
                                setAuthError('');
                            }}
                            className="login-submit-btn login-back-btn"
                            disabled={submitting}
                        >
                            Back
                        </button>

                        <div className="login-toggle">
                            {isSignUp ? (
                                <>Already have an account? <button type="button" onClick={() => setIsSignUp(false)}>Sign in</button></>
                            ) : (
                                <>No account yet? <button type="button" onClick={() => setIsSignUp(true)}>Create one</button></>
                            )}
                        </div>
                    </form>
                )}
            </div>
        </div>
    );
}

function GameMenu({ user, onSignOut, onNewGame, gamePhase, inline }) {
    const [isOpen, setIsOpen] = useState(false);
    const [confirmNewGame, setConfirmNewGame] = useState(false);

    const handleNewGame = () => {
        if (gamePhase === 'playing') {
            setConfirmNewGame(true);
        } else {
            onNewGame();
            setIsOpen(false);
        }
    };

    const confirmAndStartNew = () => {
        onNewGame();
        setConfirmNewGame(false);
        setIsOpen(false);
    };

    return (
        <div className={`game-menu ${inline ? 'game-menu--inline' : ''}`}>
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="menu-toggle"
                title="Menu"
            >
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <line x1="3" y1="6" x2="21" y2="6"></line>
                    <line x1="3" y1="12" x2="21" y2="12"></line>
                    <line x1="3" y1="18" x2="21" y2="18"></line>
                </svg>
            </button>

            {isOpen && (
                <>
                    <div className="menu-backdrop" onClick={() => { setIsOpen(false); setConfirmNewGame(false); }}></div>
                    <div className="menu-dropdown">
                        <div className="menu-header">
                            {user.photoURL && (
                                <img src={user.photoURL} alt="" className="menu-avatar" />
                            )}
                            <div className="menu-user-info">
                                <div className="menu-user-name">{user.displayName || 'Player'}</div>
                                <div className="menu-user-email">{user.email}</div>
                            </div>
                        </div>

                        <div className="menu-divider"></div>

                        {!confirmNewGame ? (
                            <>
                                <button className="menu-item" onClick={handleNewGame}>
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                        <path d="M12 5v14M5 12h14"></path>
                                    </svg>
                                    New game
                                </button>
                                <button className="menu-item menu-item-danger" onClick={onSignOut}>
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                                        <polyline points="16 17 21 12 16 7"></polyline>
                                        <line x1="21" y1="12" x2="9" y2="12"></line>
                                    </svg>
                                    Sign out
                                </button>
                            </>
                        ) : (
                            <div className="menu-confirm">
                                <div className="menu-confirm-text">
                                    Your current game will be lost. Continue?
                                </div>
                                <div className="menu-confirm-buttons">
                                    <button className="menu-btn menu-btn-danger" onClick={confirmAndStartNew}>
                                        Yes, new game
                                    </button>
                                    <button className="menu-btn" onClick={() => setConfirmNewGame(false)}>
                                        Cancel
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </>
            )}
        </div>
    );
}
