#![no_std]
#![no_main]
use esp_backtrace as _;
use esp_hal::{
    clock::CpuClock, 
    delay::Delay, 
    gpio::{Io, Level, Output},
    main,
    timer::timg::TimerGroup,
    rng::Rng,
};
use log::info;
use heapless::String;

#[main]
fn main() -> ! {
    let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
    let peripherals = esp_hal::init(config);
    let delay = Delay::new();
    esp_println::logger::init_logger_from_env();
    
    let io = Io::new(peripherals.GPIO, peripherals.IO_MUX);
    
    // Setup multiple LEDs for cool patterns
    let mut led_builtin = Output::new(io.pins.gpio2, Level::Low);
    let mut led1 = Output::new(io.pins.gpio18, Level::Low);
    let mut led2 = Output::new(io.pins.gpio19, Level::Low);
    let mut led3 = Output::new(io.pins.gpio21, Level::Low);
    
    // Initialize random number generator for cool effects
    let mut rng = Rng::new(peripherals.RNG);
    
    // Animation state
    let mut counter = 0u32;
    let mut pattern = 0u8;
    let mut speed = 100u16;
    
    info!("🚀 ESP32 MEGA COOL DEMO STARTING!");
    info!("💡 Features: Multi-LED patterns, Random effects, Dynamic timing");
    info!("⚡ CPU: {:?} MHz", CpuClock::max());
    info!("🎯 Connect LEDs to GPIO18, 19, 21 for full effect!");
    
    loop {
        match pattern {
            // Knight Rider scanner effect
            0..=3 => {
                led_builtin.set_low();
                led1.set_low();
                led2.set_low();
                led3.set_low();
                
                match counter % 8 {
                    0 => led_builtin.set_high(),
                    1 => led1.set_high(),
                    2 => led2.set_high(),
                    3 => led3.set_high(),
                    4 => led2.set_high(),
                    5 => led1.set_high(),
                    6 => led_builtin.set_high(),
                    _ => {}
                }
            }
            
            // Binary counter effect
            4..=7 => {
                led_builtin.set_state(((counter >> 0) & 1) != 0);
                led1.set_state(((counter >> 1) & 1) != 0);
                led2.set_state(((counter >> 2) & 1) != 0);
                led3.set_state(((counter >> 3) & 1) != 0);
            }
            
            // Random chaos mode
            8..=11 => {
                let random_val = rng.random() as u8;
                led_builtin.set_state((random_val & 0x01) != 0);
                led1.set_state((random_val & 0x02) != 0);
                led2.set_state((random_val & 0x04) != 0);
                led3.set_state((random_val & 0x08) != 0);
            }
            
            // Heartbeat pulse
            _ => {
                let pulse = (counter % 20) < 2 || ((counter % 20) > 3 && (counter % 20) < 6);
                led_builtin.set_state(pulse);
                led1.set_state(pulse);
                led2.set_state(pulse);
                led3.set_state(pulse);
            }
        }
        
        // Dynamic logging with pattern info
        if counter % 25 == 0 {
            let pattern_name = match pattern {
                0..=3 => "🏎️  KNIGHT RIDER",
                4..=7 => "🔢 BINARY COUNT",
                8..=11 => "🎲 CHAOS MODE",
                _ => "💓 HEARTBEAT",
            };
            
            info!("{} | Speed: {}ms | Cycle: {}", pattern_name, speed, counter);
        }
        
        // Pattern progression and speed changes
        if counter % 200 == 0 && counter > 0 {
            pattern = (pattern + 1) % 16;
            speed = match rng.random() % 4 {
                0 => 50,   // Fast
                1 => 100,  // Medium
                2 => 200,  // Slow
                _ => 300,  // Very slow
            };
            
            let mut speed_name: String<16> = String::new();
            let _ = match speed {
                50 => speed_name.push_str("LIGHTNING"),
                100 => speed_name.push_str("FAST"),
                200 => speed_name.push_str("CHILL"),
                _ => speed_name.push_str("ZEN"),
            };
            
            info!("🔄 Pattern switch! New speed: {} ({}ms)", speed_name, speed);
        }
        
        // Cool system stats every 10 seconds
        if counter % 400 == 0 && counter > 0 {
            let uptime_sec = (counter * speed as u32) / 1000;
            info!("📊 SYSTEM STATUS:");
            info!("   ⏱️  Uptime: {}s", uptime_sec);
            info!("   🔄 Cycles: {}", counter);
            info!("   🎯 Pattern: {}/15", pattern);
            info!("   🎲 RNG: {}", rng.random() % 1000);
        }
        
        counter = counter.wrapping_add(1);
        delay.delay_millis(speed);
    }
}