﻿import { useState } from 'react';
import { Navbar } from './components/Navbar';
import { Generator } from './components/Generator';
import { LoginView } from './components/LoginView';
import { HistoryView } from './components/HistoryView';
import { KittyGame } from './components/KittyGame';
import { FlappyCat } from './components/FlappyCat';
import { useAuth } from './hooks/useAuth';

export type View = 'home' | 'login' | 'history' | 'jump-game' | 'flappy-game';

const getSubdomain = () => {
    const hostname = window.location.hostname;
    // Handle localhost and 127.0.0.1 cases.
    // For more advanced cases (like bare IP hosting)
    // a regex may be necessary.
    if (hostname === 'localhost' || hostname === '127.0.0.1') {
        return null;
    }
    
    const parts = hostname.split('.');
    if (parts.length <= 2) return null;
    return parts[0];
};

function App() {
    const [url, setUrl] = useState('');
    const [view, setView] = useState<View>('home');
    const { isAuthenticated, logout } = useAuth();
    const subdomain = getSubdomain();

    /**
     * STAN POCHODNY (Derived State)
     * Rozwiązuje błąd "cascading renders". Jeśli użytkownik jest na subdomenie
     * i nie jest zalogowany, automatycznie renderujemy widok logowania,
     * ale nie nadpisujemy stanu 'view' w nieskończoność.
     */
    const activeView = (subdomain && !isAuthenticated) ? 'login' : view;

    const renderView = () => {
        switch (activeView) {
            case 'login':
                return (
                    <LoginView
                        onBack={() => setView('home')}
                        onSuccess={() => setView('home')}
                    />
                );
            case 'history':
                // Strażnik dostępu dla widoku historii
                if (!isAuthenticated) {
                    return <LoginView onBack={() => setView('home')} onSuccess={() => setView('home')} />;
                }
                return <HistoryView onBack={() => setView('home')} />;
            case 'jump-game':
                return <KittyGame onBack={() => setView('home')} />;
            case 'flappy-game':
                return <FlappyCat onBack={() => setView('home')} />;
            default:
                return <Generator url={url} setUrl={setUrl} onGenerate={() => alert('Meow!')} />;
        }
    };

    return (
        <div className="min-h-screen bg-[#fff5f8] text-slate-700 font-sans">
            <Navbar
                onNavigate={(v: View) => setView(v)}
                isAuthenticated={isAuthenticated}
                onLogout={logout}
            />
            <main>
                {/* Jeśli użytkownik jest zalogowany (SSO), activeView od razu 
                  pokaże Generator, zamiast LoginView.
                */}
                {renderView()}
            </main>
        </div>
    );
}

export default App;