import pygame
import sys
from datetime import datetime

# Initialize Pygame
pygame.init()

# Color definitions
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 69, 69)
GREEN = (46, 204, 113)
BLUE = (52, 152, 219)
PURPLE = (142, 68, 173)
ORANGE = (243, 156, 18)
PINK = (255, 99, 132)
GOLD = (241, 196, 15)
GRAY = (178, 186, 187)
DARK_GRAY = (106, 114, 116)
LIGHT_BLUE = (222, 238, 251)
LIGHT_PINK = (252, 228, 236)
LIGHT_GREEN = (218, 233, 221)
LIGHT_PURPLE = (232, 216, 243)
BG_COLOR = (240, 243, 246)
CARD_WHITE = (255, 255, 255)

# Window settings
WIDTH, HEIGHT = 980, 720
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("🔮 Zodiac & Animal Sign Finder")
clock = pygame.time.Clock()

# Font setup
font_title = pygame.font.Font(None, 52)
font_header = pygame.font.Font(None, 38)
font_subheader = pygame.font.Font(None, 30)
font_body = pygame.font.Font(None, 24)
font_small = pygame.font.Font(None, 20)

# ============ DATA ============

ZODIAC_DATA = {
    'Aries': {
        'name': 'Aries', 'dates': 'Mar 21 - Apr 19',
        'element': 'Fire', 'quality': 'Cardinal',
        'ruler': 'Mars', 'color': 'Red',
        'lucky_num': '6, 7', 'lucky_day': 'Tuesday',
        'strengths': 'Brave, passionate, confident, direct',
        'weaknesses': 'Impulsive, impatient, self-centered',
        'description': 'Aries people are full of energy and adventurous spirit. Natural born leaders who act fast and never procrastinate.'
    },
    'Taurus': {
        'name': 'Taurus', 'dates': 'Apr 20 - May 20',
        'element': 'Earth', 'quality': 'Fixed',
        'ruler': 'Venus', 'color': 'Green',
        'lucky_num': '2, 6', 'lucky_day': 'Friday',
        'strengths': 'Stable, patient, practical, loyal',
        'weaknesses': 'Stubborn, conservative, possessive',
        'description': 'Taurus people are reliable and grounded. They pursue stability and have incredible endurance once they set a goal.'
    },
    'Gemini': {
        'name': 'Gemini', 'dates': 'May 21 - Jun 20',
        'element': 'Air', 'quality': 'Mutable',
        'ruler': 'Mercury', 'color': 'Yellow',
        'lucky_num': '5, 14', 'lucky_day': 'Wednesday',
        'strengths': 'Smart, adaptable, curious, communicative',
        'weaknesses': 'Changeable, unfocused, anxious',
        'description': 'Gemini people are quick-witted and articulate. They are natural social butterflies who always bring fresh topics.'
    },
    'Cancer': {
        'name': 'Cancer', 'dates': 'Jun 21 - Jul 22',
        'element': 'Water', 'quality': 'Cardinal',
        'ruler': 'Moon', 'color': 'White',
        'lucky_num': '2, 7', 'lucky_day': 'Monday',
        'strengths': 'Gentle, caring, intuitive, protective',
        'weaknesses': 'Moody, sentimental, insecure',
        'description': 'Cancer people are emotionally rich and family-oriented. Hard shell outside but soft heart inside.'
    },
    'Leo': {
        'name': 'Leo', 'dates': 'Jul 23 - Aug 22',
        'element': 'Fire', 'quality': 'Fixed',
        'ruler': 'Sun', 'color': 'Gold',
        'lucky_num': '1, 9', 'lucky_day': 'Sunday',
        'strengths': 'Confident, generous, leader, enthusiastic',
        'weaknesses': 'Arrogant, prideful, controlling',
        'description': 'Leos are born with royal charisma. They love being the center of attention and are generous helpers.'
    },
    'Virgo': {
        'name': 'Virgo', 'dates': 'Aug 23 - Sep 22',
        'element': 'Earth', 'quality': 'Mutable',
        'ruler': 'Mercury', 'color': 'Gray',
        'lucky_num': '5, 11', 'lucky_day': 'Wednesday',
        'strengths': 'Detail-oriented, perfectionist, logical, diligent',
        'weaknesses': 'Critical, overly worried, nitpicky',
        'description': 'Virgos pursue perfection and pay attention to details. They are rational and organized, making them trustworthy partners.'
    },
    'Libra': {
        'name': 'Libra', 'dates': 'Sep 23 - Oct 22',
        'element': 'Air', 'quality': 'Cardinal',
        'ruler': 'Venus', 'color': 'Blue',
        'lucky_num': '4, 6', 'lucky_day': 'Friday',
        'strengths': 'Fair, elegant, social, peacemaker',
        'weaknesses': 'Indecisive, dependent, conflict-avoidant',
        'description': 'Libras seek balance and harmony with refined aesthetic taste. They are excellent communicators and mediators.'
    },
    'Scorpio': {
        'name': 'Scorpio', 'dates': 'Oct 23 - Nov 21',
        'element': 'Water', 'quality': 'Fixed',
        'ruler': 'Pluto', 'color': 'Dark Red',
        'lucky_num': '8, 13', 'lucky_day': 'Tuesday',
        'strengths': 'Deep, perceptive, determined, mysterious',
        'weaknesses': 'Vengeful, possessive, extreme',
        'description': 'Scorpios possess strong willpower and insight. They feel intensely and go all-in when committed to a goal.'
    },
    'Sagittarius': {
        'name': 'Sagittarius', 'dates': 'Nov 22 - Dec 21',
        'element': 'Fire', 'quality': 'Mutable',
        'ruler': 'Jupiter', 'color': 'Purple',
        'lucky_num': '3, 9', 'lucky_day': 'Thursday',
        'strengths': 'Optimistic, free-spirited, humorous, adventurous',
        'weaknesses': 'Careless, blunt, impatient',
        'description': 'Sagittarians love freedom and distant horizons. They are optimistic and radiate positive energy.'
    },
    'Capricorn': {
        'name': 'Capricorn', 'dates': 'Dec 22 - Jan 19',
        'element': 'Earth', 'quality': 'Cardinal',
        'ruler': 'Saturn', 'color': 'Brown',
        'lucky_num': '4, 8', 'lucky_day': 'Saturday',
        'strengths': 'Responsible, disciplined, mature, ambitious',
        'weaknesses': 'Too serious, stubborn, emotionally reserved',
        'description': 'Capricorns are down-to-earth with clear goals. They have incredible self-discipline and are classic workaholics.'
    },
    'Aquarius': {
        'name': 'Aquarius', 'dates': 'Jan 20 - Feb 18',
        'element': 'Air', 'quality': 'Fixed',
        'ruler': 'Uranus', 'color': 'Sky Blue',
        'lucky_num': '7, 17', 'lucky_day': 'Saturday',
        'strengths': 'Innovative, independent, humanitarian, wise',
        'weaknesses': 'Rebellious, aloof, unrealistic',
        'description': 'Aquarians are forward-thinking and creative. They pursue unique lifestyles and are pioneers of their time.'
    },
    'Pisces': {
        'name': 'Pisces', 'dates': 'Feb 19 - Mar 20',
        'element': 'Water', 'quality': 'Mutable',
        'ruler': 'Neptune', 'color': 'Sea Blue',
        'lucky_num': '3, 7', 'lucky_day': 'Thursday',
        'strengths': 'Romantic, kind, imaginative, compassionate',
        'weaknesses': 'Escapist, vulnerable, indecisive',
        'description': 'Pisces people are gentle and artistic. They have rich imagination and a selfless spirit of dedication.'
    }
}

CHINESE_ZODIAC = {
    0: ('Rat', 'Quick-witted, sociable, adaptable'),
    1: ('Ox', 'Diligent, persistent, responsible'),
    2: ('Tiger', 'Brave, decisive, confident, leader'),
    3: ('Rabbit', 'Gentle, thoughtful, popular'),
    4: ('Dragon', 'Magnificent, talented, energetic'),
    5: ('Snake', 'Wise, calm, intuitive'),
    6: ('Horse', 'Free-spirited, warm, active'),
    7: ('Goat', 'Gentle, artistic, patient'),
    8: ('Monkey', 'Clever, lively, creative'),
    9: ('Rooster', 'Diligent, observant, confident'),
    10: ('Dog', 'Loyal, just, protective'),
    11: ('Pig', 'Honest, tolerant, fortunate')
}

# Zodiac symbols
ZODIAC_SIGNS = {
    'Aries': '♈', 'Taurus': '♉', 'Gemini': '♊', 'Cancer': '♋',
    'Leo': '♌', 'Virgo': '♍', 'Libra': '♎', 'Scorpio': '♏',
    'Sagittarius': '♐', 'Capricorn': '♑', 'Aquarius': '♒', 'Pisces': '♓'
}

# ============ CORE FUNCTIONS ============

def get_zodiac(month, day):
    """Return zodiac sign based on month and day"""
    zodiac_dates = [
        (1, 20, 'Aquarius'), (2, 19, 'Pisces'),
        (3, 21, 'Aries'), (4, 20, 'Taurus'),
        (5, 21, 'Gemini'), (6, 21, 'Cancer'),
        (7, 23, 'Leo'), (8, 23, 'Virgo'),
        (9, 23, 'Libra'), (10, 23, 'Scorpio'),
        (11, 22, 'Sagittarius'), (12, 22, 'Capricorn')
    ]
    
    for m, d, sign in zodiac_dates:
        if month == m and day >= d:
            return sign
        if month == m and day < d:
            prev_idx = zodiac_dates.index((m, d, sign)) - 1
            if prev_idx < 0:
                prev_idx = len(zodiac_dates) - 1
            return zodiac_dates[prev_idx][2]
    return 'Capricorn'

def get_chinese_zodiac(year):
    """Return Chinese zodiac animal for given year"""
    return CHINESE_ZODIAC[(year - 4) % 12]

def calculate_age(birth_year, birth_month, birth_day):
    """Calculate age"""
    today = datetime.now()
    age = today.year - birth_year
    if (today.month, today.day) < (birth_month, birth_day):
        age -= 1
    return age

# ============ UI FUNCTIONS ============

def draw_text(text, font, color, x, y, center=True):
    """Draw text on screen"""
    text_surface = font.render(str(text), True, color)
    text_rect = text_surface.get_rect()
    if center:
        text_rect.center = (x, y)
    else:
        text_rect.topleft = (x, y)
    screen.blit(text_surface, text_rect)
    return text_rect

def draw_rounded_rect(surface, color, rect, radius=10):
    """Draw rounded rectangle"""
    pygame.draw.rect(surface, color, rect, border_radius=radius)

def draw_card(x, y, w, h, title, lines, bg_color, border_color, title_color, accent_color):
    """Draw an information card"""
    # Background
    card_rect = pygame.Rect(x, y, w, h)
    draw_rounded_rect(screen, bg_color, card_rect, 16)
    pygame.draw.rect(screen, border_color, card_rect, 2, border_radius=16)
    
    # Shadow effect
    shadow_rect = pygame.Rect(x+3, y+3, w, h)
    pygame.draw.rect(screen, (200, 203, 208), shadow_rect, 1, border_radius=16)
    
    # Title
    draw_text(title, font_subheader, title_color, x+w//2, y+28)
    pygame.draw.line(screen, accent_color, (x+18, y+52), (x+w-18, y+52), 2)
    
    # Content lines
    for i, line in enumerate(lines):
        if line:
            draw_text(line, font_small, BLACK, x+w//2, y+78+i*28)

def draw_input_field(x, y, w, h, text, active, placeholder):
    """Draw an input field"""
    rect = pygame.Rect(x, y, w, h)
    border_color = BLUE if active else (180, 184, 188)
    bg_color = WHITE if active else (245, 246, 248)
    
    draw_rounded_rect(screen, bg_color, rect, 10)
    pygame.draw.rect(screen, border_color, rect, 2, border_radius=10)
    
    display_text = text if text else placeholder
    text_color = BLACK if text else (160, 164, 168)
    cursor = ' ▏' if active else ''
    draw_text(display_text + cursor, font_body, text_color, x+w//2, y+h//2)
    
    return rect

# ============ MAIN LOOP ============

def main():
    running = True
    input_year = ''
    input_month = ''
    input_day = ''
    active_field = 'year'
    result = None
    error_msg = ''
    error_time = 0
    
    while running:
        screen.fill(BG_COLOR)
        mouse_pos = pygame.mouse.get_pos()
        
        # ===== TITLE SECTION =====
        draw_text("🔮 Zodiac & Animal Sign Finder", font_title, PURPLE, WIDTH//2, 42)
        draw_text("Enter your birth date to discover your Western zodiac and Chinese animal sign", 
                 font_small, DARK_GRAY, WIDTH//2, 74)
        
        # ===== INPUT SECTION =====
        input_y = 112
        
        # Year input
        draw_text("Year", font_body, BLACK, 160, input_y+15)
        year_rect = draw_input_field(200, input_y, 130, 42, input_year, 
                                    active_field == 'year', "e.g. 1990")
        
        # Month input
        draw_text("Month", font_body, BLACK, 370, input_y+15)
        month_rect = draw_input_field(420, input_y, 110, 42, input_month,
                                     active_field == 'month', "1-12")
        
        # Day input
        draw_text("Day", font_body, BLACK, 560, input_y+15)
        day_rect = draw_input_field(590, input_y, 110, 42, input_day,
                                   active_field == 'day', "1-31")
        
        # Query button
        query_btn = pygame.Rect(740, input_y, 120, 42)
        is_hover = query_btn.collidepoint(mouse_pos)
        btn_color = (93, 136, 226) if is_hover else BLUE
        draw_rounded_rect(screen, btn_color, query_btn, 10)
        draw_text("🔍 Search", font_body, WHITE, query_btn.centerx, query_btn.centery)
        
        # Clear button
        clear_btn = pygame.Rect(740, input_y+52, 120, 36)
        is_hover_clear = clear_btn.collidepoint(mouse_pos)
        clear_color = (192, 57, 77) if is_hover_clear else (172, 67, 87)
        draw_rounded_rect(screen, clear_color, clear_btn, 10)
        draw_text("Clear", font_small, WHITE, clear_btn.centerx, clear_btn.centery)
        
        # ===== ERROR MESSAGE =====
        if error_msg and pygame.time.get_ticks() - error_time < 4000:
            err_bg = pygame.Rect(WIDTH//2-200, input_y+102, 400, 35)
            draw_rounded_rect(screen, (255, 229, 217), err_bg, 8)
            draw_text(error_msg, font_small, RED, WIDTH//2, err_bg.centery)
        
        # ===== RESULTS DISPLAY =====
        if result:
            y_start = 220
            
            zodiac_key = result['zodiac_en']
            zodiac_info = ZODIAC_DATA[zodiac_key]
            sign_symbol = ZODIAC_SIGNS[zodiac_key]
            
            # Left card: Zodiac
            card_w = 440
            card_h = 390
            gap = 20
            
            zodiac_lines = [
                f"{sign_symbol}  {zodiac_info['name']}  ({zodiac_info['dates']})",
                f"Element: {zodiac_info['element']}   Quality: {zodiac_info['quality']}",
                f"Ruler: {zodiac_info['ruler']}   Lucky Color: {zodiac_info['color']}",
                f"Lucky Numbers: {zodiac_info['lucky_num']}   Lucky Day: {zodiac_info['lucky_day']}",
                f"Strengths: {zodiac_info['strengths']}",
                f"Weaknesses: {zodiac_info['weaknesses']}",
                "",
                f"Description:",
                zodiac_info['description'][:42],
                zodiac_info['description'][42:] if len(zodiac_info['description']) > 42 else ""
            ]
            
            draw_card(30, y_start, card_w, card_h,
                     f"🌟 Your Zodiac: {zodiac_info['name']}",
                     zodiac_lines, LIGHT_PINK, PINK, (192, 47, 64), PINK)
            
            # Right card: Chinese Zodiac
            animal = result['animal']
            animal_name = animal[0]
            animal_desc = animal[1]
            
            animal_lines = [
                f"🐾 Animal: {animal_name}",
                f"Year: {result['year']}",
                f"Age: {result['age']} years old",
                "",
                f"Personality:",
                animal_desc[:42],
                animal_desc[42:] if len(animal_desc) > 42 else ""
            ]
            
            draw_card(30 + card_w + gap, y_start, card_w, card_h,
                     f"🐉 Your Animal Sign: {animal_name}",
                     animal_lines, LIGHT_GREEN, GREEN, (39, 163, 86), GREEN)
            
            # Bottom card: Summary
            summary_lines = [
                f"Birth Date: {result['year']}-{result['month']:02d}-{result['day']:02d}",
                f"Western Zodiac: {zodiac_info['name']}  |  Chinese Animal: {animal_name}  |  Age: {result['age']}",
                "",
                f"💡 Fun Fact: You're a {zodiac_info['name']} born in the Year of the {animal_name}!",
                f"This combination gives you both {zodiac_info['element'].lower()} sign traits and {animal_name.lower()} characteristics."
            ]
            
            draw_card(30, y_start + card_h + gap, WIDTH-60, 165,
                     "📋 Summary",
                     summary_lines, LIGHT_BLUE, BLUE, (39, 88, 176), BLUE)
        
        # ===== FOOTER =====
        draw_text("💡 Press Enter to search · Tab to switch fields · Esc to clear", 
                 font_small, DARK_GRAY, WIDTH//2, HEIGHT-28)
        
        # ===== EVENT HANDLING =====
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # Check input field clicks
                if year_rect.collidepoint(event.pos):
                    active_field = 'year'
                elif month_rect.collidepoint(event.pos):
                    active_field = 'month'
                elif day_rect.collidepoint(event.pos):
                    active_field = 'day'
                elif query_btn.collidepoint(event.pos):
                    # Execute query
                    if input_year and input_month and input_day:
                        try:
                            year = int(input_year)
                            month = int(input_month)
                            day = int(input_day)
                            
                            if month < 1 or month > 12:
                                raise ValueError("Month must be between 1-12")
                            if day < 1 or day > 31:
                                raise ValueError("Day must be between 1-31")
                            if month in [4, 6, 9, 11] and day > 30:
                                raise ValueError(f"{month} only has 30 days")
                            if month == 2 and day > 29:
                                raise ValueError("February has at most 29 days")
                            
                            zodiac_en = get_zodiac(month, day)
                            animal = get_chinese_zodiac(year)
                            age = calculate_age(year, month, day)
                            
                            result = {
                                'year': year,
                                'month': month,
                                'day': day,
                                'zodiac_en': zodiac_en,
                                'zodiac_cn': ZODIAC_DATA[zodiac_en]['name'],
                                'animal': animal,
                                'age': age
                            }
                            error_msg = ''
                        except ValueError as e:
                            error_msg = f"❌ Error: {str(e)}"
                            error_time = pygame.time.get_ticks()
                            result = None
                    else:
                        error_msg = "⚠️ Please fill in all fields (year, month, day)"
                        error_time = pygame.time.get_ticks()
                
                elif clear_btn.collidepoint(event.pos):
                    input_year = ''
                    input_month = ''
                    input_day = ''
                    result = None
                    error_msg = ''
                    active_field = 'year'
            
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_TAB:
                    fields = ['year', 'month', 'day']
                    idx = fields.index(active_field)
                    active_field = fields[(idx + 1) % 3]
                elif event.key == pygame.K_RETURN:
                    # Trigger search
                    if input_year and input_month and input_day:
                        try:
                            year = int(input_year)
                            month = int(input_month)
                            day = int(input_day)
                            
                            if month < 1 or month > 12:
                                raise ValueError("Month must be between 1-12")
                            if day < 1 or day > 31:
                                raise ValueError("Day must be between 1-31")
                            if month in [4, 6, 9, 11] and day > 30:
                                raise ValueError(f"{month} only has 30 days")
                            if month == 2 and day > 29:
                                raise ValueError("February has at most 29 days")
                            
                            zodiac_en = get_zodiac(month, day)
                            animal = get_chinese_zodiac(year)
                            age = calculate_age(year, month, day)
                            
                            result = {
                                'year': year,
                                'month': month,
                                'day': day,
                                'zodiac_en': zodiac_en,
                                'zodiac_cn': ZODIAC_DATA[zodiac_en]['name'],
                                'animal': animal,
                                'age': age
                            }
                            error_msg = ''
                        except ValueError as e:
                            error_msg = f"❌ Error: {str(e)}"
                            error_time = pygame.time.get_ticks()
                            result = None
                    else:
                        error_msg = "⚠️ Please fill in all fields"
                        error_time = pygame.time.get_ticks()
                elif event.key == pygame.K_ESCAPE:
                    input_year = ''
                    input_month = ''
                    input_day = ''
                    result = None
                    error_msg = ''
                    active_field = 'year'
                elif event.key == pygame.K_BACKSPACE:
                    if active_field == 'year':
                        input_year = input_year[:-1]
                    elif active_field == 'month':
                        input_month = input_month[:-1]
                    elif active_field == 'day':
                        input_day = input_day[:-1]
                else:
                    if active_field == 'year' and event.unicode.isdigit() and len(input_year) < 4:
                        input_year += event.unicode
                    elif active_field == 'month' and event.unicode.isdigit() and len(input_month) < 2:
                        input_month += event.unicode
                    elif active_field == 'day' and event.unicode.isdigit() and len(input_day) < 2:
                        input_day += event.unicode
        
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()