//! Server-side theme system components
//!
//! Static implementations of theme components optimized for SSR rendering.

use leptos::prelude::*;
// Re-export shared theme types
pub use rustelo_core_lib::ThemeMode;

/// Server-side static theme provider
#[component]
pub fn ThemeProviderSSR(
    #[prop(optional)] default_theme: Option<ThemeMode>,
    #[prop(optional)] language: Option<String>,
    children: leptos::children::ChildrenFn,
) -> impl IntoView {
    let _theme = default_theme.unwrap_or(ThemeMode::Dark);
    let _lang =
        language.unwrap_or_else(|| rustelo_core_lib::config::get_default_language().to_string());

    // For SSR, we provide a static theme context without reactivity
    children()
}

/// Server-side static dark mode toggle.
///
/// Carries htmx attributes so the button is functional under the `htmx-ssr`
/// profile without any client-side WASM. The `/api/htmx/theme/toggle` endpoint
/// (see `rustelo_server::api::htmx`) returns the replacement button plus an
/// out-of-band swap that toggles the `dark` class on `<html>`.
#[component]
pub fn DarkModeToggleSSR(#[prop(optional)] class: Option<String>) -> impl IntoView {
    view! {
        <button
          id="theme-toggle"
          class=format!("ds-theme-toggle btn-icon {}", class.unwrap_or_default())
          aria-label="Toggle theme"
          title="Toggle theme"
          hx-post="/api/htmx/theme/toggle"
          hx-target="this"
          hx-swap="outerHTML"
        >
            <svg
                class="w-4 h-4 theme-light-icon hidden dark:block"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
            >
                <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z">
                </path>
            </svg>
            <svg
                class="w-4 h-4 theme-dark-icon dark:hidden"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
            >
                <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z">
                </path>
            </svg>
        </button>
    }
}

/// SSR Theme Selector - static theme selector
#[component]
pub fn ThemeSelectorSSR(
    #[prop(optional)] current_theme: Option<ThemeMode>,
    #[prop(optional)] language: Option<String>,
) -> impl IntoView {
    let theme = current_theme.unwrap_or(ThemeMode::Dark);
    let lang =
        language.unwrap_or_else(|| rustelo_core_lib::config::get_default_language().to_string());
    // TODO: Replace with proper i18n system when available
    let t = |key: &str| format!("{}[{}]", key, lang);

    let themes = vec![
        (ThemeMode::Light, "☀️", t("theme-light")),
        (ThemeMode::Dark, "🌙", t("theme-dark")),
        (ThemeMode::System, "💻", t("theme-system")),
    ];

    view! {
      <div class="theme-selector-ssr">
        <label class="block text-sm font-medium ds-text mb-2">
          {t("theme-preference")}
        </label>
        <div class="space-y-2">
          {themes.into_iter().map(|(theme_mode, icon, label)| {
            let is_selected = theme_mode == theme;
            view! {
              <div class={format!(
                "flex items-center p-3 ds-rounded ds-bg-secondary {}",
                if is_selected { "ring-2 ring-blue-500" } else { "" }
              )}>
                <div class="flex items-center">
                  <span class="mr-3 text-lg">{icon}</span>
                  <div>
                    <div class="font-medium ds-text">{label}</div>
                    <div class="text-sm ds-text-muted">
                      {match theme_mode {
                        ThemeMode::Light => t("theme-light-desc"),
                        ThemeMode::Dark => t("theme-dark-desc"),
                        ThemeMode::System => t("theme-system-desc"),
                      }}
                    </div>
                  </div>
                </div>
                {is_selected.then(|| view! {
                  <div class="ml-auto text-blue-500">
                    "✓"
                  </div>
                })}
              </div>
            }
          }).collect::<Vec<_>>()}
        </div>
        <p class="text-xs ds-text-muted mt-4">
          {t("theme-selector-requires-js")}
        </p>
      </div>
    }
}

/// SSR Theme Status Display - shows current theme without interactivity
#[component]
pub fn ThemeStatusSSR(
    #[prop(optional)] current_theme: Option<ThemeMode>,
    #[prop(optional)] language: Option<String>,
) -> impl IntoView {
    let theme = current_theme.unwrap_or(ThemeMode::Dark);
    let lang =
        language.unwrap_or_else(|| rustelo_core_lib::config::get_default_language().to_string());
    // TODO: Replace with proper i18n system when available
    let t = |key: &str| format!("{}[{}]", key, lang);

    let theme_name = match theme {
        ThemeMode::Light => t("theme-light"),
        ThemeMode::Dark => t("theme-dark"),
        ThemeMode::System => t("theme-system"),
    };

    let theme_icon = match theme {
        ThemeMode::Light => "☀️",
        ThemeMode::Dark => "🌙",
        ThemeMode::System => "💻",
    };

    view! {
      <div class="flex items-center space-x-2 text-sm ds-text-secondary">
        <span>{theme_icon}</span>
        <span>{t("current-theme")}: {theme_name}</span>
      </div>
    }
}

/// Hook-like function for SSR theme context (returns static values)
pub fn use_theme_ssr(default: Option<ThemeMode>) -> ThemeContextSSR {
    ThemeContextSSR {
        theme_mode: default.unwrap_or(ThemeMode::Dark),
        is_dark: matches!(default, Some(ThemeMode::Dark) | None),
    }
}

/// SSR Theme Context (static, non-reactive)
#[derive(Clone, Debug)]
pub struct ThemeContextSSR {
    pub theme_mode: ThemeMode,
    pub is_dark: bool,
}

impl ThemeContextSSR {
    pub fn new(theme_mode: ThemeMode) -> Self {
        Self {
            theme_mode,
            is_dark: matches!(theme_mode, ThemeMode::Dark),
        }
    }

    pub fn get_css_classes(&self) -> Vec<&'static str> {
        match self.theme_mode {
            ThemeMode::Light => vec!["theme-light"],
            ThemeMode::Dark => vec!["theme-dark", "dark"],
            ThemeMode::System => vec!["theme-system"],
        }
    }

    pub fn get_meta_theme_color(&self) -> &'static str {
        match self.theme_mode {
            ThemeMode::Light => "#ffffff",
            ThemeMode::Dark => "#0f172a",
            ThemeMode::System => "#0f172a", // Default to dark for SSR
        }
    }
}
