use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::path;
use leptos_router::{
    components::{Route, Router, Routes, Redirect},
    StaticSegment,
};
use crate::page::{PricesPage, ProxyPage, SharesPage, ReviewsPage, BlogPage, LoginPage, RegisterPage, TelegramLoginPage, TelegramRegisterPage, ProfilePage, TermsPage, NotFound, TermsAndRulesPage, PrivacyPolicyPage, RulesPage, TermsPageRu, PrivacyPolicyPageRu, RulesPageRu};
use crate::components::blog::ArticlePage;
use crate::components::{ForgotPasswordPage, PasswordRecoveryPage, EmailConfirmPage};
use crate::components::navigation::Header;
use crate::components::footer::Footer;
use crate::components::referral_tracking::{ReferralTrackingProvider, ReferralTracker};
use crate::components::wasm_guard::WasmGuard;
use crate::auth::provide_auth_context;
use crate::i18n::{provide_language_context, provide_translation_context};
use crate::{log_info, log_component};

pub fn shell(options: LeptosOptions) -> impl IntoView {
    view! {
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8"/>
                <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
                <meta name="backend-url" content="https://vproxy.cc/api"/>
                <AutoReload options=options.clone() />
                <HydrationScripts options/>
                <MetaTags/>
                <link rel="preconnect" href="https://fonts.googleapis.com"/>
                <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin=""/>
                <link rel="prefetch" href="/bg-planet.svg"/>
                <link rel="icon" type="image/png" href="/favicon.png"/>

                <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet"/>
                <script src="https://cdn.tailwindcss.com"></script>
                <script src="/tailwind-config.js"></script>
                <link href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css" rel="stylesheet"/>
            </head>
            <body>
                <App/>
            </body>
        </html>
    }
}

#[component]
pub fn App() -> impl IntoView {
    provide_meta_context();
    let auth_state = provide_auth_context();
    let lang_context = provide_language_context();
    let _translation_context = provide_translation_context();
    
    #[cfg(feature = "hydrate")]
    {
        let auth_for_restore = auth_state.clone();
        let lang_for_restore = lang_context.clone();
        Effect::new(move |_| {
            auth_for_restore.restore_from_storage();
            lang_for_restore.restore_from_storage();
            
            // Load translations from server (without sending keys)
            spawn_local(async move {
                if let Err(e) = crate::i18n::load_translations_from_server().await {
                    log::error!("Failed to load translations from server: {}", e);
                } else {
                    log::info!("Translations loaded from server successfully");
                }
            });
        });
    }
    
    {
        let lang_sync = lang_context.clone();
        let auth_sync = auth_state.clone();
        Effect::new(move |_| {
            if auth_sync.is_authenticated.get() {
                lang_sync.update_from_profile();
            }
        });
    }
    
    log_component!(created, "App");
    log_info!("VProxy application initialized");

    view! {
        <Stylesheet id="leptos" href="/pkg/vproxy-web.css"/>
        <Title text="VProxy - Premium Proxy Service"/>

        <WasmGuard>
            <ReferralTrackingProvider>
                <Router>
                    <ReferralTracker/>
                    <Header/>
                    <main>
                        <Routes fallback=|| view! { <NotFound/> }>
                            // Redirect root "/" to "/ru"
                            <Route path=StaticSegment("") view=|| view! { <Redirect path="/ru"/> } />
                           
                            // English routes
                            <Route path=(StaticSegment("en"), StaticSegment("")) view=PricesPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("prices")) view=PricesPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("proxy")) view=ProxyPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("shares")) view=SharesPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("reviews")) view=ReviewsPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("blog")) view=BlogPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("blog"), StaticSegment("write")) view=BlogPage/>
                            <Route path=path!("/en/blog/edit/:id") view=BlogPage/>
                            <Route path=path!("/en/blog/article/:id") view=ArticlePage/>
                            <Route path=(StaticSegment("en"), StaticSegment("login")) view=LoginPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("register")) view=RegisterPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("forgot-password")) view=ForgotPasswordPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("password-recovery")) view=PasswordRecoveryPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("confirm-email")) view=EmailConfirmPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("telegram-login")) view=TelegramLoginPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("telegram-register")) view=TelegramRegisterPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("profile")) view=ProfilePage/>
                            <Route path=(StaticSegment("en"), StaticSegment("terms-and-rules")) view=TermsAndRulesPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("terms")) view=TermsPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("privacy")) view=PrivacyPolicyPage/>
                            <Route path=(StaticSegment("en"), StaticSegment("rules")) view=RulesPage/>
                            
                            // Russian routes 
                            <Route path=(StaticSegment("ru"), StaticSegment("")) view=PricesPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("prices")) view=PricesPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("proxy")) view=ProxyPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("shares")) view=SharesPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("reviews")) view=ReviewsPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("blog")) view=BlogPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("blog"), StaticSegment("write")) view=BlogPage/>
                            <Route path=path!("/ru/blog/edit/:id") view=BlogPage/>
                            <Route path=path!("/ru/blog/article/:id") view=ArticlePage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("login")) view=LoginPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("register")) view=RegisterPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("forgot-password")) view=ForgotPasswordPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("password-recovery")) view=PasswordRecoveryPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("confirm-email")) view=EmailConfirmPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("telegram-login")) view=TelegramLoginPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("telegram-register")) view=TelegramRegisterPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("profile")) view=ProfilePage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("terms-and-rules")) view=TermsAndRulesPage/>
                            <Route path=(StaticSegment("ru"), StaticSegment("terms")) view=TermsPageRu/>
                            <Route path=(StaticSegment("ru"), StaticSegment("privacy")) view=PrivacyPolicyPageRu/>
                            <Route path=(StaticSegment("ru"), StaticSegment("rules")) view=RulesPageRu/>
                        </Routes>
                    </main>
                    <Footer/>
                </Router>
            </ReferralTrackingProvider>
        </WasmGuard>
    }
}

