#include <ncurses.h>
#include <string.h>
#include "ui.h"
#include "tamagotchi.h"

// Initialize UI
void init_ui(void) {
    // Initialize ncurses
    initscr();            // Start ncurses mode
    cbreak();             // Line buffering disabled
    noecho();             // Don't echo() while we do getch
    keypad(stdscr, TRUE); // We get F1, F2 etc..
    curs_set(0);          // Hide cursor
    timeout(100);         // Set non-blocking input with 100ms delay
}

// Cleanup UI
void cleanup_ui(void) {
    endwin(); // End ncurses mode
}

// Draw Streamii
void draw_tamagotchi(Tamagotchi *tama) {
    int max_y, max_x;
    getmaxyx(stdscr, max_y, max_x);

    // Streamii body
    int start_y = max_y / 2 - 5;
    int start_x = max_x / 2 - 10;

    // Clear previous drawing
    clear();

    // Streamii body (simplified ASCII art)
    mvprintw(start_y,     start_x, "    /\\___/\\    ");
    mvprintw(start_y + 1, start_x, "   (  o o  )   ");
    mvprintw(start_y + 2, start_x, "   /   ^   \\   ");
    mvprintw(start_y + 3, start_x, "  /  \\___/  \\  ");
    
    // Facial expression
    const char* face = get_tamagotchi_face(tama);
    mvprintw(start_y + 2, start_x + 6, "%s", face);
}

// Draw stats
void draw_stats(Tamagotchi *tama) {
    int max_y, max_x;
    getmaxyx(stdscr, max_y, max_x);

    // Stats area
    mvprintw(max_y - 5, 2, "Hunger:       [");
    for (int i = 0; i < tama->hunger / 10; i++) 
        printw("#");
    mvprintw(max_y - 4, 2, "Energy:       [");
    for (int i = 0; i < tama->energy / 10; i++) 
        printw("#");
    mvprintw(max_y - 3, 2, "Happiness:    [");
    for (int i = 0; i < tama->happiness / 10; i++) 
        printw("#");
    mvprintw(max_y - 2, 2, "Cleanliness:  [");
    for (int i = 0; i < tama->cleanliness / 10; i++) 
        printw("#");

    // Age and status
    mvprintw(max_y - 1, 2, "Age: %d | Status: %s", 
             tama->age, 
             tama->is_alive ? "Alive" : "DEAD");
}

// Display menu
void display_menu(void) {
    int max_y, max_x;
    getmaxyx(stdscr, max_y, max_x);

    mvprintw(max_y - 7, 2, "Controls:");
    mvprintw(max_y - 6, 2, "F1: Feed");
    mvprintw(max_y - 6, 20, "F2: Sleep");
    mvprintw(max_y - 5, 2, "F3: Play");
    mvprintw(max_y - 5, 20, "F4: Clean");
    mvprintw(max_y - 4, 2, "Q: Quit");
}

// Get user input
int get_user_input(void) {
    return getch();
}

// Show game over screen
void show_game_over(void) {
    int max_y, max_x;
    getmaxyx(stdscr, max_y, max_x);

    clear();
    mvprintw(max_y/2, max_x/2 - 5, "GAME OVER");
    mvprintw(max_y/2 + 1, max_x/2 - 10, "Your streamii has died :(");
    refresh();
    
    // Wait for key press
    timeout(-1);
    getch();
}