//! PisiLinux kurulum teması.
//!
//! PisiLinux renk paleti:
//!   Ana mavi : #1A6FA8   Vurgu mavi: #2196F3
//!   Koyu arka: #050b0c18   Panel arka : #252535
//!   Kenarlık : #3A3A5C   Metin      : #E0E0F0
//!   Yeşil    : #4CAF50   Kırmızı    : #F44336
//!   Sarı     : #FF9800

use eframe::egui::{self, Color32, FontId, Rounding, Stroke, Vec2, Visuals};

use std::sync::atomic::{AtomicU32, Ordering};

// ─── Renk Atomics ──────────────────────────────────────────────
static BG_DARK:    AtomicU32 = AtomicU32::new(0x121214);
static BG_PANEL:   AtomicU32 = AtomicU32::new(0x1A1A1E);
static BG_WIDGET:  AtomicU32 = AtomicU32::new(0x242428);
static BG_FOOTER:  AtomicU32 = AtomicU32::new(0x121214);


static BORDER:     AtomicU32 = AtomicU32::new(0x323238);
static TEXT:       AtomicU32 = AtomicU32::new(0xF3F3F5);
static TEXT_DIM:   AtomicU32 = AtomicU32::new(0x9E9EAF);
static SUCCESS:    AtomicU32 = AtomicU32::new(0x4CAF50);
static WARNING:    AtomicU32 = AtomicU32::new(0xFF9800);
static ERROR:      AtomicU32 = AtomicU32::new(0xF44336);
static SIDEBAR:    AtomicU32 = AtomicU32::new(0x0B0B0D);
static ACCENT_COLOR: AtomicU32 = AtomicU32::new(0xd9005b); // Pisi Premium Vurgu (#d9005b)
static SIDEBAR_TEXT: AtomicU32 = AtomicU32::new(0x000000);
static KEYBOARD_BG: AtomicU32 = AtomicU32::new(0xFFFFFF);
static BG_ROOT: AtomicU32 = AtomicU32::new(0x1A1A1E);




// Helper to convert hex to Color32
fn color_from_hex(rgb: u32) -> Color32 {
    Color32::from_rgb((rgb >> 16) as u8, ((rgb >> 8) & 0xFF) as u8, (rgb & 0xFF) as u8)
}

pub fn c_bg_dark() -> Color32   { color_from_hex(BG_DARK.load(Ordering::Relaxed)) }
pub fn c_bg_panel() -> Color32  { color_from_hex(BG_PANEL.load(Ordering::Relaxed)) }
pub fn c_bg_widget() -> Color32 { color_from_hex(BG_WIDGET.load(Ordering::Relaxed)) }
pub fn c_border() -> Color32    { color_from_hex(BORDER.load(Ordering::Relaxed)) }
pub fn c_text() -> Color32      { color_from_hex(TEXT.load(Ordering::Relaxed)) }
pub fn c_text_dim() -> Color32  { color_from_hex(TEXT_DIM.load(Ordering::Relaxed)) }
pub fn c_success() -> Color32   { color_from_hex(SUCCESS.load(Ordering::Relaxed)) }
pub fn c_warning() -> Color32   { color_from_hex(WARNING.load(Ordering::Relaxed)) }
pub fn c_error() -> Color32     { color_from_hex(ERROR.load(Ordering::Relaxed)) }
pub fn c_sidebar() -> Color32   { color_from_hex(SIDEBAR.load(Ordering::Relaxed)) }
pub fn c_sidebar_text() -> Color32 { color_from_hex(SIDEBAR_TEXT.load(Ordering::Relaxed)) }
pub fn c_footer_bg() -> Color32 { color_from_hex(BG_FOOTER.load(Ordering::Relaxed)) }
pub fn c_root_bg() -> Color32 { color_from_hex(BG_ROOT.load(Ordering::Relaxed)) }
pub fn c_keyboard_bg() -> Color32 { color_from_hex(KEYBOARD_BG.load(Ordering::Relaxed)) }

pub fn set_theme_mode(is_dark: bool) {
    if is_dark {
        BG_FOOTER.store(0x121214, Ordering::Relaxed);
        BG_DARK.store(0x121214, Ordering::Relaxed);
        BG_PANEL.store(0x1A1A1E, Ordering::Relaxed);
        BG_WIDGET.store(0x242428, Ordering::Relaxed);
        BORDER.store(0x323238, Ordering::Relaxed);
        TEXT.store(0xF3F3F5, Ordering::Relaxed); // #F3F3F5
        TEXT_DIM.store(0x9E9EAF, Ordering::Relaxed); // #9E9EAF
        SIDEBAR.store(0x0B0B0D, Ordering::Relaxed);
        SIDEBAR_TEXT.store(0xffffff, Ordering::Relaxed);
        KEYBOARD_BG.store(0x000000, Ordering::Relaxed);
        BG_ROOT.store(0x1A1A1E, Ordering::Relaxed);
    } else {
        BG_FOOTER.store(0xf7f7f7, Ordering::Relaxed);
        BG_DARK.store(0xf7f7f7, Ordering::Relaxed);
        SIDEBAR.store(0x292f34, Ordering::Relaxed);
        TEXT.store(0x000000, Ordering::Relaxed); // #000000
        TEXT_DIM.store(0x000000, Ordering::Relaxed); // #000000
        SIDEBAR_TEXT.store(0xffffff, Ordering::Relaxed);
        KEYBOARD_BG.store(0xffffff, Ordering::Relaxed);
        BG_ROOT.store(0xf7f7f7, Ordering::Relaxed);

        //BG_DARK.store(0xF0F0F5, Ordering::Relaxed);
        BG_PANEL.store(0xFFFFFF, Ordering::Relaxed);
        BG_WIDGET.store(0xE8E8EE, Ordering::Relaxed);
        BORDER.store(0xD0D0DA, Ordering::Relaxed);
        //TEXT.store(0x20202A, Ordering::Relaxed); // #20202A
        //TEXT_DIM.store(0x60606A, Ordering::Relaxed); // #60606A
        //SIDEBAR.store(0xE4E4EA, Ordering::Relaxed);
    }
}


pub fn c_accent() -> Color32 {
    let rgb = ACCENT_COLOR.load(std::sync::atomic::Ordering::Relaxed);
    Color32::from_rgb((rgb >> 16) as u8, ((rgb >> 8) & 0xFF) as u8, (rgb & 0xFF) as u8)
}

pub fn c_accent_dim() -> Color32 {
    let rgb = ACCENT_COLOR.load(std::sync::atomic::Ordering::Relaxed);
    let r = (((rgb >> 16) & 0xFF) as f32 * 0.8) as u8;
    let g = (((rgb >> 8) & 0xFF) as f32 * 0.8) as u8;
    let b = ((rgb & 0xFF) as f32 * 0.8) as u8;
    Color32::from_rgb(r, g, b)
}

/// egui bağlamına PisiLinux temasını uygular.
/// `cc.egui_ctx` üzerinden `setup_custom_fonts` ve `set_visuals` çağrısını birleştirir.
pub fn apply(ctx: &egui::Context, is_dark: bool) {
    setup_fonts(ctx);
    ctx.set_style(build_style());
    ctx.set_visuals(build_visuals(is_dark));
}

fn setup_fonts(ctx: &egui::Context) {
    let mut fonts = egui::FontDefinitions::default();

    // 1. ADIM: Sadece Metin (Text) Fontunu Bul ve Yükle
    let text_font_paths = [
        "/usr/share/fonts/TTF/OpenSans-Regular.ttf",
        "/usr/share/fonts/noto/NotoSans-Regular.ttf",
        "/usr/share/fonts/exo-1/Exo-Regular.otf",
        "/usr/share/fonts/exo-1/Exo2-Medium.ttf",
        "/usr/share/fonts/exo-1/Exo-Medium.otf",
    ];

    for path in text_font_paths {
        if let Ok(data) = std::fs::read(path) {
            fonts.font_data.insert(
                "system_text_font".to_owned(),
                egui::FontData::from_owned(data),
            );
            
            // Metin fontunu en başa (0. indeks) koyuyoruz ki varsayılan olarak bu kullanılsın
            fonts
                .families
                .entry(egui::FontFamily::Proportional)
                .or_default()
                .insert(0, "system_text_font".to_owned());
            break;
        }
    }

    // 2. ADIM: Renkli Emoji Fontunu Ara ve "Fallback" (Yedek) Olarak Sona Ekle
    // ISO ortamlarında Noto Color Emoji genellikle bu yollardan birinde olur
    let emoji_font_paths = [
        "/usr/share/fonts/noto/NotoColorEmoji.ttf",
    ];

    for path in emoji_font_paths {
        if let Ok(data) = std::fs::read(path) {
            fonts.font_data.insert(
                "system_emoji_font".to_owned(),
                egui::FontData::from_owned(data),
            );

            // ÖNEMLİ: Emojiyi listenin SONUNA (push ile) ekliyoruz.
            // Böylece egui normal harfleri sistem fontuyla yazacak, 
            // harf sistem fontunda yoksa (yani emojiyse) gidip bu fonttan alacak.
            fonts
                .families
                .entry(egui::FontFamily::Proportional)
                .or_default()
                .push("system_emoji_font".to_owned());
                
            fonts
                .families
                .entry(egui::FontFamily::Monospace)
                .or_default()
                .insert(0, "system_emoji_font".to_owned());
            break;
        }
    }

    ctx.set_fonts(fonts);
}



fn build_visuals(is_dark: bool) -> Visuals {
    let mut v = if is_dark { Visuals::dark() } else { Visuals::light() };

    // Genel arka planlar
    v.window_fill        = c_bg_dark();
    v.panel_fill         = c_bg_panel();
    v.faint_bg_color     = c_bg_widget();
    v.extreme_bg_color   = c_sidebar();
    v.code_bg_color      = if is_dark { Color32::from_rgb(0x18, 0x18, 0x28) } else { Color32::from_rgb(0xEE, 0xEE, 0xF5) };

    // Metin
    v.override_text_color = None;

    // ─── KENARLIKLAR (Calamares Uyumu için İnce İnce Yumuşatıldı) ───────────────────
    v.widgets.noninteractive.bg_stroke = Stroke::new(1.0, c_border());

    // ─── WIDGET DOLGULARI (Burası ComboBox ve Butonların Kaderini Belirliyor) ───────
    v.widgets.noninteractive.bg_fill = c_bg_widget();
    
    // Pasif Hali: Widget arka planı (TextEdit, ComboBox giriş alanı)
    v.widgets.inactive.bg_fill       = if is_dark { Color32::from_rgb(255, 255, 255) } else { Color32::from_rgb(245, 245, 245) };
    
    // Üzerine Gelme Hali: Hafif açık
    v.widgets.hovered.bg_fill        = if is_dark { Color32::from_rgb(55, 58, 68) } else { Color32::from_rgb(235, 235, 235) };
    
    // Tıklanma/Açık Kalma Hali: Daha açık
    v.widgets.active.bg_fill         = if is_dark { Color32::WHITE } else { Color32::from_rgb(230, 230, 230) };

    // ComboBox stilleri (combobox_stil.rs)
    crate::ui::combobox_stil::apply_visuals(&mut v);

    // ─── METİN RENKLERİ ────────────────────────────────────────────────────────────
    v.widgets.noninteractive.fg_stroke = Stroke::new(1.0, c_text());

    // ─── YUVARLAK KÖŞELER (Zaten 6.0'dı, Tam İstediğin Calamares Kıvamında) ─────────
    v.widgets.noninteractive.rounding = Rounding::same(6.0);
    v.widgets.inactive.rounding       = Rounding::same(6.0);
    v.widgets.hovered.rounding        = Rounding::same(6.0);
    v.widgets.active.rounding         = Rounding::same(6.0);

    // Seçim rengi
    v.selection.bg_fill  = c_accent_dim();
    v.selection.stroke   = Stroke::new(1.0, c_accent());

    // Hyperlink
    v.hyperlink_color = c_accent();

    // Pencere kenarlığı
    v.window_stroke   = Stroke::new(1.0, c_border());
    v.window_rounding = Rounding::same(8.0);

    v.interact_cursor = Some(egui::CursorIcon::PointingHand);

    v
}

fn build_style() -> egui::Style {
    let mut style = egui::Style::default();

    // Genel boşluk ve boyutlar
    style.spacing.item_spacing     = Vec2::new(8.0, 6.0);
    style.spacing.button_padding   = Vec2::new(12.0, 6.0);
    style.spacing.indent           = 16.0;
    style.spacing.scroll.bar_width = 14.0;

    // Metin boyutları
    style.text_styles = [
        (egui::TextStyle::Small,   FontId::proportional(11.0)),
        (egui::TextStyle::Body,    FontId::proportional(14.0)),
        (egui::TextStyle::Button,  FontId::proportional(14.0)),
        (egui::TextStyle::Heading, FontId::proportional(20.0)),
        (egui::TextStyle::Monospace, FontId::monospace(13.0)),
    ]
    .into();

    style
}

// ─── Yardımcı widget'lar ─────────────────────────────────────────

pub use super::buttons::*;
pub use super::combobox::*;

/// Bölüm başlığı — büyük, açık renkli, alt çizgisiz.
pub fn section_heading(ui: &mut egui::Ui, text: &str) {
    ui.label(
        egui::RichText::new(text)
            .size(18.0)
            .color(c_text())
            .strong(),
    );
    ui.add_space(2.0);
    let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 1.0), egui::Sense::hover());
    ui.painter().line_segment(
        [rect.left_center(), rect.right_center()],
        Stroke::new(1.0, c_accent_dim()),
    );
    ui.add_space(8.0);
}

/// Hata kutusu — kırmızı çerçeveli bildirim.
pub fn error_box(ui: &mut egui::Ui, msg: &str) {
    egui::Frame::none()
        .fill(Color32::from_rgba_unmultiplied(0xF4, 0x43, 0x36, 20))
        .stroke(Stroke::new(1.0, c_error()))
        .rounding(Rounding::same(6.0))
        .inner_margin(egui::Margin::same(10.0))
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.add(egui::Image::new(egui::include_image!("../../assets/icons/fail-icon.svg"))
                    .max_width(18.0).max_height(18.0)
                    .tint(c_error()));
                ui.colored_label(c_error(), msg);
            });
        });
}

/// Uyarı kutusu — turuncu çerçeveli bildirim.
pub fn warning_box(ui: &mut egui::Ui, msg: &str) {
    egui::Frame::none()
        .fill(Color32::from_rgba_unmultiplied(0xFF, 0x98, 0x00, 20))
        .stroke(Stroke::new(1.0, c_warning()))
        .rounding(Rounding::same(6.0))
        .inner_margin(egui::Margin::same(10.0))
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.add(egui::Image::new(egui::include_image!("../../assets/icons/warning-icon.svg"))
                    .max_width(18.0).max_height(18.0)
                    .tint(c_warning()));
                ui.colored_label(c_warning(), msg);
            });
        });
}

/// Başarı kutusu — yeşil çerçeveli bildirim.
pub fn success_box(ui: &mut egui::Ui, msg: &str) {
    egui::Frame::none()
        .fill(Color32::from_rgba_unmultiplied(0x4C, 0xAF, 0x50, 20))
        .stroke(Stroke::new(1.0, c_success()))
        .rounding(Rounding::same(6.0))
        .inner_margin(egui::Margin::same(10.0))
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.add(egui::Image::new(egui::include_image!("../../assets/icons/check.svg"))
                    .max_width(18.0).max_height(18.0)
                    .tint(c_success()));
                ui.colored_label(c_success(), msg);
            });
        });
}
