//! Kurulum sırasında gösterilen slayt gösterisi.
//!
//! Her slayt: başlık, açıklama metni ve isteğe bağlı bir simge karakteri.
//! Slaytlar otomatik olarak 6 saniyede bir değişir.
//! Masaüstü ortamına göre farklı slayt setleri yüklenebilir.

use eframe::egui;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use rust_i18n::t;
use std::borrow::Cow;

const SLIDE_INTERVAL: Duration = Duration::from_secs(6);

pub struct Slide {
    pub icon:        &'static str,
    pub title:       Cow<'static, str>,
    pub description: Cow<'static, str>,
}

/// Masaüstü ortamına göre slayt seti döner.
/// ISO meta verisi ileride `/etc/livecd-desktop` gibi bir dosyadan okunabilir.
pub fn slides_for_desktop(desktop: &str, branding_slides: &[crate::branding::SlideItem]) -> Vec<Slide> {
    if !branding_slides.is_empty() {
        branding_slides
            .iter()
            .filter(|item| item.desktop.is_empty() || item.desktop.to_lowercase() == desktop.to_lowercase())
            .map(|item| Slide {
                icon: Box::leak(item.icon.clone().into_boxed_str()),
                title: Cow::Owned(item.title.clone()),
                description: Cow::Owned(item.description.clone()),
            })
            .collect()
    } else {
        let mut slides = default_slides();
        let specific_slides = match desktop {
            "budgie"         => budgie_slides(),
            "cinnamon"       => cinnamon_slides(),
            "gnome"          => gnome_slides(),
            "kde" | "plasma" => kde_slides(),
            "lxde"           => lxde_slides(),
            "lxqt"           => lxqt_slides(),
            "lumina"         => lumina_slides(),
            "mate"           => mate_slides(),
            "xfce"           => xfce_slides(),
            _                => vec![],
        };
        slides.extend(specific_slides);
        slides
    }
}

fn default_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "pisilogo",
            title:       t!("welcome_slide_title"),
            description: t!("welcome_slide_description"),
        },
        Slide {
            icon:        "pisi",
            title:       t!("package_manager_title"),
            description: t!("package_manager_description"),
        },
        Slide {
            icon:        "community",
            title:       t!("community_title"),
            description: t!("community_description"),
        },
        Slide {
            icon:        "pisi_speed",
            title:       t!("speed_title"),
            description: t!("speed_description"),
        },
        Slide {
            icon:        "securety",
            title:       t!("security_title"),
            description: t!("security_description"),
        },
        Slide {
            icon:        "customization",
            title:       t!("customization_title"),
            description: t!("customization_description"),
        },
    ]
}

fn budgie_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "budgie",
            title:       t!("budgie_title"),
            description: t!("budgie_description"),
        },
        Slide {
            icon:        "budgie_applets",
            title:       t!("budgie_applets_title"),
            description: t!("budgie_applets_description"),
        },
        Slide {
            icon:        "budgie_raven",
            title:       t!("budgie_raven_title"),
            description: t!("budgie_raven_description"),
        },
        Slide {
            icon:        "budgie_gtk_theme",
            title:       t!("budgie_gtk_theme_title"),
            description: t!("budgie_gtk_theme_description"),
        },
    ]
}

fn cinnamon_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "cinnamon",
            title:       t!("cinnamon_title"),
            description: t!("cinnamon_description"),
        },
        Slide {
            icon:        "cinnamon_panel",
            title:       t!("cinnamon_panel_title"),
            description: t!("cinnamon_panel_description"),
        },
        Slide {
            icon:        "cinnamon_settings",
            title:       t!("cinnamon_settings_title"),
            description: t!("cinnamon_settings_description"),
        },
        Slide {
            icon:        "cinnamon_desklets",
            title:       t!("cinnamon_desklets_title"),
            description: t!("cinnamon_desklets_description"),
        },
    ]
}

fn gnome_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "gnome",
            title:       t!("gnome_title"),
            description: t!("gnome_description"),
        },
        Slide {
            icon:        "gnome_search",
            title:       t!("gnome_search_title"),
            description: t!("gnome_search_description"),
        },
        Slide {
            icon:        "gnome_extensions",
            title:       t!("gnome_extensions_title"),
            description: t!("gnome_extensions_description"),
        },
    ]
}

fn kde_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "kde",
            title:       t!("kde_title"),
            description: t!("kde_description"),
        },
        Slide {
            icon:        "file_manager",
            title:       t!("dolphin_title"),
            description: t!("dolphin_description"),
        },
        Slide {
            icon:        "kde_connect",
            title:       t!("kde_connect_title"),
            description: t!("kde_connect_description"),
        },
        Slide {
            icon:        "discover",
            title:       t!("discover_title"),
            description: t!("discover_description"),
        },
    ]
}

fn lxde_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "lxde",
            title:       t!("lxde_title"),
            description: t!("lxde_description"),
        },
        Slide {
            icon:        "lxde_openbox",
            title:       t!("lxde_openbox_title"),
            description: t!("lxde_openbox_description"),
        },
        Slide {
            icon:        "file_manager",
            title:       t!("lxde_pcmanfm_title"),
            description: t!("lxde_pcmanfm_description"),
        },
        Slide {
            icon:        "lxde_lxpanel",
            title:       t!("lxde_lxpanel_title"),
            description: t!("lxde_lxpanel_description"),
        },
    ]
}

fn lxqt_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "lxqt",
            title:       t!("lxqt_title"),
            description: t!("lxqt_description"),
        },
        Slide {
            icon:        "lxqt_panel",
            title:       t!("lxqt_panel_title"),
            description: t!("lxqt_panel_description"),
        },
        Slide {
            icon:        "file_manager",
            title:       t!("lxqt_pcmanfm_qt_title"),
            description: t!("lxqt_pcmanfm_qt_description"),
        },
    ]
}

fn lumina_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "lumina",
            title:       t!("lumina_title"),
            description: t!("lumina_description"),
        },
        Slide {
            icon:        "lumina_applications",
            title:       t!("lumina_applications_title"),
            description: t!("lumina_applications_description"),
        },
        Slide {
            icon:        "lumina_theme",
            title:       t!("lumina_theme_title"),
            description: t!("lumina_theme_description"),
        },
        Slide {
            icon:        "lumina_panel",
            title:       t!("lumina_panel_title"),
            description: t!("lumina_panel_description"),
        },
    ]
}

fn mate_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "mate",
            title:       t!("mate_title"),
            description: t!("mate_description"),
        },
        Slide {
            icon:        "file_manager",
            title:       t!("mate_caja_title"),
            description: t!("mate_caja_description"),
        },
        Slide {
            icon:        "mate_settings",
            title:       t!("mate_settings_title"),
            description: t!("mate_settings_description"),
        },
        Slide {
            icon:        "mate_applications",
            title:       t!("mate_applications_title"),
            description: t!("mate_applications_description"),
        },
    ]
}

fn xfce_slides() -> Vec<Slide> {
    vec![
        Slide {
            icon:        "xfce",
            title:       t!("xfce_title"),
            description: t!("xfce_description"),
        },
        Slide {
            icon:        "xfce_panel",
            title:       t!("xfce_panel_title"),
            description: t!("xfce_panel_description"),
        },
        Slide {
            icon:        "file_manager",
            title:       t!("xfce_thunar_title"),
            description: t!("xfce_thunar_description"),
        },
        Slide {
            icon:        "xfce_settings",
            title:       t!("xfce_settings_title"),
            description: t!("xfce_settings_description"),
        },
    ]
}


// ─── Slayt gösterisi widget'ı ───────────────────────────────────────────

pub struct Slideshow {
    slides:       Vec<Slide>,
    current:      usize,
    last_advance: Instant,
    /// branding.toml'dan gelen ikon-adı → `file://` URI eşlemesi
    icons:        HashMap<String, String>,
}

impl Slideshow {
    pub fn new(desktop: &str, icons: HashMap<String, String>, branding_slides: Vec<crate::branding::SlideItem>) -> Self {
        Self {
            slides:       slides_for_desktop(desktop, &branding_slides),
            current:      0,
            last_advance: Instant::now(),
            icons,
        }
    }

    /// Her frame'de çağrılır. Otomatik ilerlemeyi ve çizimi yönetir.
    pub fn show(&mut self, ui: &mut egui::Ui) {
        // Otomatik ilerleme
        if self.last_advance.elapsed() >= SLIDE_INTERVAL {
            self.current = (self.current + 1) % self.slides.len();
            self.last_advance = Instant::now();
            ui.ctx().request_repaint_after(SLIDE_INTERVAL);
        } else {
            // Bir sonraki değişime kadar geri sayım için tekrar çiz
            let remaining = SLIDE_INTERVAL
                .checked_sub(self.last_advance.elapsed())
                .unwrap_or_default();
            ui.ctx().request_repaint_after(remaining);
        }

        let slide = &self.slides[self.current];

        // İkona karşılık gelen URI'yi branding haritasından al
        let resolved_uri = self.icons.get(slide.icon).cloned();

        egui::Frame::none()
            .fill(crate::ui::theme::c_bg_widget())
            .rounding(egui::Rounding::same(10.0))
            .inner_margin(egui::Margin::same(24.0))
            .show(ui, |ui| {
                ui.set_min_height(180.0);
                ui.vertical_centered(|ui| {
                    // Simge veya Görsel
                    if let Some(uri) = resolved_uri {
                        ui.add(
                            egui::Image::from_uri(uri)
                                .max_height(64.0)
                                .rounding(egui::Rounding::same(8.0)),
                        );
                    } else {
                        ui.label(
                            egui::RichText::new(slide.icon)
                                .size(48.0),
                        );
                    }
                    ui.add_space(10.0);

                    // Başlık
                    ui.label(
                        egui::RichText::new(slide.title.clone())
                            .size(17.0)
                            .strong()
                            .color(crate::ui::theme::c_text()),
                    );
                    ui.add_space(8.0);

                    // Açıklama
                    ui.label(
                        egui::RichText::new(slide.description.clone())
                            .size(13.0)
                            .color(crate::ui::theme::c_text_dim()),
                    );

                    ui.add_space(16.0);

                    // Nokta göstergesi
                    ui.horizontal(|ui| {
                        let dot_size = egui::vec2(8.0, 8.0);
                        for i in 0..self.slides.len() {
                            let color = if i == self.current {
                                crate::ui::theme::c_accent()
                            } else {
                                crate::ui::theme::c_border()
                            };
                            let (rect, response) = ui.allocate_exact_size(dot_size, egui::Sense::click());
                            ui.painter().circle_filled(rect.center(), 4.0, color);
                            if response.clicked() {
                                self.current = i;
                                self.last_advance = Instant::now();
                            }
                            ui.add_space(4.0);
                        }
                    });
                });
            });
    }

    pub fn advance(&mut self) {
        self.current = (self.current + 1) % self.slides.len();
        self.last_advance = Instant::now();
    }

    pub fn previous(&mut self) {
        if self.current == 0 {
            self.current = self.slides.len() - 1;
        } else {
            self.current -= 1;
        }
        self.last_advance = Instant::now();
    }
}
