import pygame

# ===== Init =====
pygame.init()
WIDTH, HEIGHT = 1750, 1500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Currency Unit Converter")

# ===== Colors =====
BG = (28, 30, 42)
CARD = (45, 50, 65)
BTN = (70, 140, 210)
BTN_HOVER = (100, 170, 240)
TEXT = (230, 230, 230)
SUB = (170, 170, 185)
INPUT_BG = (55, 60, 75)

FONT_TITLE = pygame.font.Font(None, 42)
FONT = pygame.font.Font(None, 30)
FONT_SM = pygame.font.Font(None, 24)

# ===== Exchange Rates (relative to USD) =====
rates = {
    "USD": 1.0,
    "CNY": 7.24,
    "EUR": 0.92,
    "JPY": 149.5,
    "GBP": 0.79,
}

currencies = list(rates.keys())

# ===== UI State =====
input_text = ""
input_active = False
from_currency = 0
to_currency = 1
result_text = ""
hover_swap = False

# ===== Helpers =====
def draw_rounded_rect(surface, color, rect, radius=12):
    pygame.draw.rect(surface, color, rect, border_radius=radius)

def draw_dropdown(x, y, w, h, options, selected, opened, mouse_pos):
    rect = pygame.Rect(x, y, w, h)
    draw_rounded_rect(screen, INPUT_BG, rect)
    pygame.draw.rect(screen, SUB, rect, 2, border_radius=12)

    txt = FONT.render(options[selected], True, TEXT)
    screen.blit(txt, txt.get_rect(center=rect.center))

    # Arrow
    ax = rect.right - 25
    pts = [(ax, rect.centery - 6), (ax + 10, rect.centery - 6), (ax + 5, rect.centery + 4)]
    pygame.draw.polygon(screen, SUB, pts)

    if opened:
        for i, opt in enumerate(options):
            o_rect = pygame.Rect(x, y + (i + 1) * (h + 4), w, h)
            draw_rounded_rect(screen, INPUT_BG, o_rect)
            pygame.draw.rect(screen, SUB, o_rect, 1, border_radius=10)
            ot = FONT.render(opt, True, TEXT)
            screen.blit(ot, ot.get_rect(center=o_rect.center))
    return rect

# ===== Rects =====
input_rect = pygame.Rect(60, 200, 280, 50)
from_rect = pygame.Rect(60, 300, 180, 44)
to_rect = pygame.Rect(510, 300, 180, 44)
swap_rect = pygame.Rect(330, 310, 90, 44)
convert_rect = pygame.Rect(225, 400, 300, 55)

from_opened = False
to_opened = False

clock = pygame.time.Clock()
running = True

# ===== Main Loop =====
while running:
    screen.fill(BG)
    mouse_pos = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            # Input box
            input_active = input_rect.collidepoint(event.pos)

            # Convert button
            if convert_rect.collidepoint(event.pos):
                try:
                    amount = float(input_text)
                    from_cur = currencies[from_currency]
                    to_cur = currencies[to_currency]
                    usd_amount = amount / rates[from_cur]
                    converted = usd_amount * rates[to_cur]
                    result_text = f"{amount:.2f} {from_cur} = {converted:.2f} {to_cur}"
                except ValueError:
                    result_text = "Please enter a valid number"

            # Swap
            if swap_rect.collidepoint(event.pos):
                from_currency, to_currency = to_currency, from_currency

            # Dropdowns
            if from_rect.collidepoint(event.pos):
                from_opened = not from_opened
                to_opened = False
            elif to_rect.collidepoint(event.pos):
                to_opened = not to_opened
                from_opened = False
            else:
                if from_opened:
                    for i in range(len(currencies)):
                        if pygame.Rect(60, 300 + (i + 1) * 48, 180, 44).collidepoint(event.pos):
                            from_currency = i
                            from_opened = False
                if to_opened:
                    for i in range(len(currencies)):
                        if pygame.Rect(510, 300 + (i + 1) * 48, 180, 44).collidepoint(event.pos):
                            to_currency = i
                            to_opened = False

        if event.type == pygame.KEYDOWN:
            if input_active:
                if event.key == pygame.K_BACKSPACE:
                    input_text = input_text[:-1]
                elif len(input_text) < 15 and event.unicode.isprintable():
                    input_text += event.unicode

    # ===== Title =====
    title = FONT_TITLE.render("💱 Currency Converter", True, TEXT)
    screen.blit(title, (WIDTH // 2 - title.get_width() // 2, 30))

    # ===== Input Box =====
    label = FONT_SM.render("Enter Amount:", True, SUB)
    screen.blit(label, (60, 175))

    draw_rounded_rect(screen, INPUT_BG if not input_active else (65, 70, 90), input_rect)
    pygame.draw.rect(screen, SUB, input_rect, 2, border_radius=12)

    display = input_text if input_text else "Type here..."
    clr = TEXT if input_text else SUB
    txt_surf = FONT.render(display, True, clr)
    screen.blit(txt_surf, txt_surf.get_rect(centery=input_rect.centery, left=input_rect.left + 15))

    # ===== From / To Labels =====
    f_lab = FONT_SM.render("From:", True, SUB)
    t_lab = FONT_SM.render("To:", True, SUB)
    screen.blit(f_lab, (60, 278))
    screen.blit(t_lab, (510, 278))

    # ===== Dropdowns =====
    from_rect_final = draw_dropdown(60, 300, 180, 44, currencies, from_currency, from_opened, mouse_pos)
    to_rect_final = draw_dropdown(510, 300, 180, 44, currencies, to_currency, to_opened, mouse_pos)

    # ===== Swap Button =====
    hover_swap = swap_rect.collidepoint(mouse_pos)
    draw_rounded_rect(screen, BTN_HOVER if hover_swap else BTN, swap_rect)
    pygame.draw.rect(screen, SUB, swap_rect, 2, border_radius=12)
    sw_txt = FONT.render("⇄ Swap", True, TEXT)
    screen.blit(sw_txt, sw_txt.get_rect(center=swap_rect.center))

    # ===== Convert Button =====
    hover_cvt = convert_rect.collidepoint(mouse_pos)
    draw_rounded_rect(screen, BTN_HOVER if hover_cvt else BTN, convert_rect)
    pygame.draw.rect(screen, SUB, convert_rect, 2, border_radius=14)
    cvt_txt = FONT.render("Convert", True, TEXT)
    screen.blit(cvt_txt, cvt_txt.get_rect(center=convert_rect.center))

    # ===== Result =====
    if result_text:
        result_color = (120, 220, 150)
        res_surf = FONT.render(result_text, True, result_color)
        screen.blit(res_surf, res_surf.get_rect(center=(WIDTH // 2, 480)))

    # ===== Rate Reference =====
    ref = FONT_SM.render("Reference rates (vs USD)", True, (120, 120, 140))
    screen.blit(ref, (WIDTH // 2 - ref.get_width() // 2, 510))

    rate_str = " | ".join([f"{c}: {rates[c]}" for c in currencies])
    rate_surf = FONT_SM.render(rate_str, True, (140, 140, 155))
    screen.blit(rate_surf, rate_surf.get_rect(center=(WIDTH // 2, 540)))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()