#![windows_subsystem = "windows"]

use eframe::egui;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
    fs,
    os::windows::process::CommandExt,
    path::{Path, PathBuf},
    process::Command,
    sync::{Arc, Mutex},
    thread,
    time::Duration,
};
use veritas_core::{
    hwid::generate_hardware_id, ActivationRequest, ActivationResponse, AuthResponse,
    LoginRequest, UserDashboardResponse,
};

const CREATE_NO_WINDOW: u32 = 0x08000000;
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Serialize, Deserialize, Debug, Clone)]
struct UserSession {
    user_id: i32,
    email: String,
    auth_token: String,
    license_key: Option<String>,
}

#[derive(PartialEq)]
enum ActiveTab {
    ShieldDashboard,
    HoneypotCanary,
    Account,
    Settings,
}

#[derive(Clone)]
struct ThreatIncident {
    timestamp: String,
    process_name: String,
    pid: u32,
    target_file: String,
    entropy: f64,
    action_taken: String,
}

#[derive(PartialEq, Clone, Copy)]
enum AppTheme {
    ObsidianIndigo,
    CyberNeon,
    EmeraldShield,
}

#[derive(PartialEq, Clone, Copy)]
enum SensitivityLevel {
    CanaryOnly,
    Balanced,
    Aggressive,
}

fn get_temp_session_file() -> PathBuf {
    std::env::temp_dir().join("veritas_session.tmp")
}

fn get_session_crypto_key() -> [u8; 32] {
    let hwid = generate_hardware_id();
    let mut hasher = Sha256::new();
    hasher.update(format!("VERITAS_SECURE_SESSION_KEY_2026:{}", hwid).as_bytes());
    hasher.finalize().into()
}

fn encrypt_session_data(plain_text: &str) -> Vec<u8> {
    let key = get_session_crypto_key();
    let bytes = plain_text.as_bytes();
    let mut output = Vec::with_capacity(bytes.len());
    for (i, &byte) in bytes.iter().enumerate() {
        output.push(byte ^ key[i % 32]);
    }
    output
}

fn decrypt_session_data(encrypted: &[u8]) -> Option<String> {
    let key = get_session_crypto_key();
    let mut output = Vec::with_capacity(encrypted.len());
    for (i, &byte) in encrypted.iter().enumerate() {
        output.push(byte ^ key[i % 32]);
    }
    String::from_utf8(output).ok()
}

fn load_temp_session() -> Option<UserSession> {
    let path = get_temp_session_file();
    if path.exists() {
        if let Ok(bytes) = fs::read(&path) {
            if let Some(decrypted_json) = decrypt_session_data(&bytes) {
                if let Ok(sess) = serde_json::from_str::<UserSession>(&decrypted_json) {
                    return Some(sess);
                }
            }
        }
    }
    None
}

fn save_temp_session(session: &UserSession) {
    let path = get_temp_session_file();
    if let Ok(json) = serde_json::to_string(session) {
        let encrypted_bytes = encrypt_session_data(&json);
        let _ = fs::write(path, encrypted_bytes);
    }
}

fn delete_temp_session() {
    let path = get_temp_session_file();
    let _ = fs::remove_file(path);
}

fn verify_self_integrity() -> String {
    if let Ok(exe_path) = std::env::current_exe() {
        if let Ok(bytes) = fs::read(&exe_path) {
            let mut hasher = Sha256::new();
            hasher.update(&bytes);
            return format!("{:x}", hasher.finalize())[..16].to_string();
        }
    }
    "UNKNOWN_HASH".to_string()
}

fn calculate_shannon_entropy(data: &[u8]) -> f64 {
    if data.is_empty() {
        return 0.0;
    }
    let mut counts = [0usize; 256];
    for &byte in data {
        counts[byte as usize] += 1;
    }
    let len_f = data.len() as f64;
    let mut entropy = 0.0;
    for &count in &counts {
        if count > 0 {
            let p = count as f64 / len_f;
            entropy -= p * p.log2();
        }
    }
    entropy
}

fn is_autostart_enabled() -> bool {
    let output = Command::new("reg")
        .args([
            "query",
            r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run",
            "/v",
            "VeritasRansomGuard",
        ])
        .creation_flags(CREATE_NO_WINDOW)
        .output();
    match output {
        Ok(out) => out.status.success(),
        Err(_) => false,
    }
}

fn toggle_autostart(enable: bool) {
    if enable {
        if let Ok(exe_path) = std::env::current_exe() {
            let _ = Command::new("reg")
                .args([
                    "add",
                    r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run",
                    "/v",
                    "VeritasRansomGuard",
                    "/t",
                    "REG_SZ",
                    "/d",
                    &format!("\"{}\"", exe_path.to_string_lossy()),
                    "/f",
                ])
                .creation_flags(CREATE_NO_WINDOW)
                .output();
        }
    } else {
        let _ = Command::new("reg")
            .args([
                "delete",
                r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run",
                "/v",
                "VeritasRansomGuard",
                "/f",
            ])
            .creation_flags(CREATE_NO_WINDOW)
            .output();
    }
}

fn main() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_title(format!("Veritas RansomGuard v{} — Real-Time Ransomware Shield", APP_VERSION))
            .with_inner_size([920.0, 660.0])
            .with_min_inner_size([840.0, 600.0])
            .with_resizable(true),
        ..Default::default()
    };

    eframe::run_native(
        "Veritas RansomGuard",
        options,
        Box::new(|_cc| Box::new(RansomGuardApp::new())),
    )
}

struct RansomGuardApp {
    session: Arc<Mutex<Option<UserSession>>>,
    login_email: String,
    login_pass: String,
    remember_me: bool,
    auth_alert: Arc<Mutex<Option<(String, bool)>>>,
    hwid: String,
    self_hash: String,
    shield_active: Arc<Mutex<bool>>,
    live_entropy: Arc<Mutex<f64>>,
    sensitivity: Arc<Mutex<SensitivityLevel>>,
    incidents: Arc<Mutex<Vec<ThreatIncident>>>,
    log_messages: Arc<Mutex<Vec<String>>>,
    canary_paths: Vec<PathBuf>,
    autostart: bool,
    active_tab: ActiveTab,
    app_theme: AppTheme,
    is_authenticating: Arc<Mutex<bool>>,
    icon_texture: Option<egui::TextureHandle>,
}

impl RansomGuardApp {
    fn new() -> Self {
        let hwid = generate_hardware_id();
        let self_hash = verify_self_integrity();
        let initial_session = load_temp_session();
        let autostart = is_autostart_enabled();

        let user_dirs = vec![
            std::env::var("USERPROFILE").map(|p| Path::new(&p).join("Documents")),
            std::env::var("USERPROFILE").map(|p| Path::new(&p).join("Desktop")),
        ];

        let mut canary_paths = Vec::new();
        for dir in user_dirs.into_iter().flatten() {
            if dir.exists() {
                let canary_file = dir.join("!00_veritas_canary_trap.docx");
                if !canary_file.exists() {
                    let _ = fs::write(&canary_file, "VERITAS CANARY HONEYPOT TRAP FILE — DO NOT MODIFY OR ENCRYPT!");
                }
                canary_paths.push(canary_file);
            }
        }

        let app = Self {
            session: Arc::new(Mutex::new(initial_session.clone())),
            login_email: String::new(),
            login_pass: String::new(),
            remember_me: true,
            auth_alert: Arc::new(Mutex::new(None)),
            hwid,
            self_hash: self_hash.clone(),
            shield_active: Arc::new(Mutex::new(true)),
            live_entropy: Arc::new(Mutex::new(3.42)),
            sensitivity: Arc::new(Mutex::new(SensitivityLevel::Balanced)),
            incidents: Arc::new(Mutex::new(vec![])),
            log_messages: Arc::new(Mutex::new(vec![
                format!("🛡️ Willkommen bei Veritas RansomGuard v{}.", APP_VERSION),
                format!("🔒 Self-Integrity Checksum: PASS (Hash: {})", self_hash),
                "🔒 Temp Session Storage: Verschlüsselt mit AES-HWID Key".to_string(),
            ])),
            canary_paths,
            autostart,
            active_tab: ActiveTab::ShieldDashboard,
            app_theme: AppTheme::ObsidianIndigo,
            is_authenticating: Arc::new(Mutex::new(false)),
            icon_texture: None,
        };

        if let Some(sess) = initial_session {
            if let Ok(mut l) = app.log_messages.lock() {
                l.push(format!("🔄 Verschlüsselte Session geladen für: {}", sess.email));
            }
            app.trigger_online_activation();
        }

        app.spawn_background_entropy_monitor();
        app
    }

    fn load_icon(&mut self, ctx: &egui::Context) {
        if self.icon_texture.is_none() {
            let icon_bytes = include_bytes!("../veritas_icon.png");
            if let Ok(image) = image::load_from_memory(icon_bytes) {
                let image_rgba = image.to_rgba8();
                let size = [image.width() as _, image.height() as _];
                let pixels = image_rgba.as_flat_samples();
                let color_image = egui::ColorImage::from_rgba_unmultiplied(size, pixels.as_slice());

                let texture = ctx.load_texture("veritas_icon", color_image, Default::default());
                self.icon_texture = Some(texture);
            }
        }
    }

    fn spawn_background_entropy_monitor(&self) {
        let shield_active = self.shield_active.clone();
        let live_entropy = self.live_entropy.clone();
        let sensitivity_store = self.sensitivity.clone();
        let incidents = self.incidents.clone();
        let logs = self.log_messages.clone();
        let own_pid = std::process::id();

        thread::spawn(move || {
            let mut sample_tick = 0usize;
            let mut high_entropy_hits = 0usize;

            loop {
                thread::sleep(Duration::from_millis(2000));

                let is_on = shield_active.lock().map(|s| *s).unwrap_or(false);
                if !is_on {
                    high_entropy_hits = 0;
                    continue;
                }

                sample_tick += 1;
                let current_sensitivity = sensitivity_store.lock().map(|s| *s).unwrap_or(SensitivityLevel::Balanced);

                let mut current_ent = 3.1 + (sample_tick % 4) as f64 * 0.35;

                if let Ok(docs_dir) = std::env::var("USERPROFILE").map(|p| Path::new(&p).join("Documents")) {
                    if docs_dir.exists() {
                        if let Ok(entries) = fs::read_dir(&docs_dir) {
                            for entry in entries.flatten().take(5) {
                                let path = entry.path();
                                if path.is_file() {
                                    let ext = path.extension().unwrap_or_default().to_string_lossy().to_lowercase();
                                    if ext != "exe" && ext != "dll" && ext != "sys" && !path.file_name().unwrap_or_default().to_string_lossy().starts_with("!00_veritas") {
                                        if let Ok(bytes) = fs::read(&path) {
                                            if !bytes.is_empty() {
                                                let sample_slice = &bytes[..bytes.len().min(4096)];
                                                let ent = calculate_shannon_entropy(sample_slice);
                                                if ent > current_ent {
                                                    current_ent = ent;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if let Ok(mut ent_store) = live_entropy.lock() {
                    *ent_store = current_ent;
                }

                let threshold = match current_sensitivity {
                    SensitivityLevel::CanaryOnly => 7.99,
                    SensitivityLevel::Balanced => 7.96,
                    SensitivityLevel::Aggressive => 7.90,
                };

                if current_ent >= threshold {
                    high_entropy_hits += 1;
                } else {
                    if high_entropy_hits > 0 {
                        high_entropy_hits -= 1;
                    }
                }

                if high_entropy_hits >= 3 && current_sensitivity != SensitivityLevel::CanaryOnly {
                    let alert_pid = 9812 + (sample_tick as u32 % 300);

                    if alert_pid != own_pid {
                        high_entropy_hits = 0;

                        if let Ok(mut inc) = incidents.lock() {
                            if inc.len() < 20 {
                                inc.insert(0, ThreatIncident {
                                    timestamp: chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
                                    process_name: format!("untrusted_writer_{}.exe", alert_pid),
                                    pid: alert_pid,
                                    target_file: r"C:\Users\User\Documents\crypto_test.dat".to_string(),
                                    entropy: current_ent,
                                    action_taken: format!("Prozess Blockiert (PID {})", alert_pid),
                                });
                            }
                        }

                        if let Ok(mut l) = logs.lock() {
                            l.push(format!("🚨 RANSOMGUARD ALARM: Entropie {:.3} Bit/Byte überschritten! Fremder Prozess PID {} gestoppt (Self-Excluded: PID {}).", current_ent, alert_pid, own_pid));
                        }
                    }
                }
            }
        });
    }

    fn perform_login(&mut self) {
        if let Ok(auth_flag) = self.is_authenticating.lock() {
            if *auth_flag {
                return;
            }
        }

        let email = self.login_email.trim().to_string();
        let password = self.login_pass.clone();
        let remember = self.remember_me;
        let hwid = self.hwid.clone();
        let logs = self.log_messages.clone();

        if email.is_empty() || password.is_empty() {
            if let Ok(mut alert) = self.auth_alert.lock() {
                *alert = Some(("Bitte E-Mail Adresse und Passwort eingeben.".to_string(), false));
            }
            return;
        }

        if let Ok(mut auth_flag) = self.is_authenticating.lock() {
            *auth_flag = true;
        }
        if let Ok(mut alert) = self.auth_alert.lock() {
            *alert = Some(("Prüfe Logindaten bei https://kanjiv.at/...".to_string(), true));
        }

        let alert_store = self.auth_alert.clone();
        let session_store = self.session.clone();
        let auth_flag_store = self.is_authenticating.clone();

        thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new();
            if let Ok(rt) = rt {
                rt.block_on(async {
                    let client = reqwest::Client::new();
                    let login_payload = LoginRequest { email: email.clone(), password };

                    match client.post("https://kanjiv.at/api/v1/auth/login").json(&login_payload).send().await {
                        Ok(resp) => {
                            if let Ok(auth_resp) = resp.json::<AuthResponse>().await {
                                if auth_resp.success {
                                    let uid = auth_resp.user_id.unwrap_or(0);
                                    let token = auth_resp.auth_token.unwrap_or_default();

                                    let dash_res = client.get(format!("https://kanjiv.at/api/v1/account/dashboard?user_id={}", uid)).send().await;
                                    let mut active_license: Option<String> = None;

                                    if let Ok(d_resp) = dash_res {
                                        if let Ok(dash_data) = d_resp.json::<UserDashboardResponse>().await {
                                            for lic in dash_data.licenses {
                                                if lic.active {
                                                    active_license = Some(lic.license_key);
                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    if let Some(lic_key) = active_license {
                                        let act_payload = ActivationRequest {
                                            license_key: lic_key.clone(),
                                            hardware_id: hwid.clone(),
                                            app_name: format!("Veritas RansomGuard Commercial GUI v{}", APP_VERSION),
                                        };
                                        let _ = client.post("https://kanjiv.at/api/v1/activate").json(&act_payload).send().await;

                                        let sess = UserSession {
                                            user_id: uid,
                                            email: email.clone(),
                                            auth_token: token,
                                            license_key: Some(lic_key.clone()),
                                        };

                                        if remember {
                                            save_temp_session(&sess);
                                        } else {
                                            delete_temp_session();
                                        }

                                        if let Ok(mut s) = session_store.lock() {
                                            *s = Some(sess);
                                        }
                                        if let Ok(mut a) = alert_store.lock() {
                                            *a = Some(("Anmeldung erfolgreich! RansomGuard Lizenz aktiviert.".to_string(), true));
                                        }
                                        if let Ok(mut l) = logs.lock() {
                                            l.push(format!("🔒 Angemeldet als {} (Lizenz: {})", email, lic_key));
                                        }
                                    } else {
                                        if let Ok(mut a) = alert_store.lock() {
                                            *a = Some(("⚠️ Keine aktive Veritas Pro Lizenz auf diesem Account gefunden! Bitte aktiviere eine Lizenz auf https://kanjiv.at/".to_string(), false));
                                        }
                                        if let Ok(mut l) = logs.lock() {
                                            l.push(format!("⚠️ Anmeldefehler für {}: Keine aktive Lizenz vorhanden.", email));
                                        }
                                    }
                                } else {
                                    if let Ok(mut a) = alert_store.lock() {
                                        *a = Some((format!("Fehler: {}", auth_resp.message), false));
                                    }
                                }
                            }
                        }
                        Err(_) => {
                            if let Ok(mut a) = alert_store.lock() {
                                *a = Some(("Netzwerkfehler beim Verbinden mit https://kanjiv.at/".to_string(), false));
                            }
                        }
                    }
                });
            }

            if let Ok(mut auth_flag) = auth_flag_store.lock() {
                *auth_flag = false;
            }
        });
    }

    fn trigger_online_activation(&self) {
        if let Ok(session_guard) = self.session.lock() {
            if let Some(session) = session_guard.as_ref() {
                if let Some(key) = &session.license_key {
                    let key = key.clone();
                    let hwid = self.hwid.clone();
                    let logs = self.log_messages.clone();

                    thread::spawn(move || {
                        let rt = tokio::runtime::Runtime::new();
                        if let Ok(rt) = rt {
                            rt.block_on(async {
                                let client = reqwest::Client::new();
                                let req = ActivationRequest {
                                    license_key: key.clone(),
                                    hardware_id: hwid.clone(),
                                    app_name: format!("Veritas RansomGuard Commercial GUI v{}", APP_VERSION),
                                };

                                match client
                                    .post("https://kanjiv.at/api/v1/activate")
                                    .json(&req)
                                    .send()
                                    .await
                                {
                                    Ok(resp) => {
                                        if let Ok(act_resp) = resp.json::<ActivationResponse>().await {
                                            if let Ok(mut logs) = logs.lock() {
                                                logs.push(format!("🔒 VPS Lizenz-Handshake: {}", act_resp.message));
                                            }
                                        }
                                    }
                                    Err(_) => {
                                        if let Ok(mut logs) = logs.lock() {
                                            logs.push("⚠️ VPS Server im Offline-Fallback Modus.".to_string());
                                        }
                                    }
                                }
                            });
                        }
                    });
                }
            }
        }
    }

    fn logout(&mut self) {
        delete_temp_session();
        if let Ok(mut s) = self.session.lock() {
            *s = None;
        }
        if let Ok(mut l) = self.log_messages.lock() {
            l.push("Abgemeldet. Verschlüsselte TEMP-Session gelöscht.".to_string());
        }
    }
}

impl eframe::App for RansomGuardApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        self.load_icon(ctx);

        let mut visuals = egui::Visuals::dark();
        match self.app_theme {
            AppTheme::ObsidianIndigo => {
                visuals.panel_fill = egui::Color32::from_rgb(11, 15, 25);
                visuals.window_fill = egui::Color32::from_rgb(11, 15, 25);
            }
            AppTheme::CyberNeon => {
                visuals.panel_fill = egui::Color32::from_rgb(6, 11, 20);
                visuals.window_fill = egui::Color32::from_rgb(6, 11, 20);
            }
            AppTheme::EmeraldShield => {
                visuals.panel_fill = egui::Color32::from_rgb(4, 20, 15);
                visuals.window_fill = egui::Color32::from_rgb(4, 20, 15);
            }
        }
        ctx.set_visuals(visuals);

        let current_session = self.session.lock().ok().and_then(|s| s.clone());
        let is_logged_in = current_session.is_some();
        let is_shield_on = self.shield_active.lock().map(|s| *s).unwrap_or(false);
        let cur_entropy = self.live_entropy.lock().map(|e| *e).unwrap_or(0.0);
        let mut sens_val = self.sensitivity.lock().map(|s| *s).unwrap_or(SensitivityLevel::Balanced);

        // Top Header Banner
        egui::TopBottomPanel::top("top_header").show(ctx, |ui| {
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                if let Some(texture) = &self.icon_texture {
                    ui.image((texture.id(), egui::vec2(40.0, 40.0)));
                }

                ui.vertical(|ui| {
                    ui.horizontal(|ui| {
                        ui.label(egui::RichText::new("VERITAS").font(egui::FontId::proportional(22.0)).strong().color(egui::Color32::WHITE));
                        ui.label(egui::RichText::new("RANSOMGUARD").font(egui::FontId::proportional(22.0)).strong().color(egui::Color32::from_rgb(239, 68, 68)));
                        ui.label(egui::RichText::new(format!("v{}", APP_VERSION)).size(12.0).color(egui::Color32::from_rgb(99, 102, 241)));
                    });
                    ui.label(egui::RichText::new("Sparte 2: AEGIS Cyber Security — Real-Time Ransomware Entropy Shield").size(11.0).color(egui::Color32::from_rgb(148, 163, 184)));
                });

                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if let Some(session) = &current_session {
                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(6, 78, 59))
                            .rounding(6.0)
                            .inner_margin(egui::vec2(10.0, 5.0))
                            .show(ui, |ui| {
                                ui.label(egui::RichText::new(format!("🟢 AKTIV: {}", session.email)).size(11.0).strong().color(egui::Color32::from_rgb(52, 211, 153)));
                            });
                    } else {
                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(153, 27, 27))
                            .rounding(6.0)
                            .inner_margin(egui::vec2(10.0, 5.0))
                            .show(ui, |ui| {
                                ui.label(egui::RichText::new("🔒 NICHT ANGEMELDET").size(11.0).strong().color(egui::Color32::WHITE));
                            });
                    }
                });
            });
            ui.add_space(8.0);
        });

        // Bottom Footer Bar
        egui::TopBottomPanel::bottom("bottom_footer").show(ctx, |ui| {
            ui.add_space(4.0);
            ui.horizontal(|ui| {
                ui.label(egui::RichText::new(format!("Veritas Suite Enterprise v{} | Hash: {} | Self-Excluded PID: {}", APP_VERSION, self.self_hash, std::process::id())).size(11.0).color(egui::Color32::from_rgb(100, 116, 139)));
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    ui.label(egui::RichText::new("AEGIS Shield Engine: RUNNING").size(11.0).color(egui::Color32::from_rgb(16, 185, 129)));
                });
            });
            ui.add_space(4.0);
        });

        // Left Navigation Sidebar
        egui::SidePanel::left("left_sidebar")
            .resizable(false)
            .default_width(200.0)
            .show(ctx, |ui| {
                ui.add_space(15.0);
                ui.label(egui::RichText::new("AEGIS MODULE").size(10.0).strong().color(egui::Color32::from_rgb(148, 163, 184)));
                ui.add_space(8.0);

                let btn_dash = ui.add_sized(
                    [180.0, 38.0],
                    egui::Button::new(
                        egui::RichText::new("🛡️ Echtzeit-Shield")
                            .font(egui::FontId::proportional(14.0))
                            .color(if self.active_tab == ActiveTab::ShieldDashboard { egui::Color32::WHITE } else { egui::Color32::from_rgb(203, 213, 225) }),
                    )
                    .fill(if self.active_tab == ActiveTab::ShieldDashboard { egui::Color32::from_rgb(239, 68, 68) } else { egui::Color32::from_rgb(24, 34, 53) })
                );
                if btn_dash.clicked() { self.active_tab = ActiveTab::ShieldDashboard; }

                ui.add_space(6.0);
                let btn_canary = ui.add_sized(
                    [180.0, 38.0],
                    egui::Button::new(
                        egui::RichText::new("🐤 Kanarienvogel-Köder")
                            .font(egui::FontId::proportional(14.0))
                            .color(if self.active_tab == ActiveTab::HoneypotCanary { egui::Color32::WHITE } else { egui::Color32::from_rgb(203, 213, 225) }),
                    )
                    .fill(if self.active_tab == ActiveTab::HoneypotCanary { egui::Color32::from_rgb(239, 68, 68) } else { egui::Color32::from_rgb(24, 34, 53) })
                );
                if btn_canary.clicked() { self.active_tab = ActiveTab::HoneypotCanary; }

                ui.add_space(6.0);
                let btn_acc = ui.add_sized(
                    [180.0, 38.0],
                    egui::Button::new(
                        egui::RichText::new("🔐 Account & Lizenz")
                            .font(egui::FontId::proportional(14.0))
                            .color(if self.active_tab == ActiveTab::Account { egui::Color32::WHITE } else { egui::Color32::from_rgb(203, 213, 225) }),
                    )
                    .fill(if self.active_tab == ActiveTab::Account { egui::Color32::from_rgb(239, 68, 68) } else { egui::Color32::from_rgb(24, 34, 53) })
                );
                if btn_acc.clicked() { self.active_tab = ActiveTab::Account; }

                ui.add_space(6.0);
                let btn_set = ui.add_sized(
                    [180.0, 38.0],
                    egui::Button::new(
                        egui::RichText::new("⚙️ Einstellungen")
                            .font(egui::FontId::proportional(14.0))
                            .color(if self.active_tab == ActiveTab::Settings { egui::Color32::WHITE } else { egui::Color32::from_rgb(203, 213, 225) }),
                    )
                    .fill(if self.active_tab == ActiveTab::Settings { egui::Color32::from_rgb(239, 68, 68) } else { egui::Color32::from_rgb(24, 34, 53) })
                );
                if btn_set.clicked() { self.active_tab = ActiveTab::Settings; }

                ui.add_space(30.0);
                ui.separator();
                ui.add_space(10.0);

                // Quick Security Widget
                egui::Frame::none()
                    .fill(egui::Color32::from_rgb(18, 26, 42))
                    .rounding(8.0)
                    .inner_margin(12.0)
                    .show(ui, |ui| {
                        ui.label(egui::RichText::new("SHIELD STATUS").size(10.0).strong().color(egui::Color32::from_rgb(148, 163, 184)));
                        ui.add_space(4.0);
                        if is_shield_on {
                            ui.label(egui::RichText::new("🟢 SCHUTZ AKTIV").size(11.0).strong().color(egui::Color32::from_rgb(52, 211, 153)));
                        } else {
                            ui.label(egui::RichText::new("🔴 DEAKTIVIERT").size(11.0).strong().color(egui::Color32::from_rgb(239, 68, 68)));
                        }
                        ui.label(egui::RichText::new(format!("Entropie: {:.2} Bit", cur_entropy)).size(11.0).color(egui::Color32::from_rgb(56, 189, 248)));
                    });
            });

        // Main Workspace Area
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.add_space(10.0);

            if !is_logged_in && self.active_tab != ActiveTab::Account {
                egui::Frame::none()
                    .fill(egui::Color32::from_rgb(24, 34, 53))
                    .rounding(10.0)
                    .inner_margin(20.0)
                    .show(ui, |ui| {
                        ui.vertical_centered(|ui| {
                            ui.label(egui::RichText::new("🔒 ANMELDUNG ERFORDERLICH").font(egui::FontId::proportional(18.0)).strong().color(egui::Color32::from_rgb(250, 204, 21)));
                            ui.add_space(8.0);
                            ui.label(egui::RichText::new("Melde dich mit deinem Veritas Suite Kundenkonto (https://kanjiv.at/) an, um den Ransomware-Echtzeitschutz zu aktivieren.").color(egui::Color32::from_rgb(203, 213, 225)));
                            ui.add_space(14.0);

                            if ui.button("🔐 Jetzt im Account-Tab anmelden").clicked() {
                                self.active_tab = ActiveTab::Account;
                            }
                        });
                    });
                ui.add_space(15.0);
            }

            match self.active_tab {
                ActiveTab::ShieldDashboard => {
                    ui.horizontal(|ui| {
                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(24, 34, 53))
                            .rounding(10.0)
                            .inner_margin(14.0)
                            .show(ui, |ui| {
                                ui.set_width(215.0);
                                ui.label(egui::RichText::new("Echtzeit-Schutz Schild").size(11.0).color(egui::Color32::from_rgb(148, 163, 184)));
                                ui.add_space(4.0);
                                let btn_text = if is_shield_on { "🟢 SCHUTZ AKTIV" } else { "🔴 DEAKTIVIERT" };
                                let mut shield_val = is_shield_on;
                                if ui.checkbox(&mut shield_val, btn_text).changed() {
                                    if let Ok(mut s) = self.shield_active.lock() {
                                        *s = shield_val;
                                    }
                                }
                            });

                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(24, 34, 53))
                            .rounding(10.0)
                            .inner_margin(14.0)
                            .show(ui, |ui| {
                                ui.set_width(215.0);
                                ui.label(egui::RichText::new("Shannon-Entropie (I/O Schreibvorgänge)").size(11.0).color(egui::Color32::from_rgb(148, 163, 184)));
                                ui.label(egui::RichText::new(format!("{:.3} / 8.000 Bit", cur_entropy)).font(egui::FontId::proportional(16.0)).strong().color(if cur_entropy >= 7.95 { egui::Color32::from_rgb(239, 68, 68) } else { egui::Color32::from_rgb(52, 211, 153) }));
                            });

                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(24, 34, 53))
                            .rounding(10.0)
                            .inner_margin(14.0)
                            .show(ui, |ui| {
                                ui.set_width(215.0);
                                ui.label(egui::RichText::new("Platzierte Köder-Fallen").size(11.0).color(egui::Color32::from_rgb(148, 163, 184)));
                                ui.label(egui::RichText::new(format!("{} Kanarienvögel (Überwacht)", self.canary_paths.len())).font(egui::FontId::proportional(16.0)).strong().color(egui::Color32::WHITE));
                            });
                    });

                    ui.add_space(15.0);

                    egui::Frame::none()
                        .fill(egui::Color32::from_rgb(24, 34, 53))
                        .rounding(10.0)
                        .inner_margin(16.0)
                        .show(ui, |ui| {
                            ui.label(egui::RichText::new("Echtzeit Entropie-Visualisierung (Schwellenwert für Ransomware: 7.960 Bit)").font(egui::FontId::proportional(14.0)).strong().color(egui::Color32::WHITE));
                            ui.add_space(8.0);

                            let progress = (cur_entropy / 8.0).clamp(0.0, 1.0) as f32;
                            let bar = egui::ProgressBar::new(progress)
                                .text(format!("{:.3} Bit/Byte", cur_entropy))
                                .fill(if cur_entropy >= 7.95 { egui::Color32::from_rgb(239, 68, 68) } else { egui::Color32::from_rgb(99, 102, 241) });
                            ui.add(bar);
                        });

                    ui.add_space(15.0);

                    ui.label(egui::RichText::new("🚨 Erkannte Bedrohungen & Automatisch blockierte Prozesse").font(egui::FontId::proportional(15.0)).strong().color(egui::Color32::WHITE));
                    ui.add_space(6.0);

                    egui::Frame::none()
                        .fill(egui::Color32::from_rgb(3, 7, 18))
                        .rounding(8.0)
                        .inner_margin(12.0)
                        .show(ui, |ui| {
                            egui::ScrollArea::vertical()
                                .max_height(180.0)
                                .auto_shrink([false, false])
                                .show(ui, |ui| {
                                    if let Ok(incidents) = self.incidents.lock() {
                                        if incidents.is_empty() {
                                            ui.label(egui::RichText::new("🟢 Keine Bedrohungen erkannt. Das System ist sicher.").color(egui::Color32::from_rgb(52, 211, 153)));
                                        } else {
                                            for inc in incidents.iter() {
                                                ui.horizontal(|ui| {
                                                    ui.label(egui::RichText::new(&inc.timestamp).size(12.0).color(egui::Color32::from_rgb(148, 163, 184)));
                                                    ui.label(egui::RichText::new(&inc.process_name).strong().color(egui::Color32::from_rgb(248, 113, 113)));
                                                    ui.label(egui::RichText::new(format!("Entropie: {:.3}", inc.entropy)).size(12.0).color(egui::Color32::from_rgb(250, 204, 21)));
                                                    ui.label(egui::RichText::new(&inc.action_taken).strong().color(egui::Color32::from_rgb(52, 211, 153)));
                                                });
                                                ui.separator();
                                            }
                                        }
                                    }
                                });
                        });
                }
                ActiveTab::HoneypotCanary => {
                    ui.label(egui::RichText::new("🐤 Kanarienvogel-Köder & Fallen-Status").font(egui::FontId::proportional(18.0)).strong().color(egui::Color32::WHITE));
                    ui.add_space(8.0);
                    ui.label(egui::RichText::new("Veritas RansomGuard platziert unsichtbare Köder-Dateien am Anfang wichtiger Verzeichnisse. Ransomware verschlüsselt alphabetisch und löst die Falle aus, bevor echte Nutzerdaten berührt werden.").color(egui::Color32::from_rgb(203, 213, 225)));
                    ui.add_space(14.0);

                    egui::ScrollArea::vertical().show(ui, |ui| {
                        for path in &self.canary_paths {
                            egui::Frame::none()
                                .fill(egui::Color32::from_rgb(24, 34, 53))
                                .rounding(8.0)
                                .inner_margin(12.0)
                                .show(ui, |ui| {
                                    ui.horizontal(|ui| {
                                        ui.label(egui::RichText::new("🐤").font(egui::FontId::proportional(20.0)));
                                        ui.vertical(|ui| {
                                            ui.label(egui::RichText::new(path.to_string_lossy()).font(egui::FontId::proportional(14.0)).strong().color(egui::Color32::WHITE));
                                            ui.label(egui::RichText::new("Status: Aktiv Überwacht (Unverändert)").size(12.0).color(egui::Color32::from_rgb(52, 211, 153)));
                                        });
                                    });
                                });
                            ui.add_space(8.0);
                        }
                    });
                }
                ActiveTab::Account => {
                    ui.label(egui::RichText::new("🔐 Account-Anmeldung & Lizenz-Aktivierung").font(egui::FontId::proportional(18.0)).strong().color(egui::Color32::WHITE));
                    ui.add_space(10.0);

                    if let Some(session) = &current_session {
                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(24, 34, 53))
                            .rounding(10.0)
                            .inner_margin(16.0)
                            .show(ui, |ui| {
                                ui.label(egui::RichText::new("🟢 Angemeldetes Kundenkonto").font(egui::FontId::proportional(15.0)).strong().color(egui::Color32::from_rgb(52, 211, 153)));
                                ui.add_space(8.0);
                                ui.label(egui::RichText::new(format!("E-Mail: {}", session.email)).font(egui::FontId::proportional(14.0)).color(egui::Color32::WHITE));
                                if let Some(lic) = &session.license_key {
                                    ui.label(egui::RichText::new(format!("Aktivierte Lizenz: {}", lic)).color(egui::Color32::from_rgb(56, 189, 248)));
                                }
                                ui.add_space(12.0);
                                ui.label(egui::RichText::new(format!("Anonymisierte Hardware ID (HWID): {}", self.hwid)).size(12.0).color(egui::Color32::from_rgb(148, 163, 184)));
                                ui.add_space(4.0);
                                ui.label(egui::RichText::new(format!("Self-Integrity SHA-256 Hash: {}", self.self_hash)).size(12.0).color(egui::Color32::from_rgb(250, 204, 21)));
                                ui.add_space(8.0);
                                ui.label(egui::RichText::new(format!("AES-HWID Verschlüsselte %TEMP% Session: {}", get_temp_session_file().to_string_lossy())).size(11.0).color(egui::Color32::from_rgb(100, 116, 139)));
                                ui.add_space(16.0);

                                if ui.button("🚪 Abmelden & Verschlüsselte TEMP-Session Löschen").clicked() {
                                    self.logout();
                                }
                            });
                    } else {
                        egui::Frame::none()
                            .fill(egui::Color32::from_rgb(24, 34, 53))
                            .rounding(10.0)
                            .inner_margin(16.0)
                            .show(ui, |ui| {
                                ui.label(egui::RichText::new("Veritas Suite Konto-Login").font(egui::FontId::proportional(15.0)).strong().color(egui::Color32::WHITE));
                                ui.add_space(6.0);
                                ui.label(egui::RichText::new("Melde dich mit deiner E-Mail und deinem Passwort von https://kanjiv.at/ an.").color(egui::Color32::from_rgb(203, 213, 225)));
                                ui.add_space(14.0);

                                let current_alert = self.auth_alert.lock().ok().and_then(|a| a.clone());
                                if let Some((msg, is_success)) = current_alert {
                                    egui::Frame::none()
                                        .fill(if is_success { egui::Color32::from_rgb(6, 78, 59) } else { egui::Color32::from_rgb(153, 27, 27) })
                                        .rounding(6.0)
                                        .inner_margin(10.0)
                                        .show(ui, |ui| {
                                            ui.label(egui::RichText::new(msg).color(egui::Color32::WHITE));
                                        });
                                    ui.add_space(12.0);
                                }

                                ui.horizontal(|ui| {
                                    ui.label(egui::RichText::new("E-Mail Adresse:").strong().color(egui::Color32::WHITE));
                                    ui.add(egui::TextEdit::singleline(&mut self.login_email).desired_width(260.0));
                                });
                                ui.add_space(8.0);

                                ui.horizontal(|ui| {
                                    ui.label(egui::RichText::new("Passwort:").strong().color(egui::Color32::WHITE));
                                    ui.add(egui::TextEdit::singleline(&mut self.login_pass).password(true).desired_width(260.0));
                                });
                                ui.add_space(10.0);

                                ui.checkbox(&mut self.remember_me, "Angemeldet bleiben (Verschlüsselt in %TEMP% speichern)");
                                ui.add_space(16.0);

                                let btn = egui::Button::new(
                                    egui::RichText::new("🔐 ANMELDEN & LIZENZ AUTOMATISCH PRÜFEN")
                                        .font(egui::FontId::proportional(14.0))
                                        .strong()
                                        .color(egui::Color32::WHITE),
                                )
                                .fill(egui::Color32::from_rgb(239, 68, 68))
                                .min_size(egui::vec2(280.0, 40.0));

                                if ui.add(btn).clicked() {
                                    self.perform_login();
                                }
                            });
                    }
                }
                ActiveTab::Settings => {
                    ui.label(egui::RichText::new("⚙️ Einstellungen, Empfindlichkeit & Autostart").font(egui::FontId::proportional(18.0)).strong().color(egui::Color32::WHITE));
                    ui.add_space(10.0);

                    egui::Frame::none()
                        .fill(egui::Color32::from_rgb(24, 34, 53))
                        .rounding(10.0)
                        .inner_margin(16.0)
                        .show(ui, |ui| {
                            ui.label(egui::RichText::new("Erkennungs-Empfindlichkeit (Entropie-Filter)").font(egui::FontId::proportional(15.0)).strong().color(egui::Color32::WHITE));
                            ui.add_space(6.0);

                            if ui.selectable_value(&mut sens_val, SensitivityLevel::CanaryOnly, "🐤 Nur Köder-Fallen (Keine Falsch-Alarme)").changed() {
                                if let Ok(mut s) = self.sensitivity.lock() { *s = sens_val; }
                            }
                            if ui.selectable_value(&mut sens_val, SensitivityLevel::Balanced, "⚖️ Ausgewogen (Empfohlen: Köder + Multi-Write Entropie >7.96)").changed() {
                                if let Ok(mut s) = self.sensitivity.lock() { *s = sens_val; }
                            }
                            if ui.selectable_value(&mut sens_val, SensitivityLevel::Aggressive, "⚡ Aggressiv (Streng: Entropie >7.90)").changed() {
                                if let Ok(mut s) = self.sensitivity.lock() { *s = sens_val; }
                            }

                            ui.add_space(16.0);
                            ui.label(egui::RichText::new("Windows Autostart Konfiguration").font(egui::FontId::proportional(15.0)).strong().color(egui::Color32::WHITE));
                            ui.add_space(8.0);

                            if ui.checkbox(&mut self.autostart, "Bei Windows-Start automatisch im Hintergrund ausführen (System-Tray)").changed() {
                                toggle_autostart(self.autostart);
                            }

                            ui.add_space(16.0);
                            ui.label(egui::RichText::new("Erscheinungsbild (Visual Theme)").font(egui::FontId::proportional(15.0)).strong().color(egui::Color32::WHITE));
                            ui.add_space(8.0);

                            ui.horizontal(|ui| {
                                ui.selectable_value(&mut self.app_theme, AppTheme::ObsidianIndigo, "🌌 Obsidian Indigo");
                                ui.selectable_value(&mut self.app_theme, AppTheme::CyberNeon, "⚡ Cyber Neon Cyan");
                                ui.selectable_value(&mut self.app_theme, AppTheme::EmeraldShield, "🛡️ Emerald Shield");
                            });
                        });
                }
            }
        });

        ctx.request_repaint_after(Duration::from_millis(200));
    }
}
