#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import scrolledtext
from core.tts_engine import VOICE_DATA

# FUSS Color Palette
COLOR_BG = "#e1f5fe"      # Main background light blue
COLOR_HEADER = "#cfd8dc"  # Header grey
COLOR_ACCENT = "#455a64"  # Title and labels dark grey
COLOR_BTN_BAR = "#eceff1" # Bottom button bar light grey

class MainWindow:
    """
    Handles the Graphical User Interface of FUSS Reader.
    Defines the layout, widgets, and user interaction elements.
    """
    def __init__(self, root, app, msgs):
        self.root = root
        self.app = app
        self.msgs = msgs # Dictionary containing translations received from main.py
        self.voice_var = tk.StringVar(value="it_f")
        self.setup_ui()
        self.create_context_menu()
        self.center_window()

    def setup_ui(self):
        """Initializes and arranges all UI components."""
        # Global window background configuration
        self.root.configure(bg=COLOR_BG)
        
        # --- 1. HEADER (Top Section) ---
        header = tk.Frame(self.root, bg=COLOR_HEADER, height=55, bd=0)
        header.pack(side="top", fill="x")
        
        # Translated main title
        tk.Label(header, text=self.msgs["title"], 
                 font=("Helvetica", 14, "bold"), bg=COLOR_HEADER, fg=COLOR_ACCENT).pack(pady=15)

        # --- 2. BUTTON BAR (Bottom Section) ---
        btn_bar = tk.Frame(self.root, bg=COLOR_BTN_BAR, pady=20, bd=1, relief="raised")
        btn_bar.pack(side="bottom", fill="x")

        # UNIFORM style for all buttons (Large and square)
        btn_style = {
            "font": ("Helvetica", 10, "bold"), 
            "width": 12, 
            "height": 2, 
            "relief": "raised", 
            "bd": 2
        }

        # EXIT button isolated on the RIGHT (translated)
        tk.Button(btn_bar, text=self.msgs["btn_exit"], bg="#607d8b", fg="white", 
                  command=self.app.quit_app, **btn_style).pack(side="right", padx=30)

        # Central frame to group main control buttons together
        inner_btn_frame = tk.Frame(btn_bar, bg=COLOR_BTN_BAR)
        inner_btn_frame.pack(side="left", padx=(345, 0))

        # Operational group (inside central frame) - all labels are translated
        tk.Button(inner_btn_frame, text=self.msgs["btn_open"], bg="white", command=self.app.load_file, **btn_style).pack(side="left", padx=8)
        tk.Button(inner_btn_frame, text=self.msgs["btn_paste"], bg="#bbdefb", command=self.app.paste_text, **btn_style).pack(side="left", padx=8)
        
        self.play_btn = tk.Button(inner_btn_frame, text=self.msgs["btn_play"], bg="#4caf50", fg="white", command=self.app.start_reading, **btn_style)
        self.play_btn.pack(side="left", padx=8)
        
        self.pause_btn = tk.Button(inner_btn_frame, text=self.msgs["btn_pause"], bg="#ff9800", fg="white", command=self.app.toggle_pause, **btn_style)
        self.pause_btn.pack(side="left", padx=8)
        
        tk.Button(inner_btn_frame, text=self.msgs["btn_stop"], bg="#dc3545", fg="white", command=self.app.stop_reading, **btn_style).pack(side="left", padx=8)
        
        tk.Button(inner_btn_frame, text=self.msgs["btn_clear"], bg="white", command=self.app.clear_all, **btn_style).pack(side="left", padx=20)

        # --- 3. MAIN BODY (Sidebar + Text Area) ---
        main_body = tk.Frame(self.root, bg=COLOR_BG)
        main_body.pack(side="top", fill="both", expand=True)

        # SIDEBAR (Left - Voice and Speed settings)
        sidebar = tk.Frame(main_body, bg=COLOR_BG, width=300, padx=20, pady=20)
        sidebar.pack(side="left", fill="y")

        # Voice Selection Box (Translated title)
        voice_box = tk.LabelFrame(sidebar, text=self.msgs["voice_select"], bg=COLOR_BG, 
                                  font=("Helvetica", 11, "bold"), fg=COLOR_ACCENT, labelanchor="n")
        voice_box.pack(fill="x", pady=(0, 10), padx=(20, 10))
        
        # M/F Sub-labels translated
        tk.Label(voice_box, text=self.msgs["fem"], font=("Helvetica", 9, "italic"), bg=COLOR_BG, fg="#78909c").grid(row=0, column=0, pady=(10, 5), padx=10)
        tk.Label(voice_box, text=self.msgs["mas"], font=("Helvetica", 9, "italic"), bg=COLOR_BG, fg="#78909c").grid(row=0, column=1, pady=(10, 5), padx=10)

        # Generate Radiobuttons for each language/voice pair
        keys = list(VOICE_DATA.keys())
        for i in range(5):
            for j in range(2):
                idx = i * 2 + j
                if idx < len(keys):
                    k = keys[idx]
                    tk.Radiobutton(voice_box, text=VOICE_DATA[k]["label"], value=k, 
                                   variable=self.voice_var, bg=COLOR_BG,
                                   font=("Helvetica", 11), activebackground=COLOR_BG,
                                   selectcolor="white").grid(row=i+1, column=j, sticky="w", padx=10, pady=12)

        # SPEED Selection Box (Translated title using DejaVu Sans for proper accent rendering)
        speed_box = tk.LabelFrame(sidebar, text=self.msgs["speed"], bg=COLOR_BG,
                                  font=("DejaVu Sans", 11, "bold"), fg=COLOR_ACCENT, labelanchor="n")        

        speed_box.pack(fill="x", pady=(60, 0), padx=(20, 10))
        
        self.speed_label = tk.Label(speed_box, text="1.0x", bg=COLOR_BG, fg="#0277bd", font=("Helvetica", 11, "bold"))
        self.speed_label.pack(pady=(10, 0))
        
        # Vertical Scale for speed adjustment
        self.speed_scale = tk.Scale(speed_box, from_=1.8, to=0.4, resolution=0.1, 
                                    orient="vertical", length=180, width=24, 
                                    bg="white", troughcolor="#f5f5f5", 
                                    highlightthickness=0, showvalue=0, 
                                    command=self.update_speed_label)
        self.speed_scale.set(1.0)
        self.speed_scale.pack(pady=15)

        # TEXT AREA (Right Section)
        text_container = tk.Frame(main_body, bg=COLOR_BG, padx=10, pady=15)
        text_container.pack(side="right", expand=True, fill="both")

        # Scrollable text widget for document reading
        self.text_area = scrolledtext.ScrolledText(text_container, font=("Helvetica", 18), 
                                                   wrap="word", padx=35, pady=35, 
                                                   bg="white", fg="black",
                                                   insertbackground="black", # Black cursor
                                                   bd=1, relief="solid")
        self.text_area.pack(expand=True, fill="both")
        
        # Karaoke highlight tag configuration
        self.text_area.tag_configure("highlight", background="yellow", foreground="black")
        
        # Initial display of the translated welcome message
        self.text_area.insert("1.0", self.msgs["msg_welcome"])

    def center_window(self):
        """Calculates screen dimensions and centers the application window."""
        # Force Tkinter to update tasks to get accurate window dimensions
        self.root.update_idletasks()
        
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        
        # Get screen width and height
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        
        # Calculate horizontal and vertical offsets
        x = (screen_width // 2) - (width // 2)
        y = (screen_height // 2) - (height // 2)
        
        # Apply the new coordinates (keeping the current width and height)
        self.root.geometry(f'+{x}+{y}')
        
    def update_speed_label(self, val):
        """Updates the speed numeric label in real-time as the slider moves."""
        self.speed_label.config(text=f"{val}x")

    def create_context_menu(self):
        """Creates a right-click popup menu for common text operations."""
        self.menu = tk.Menu(self.root, tearoff=0)
        
        # Use translated strings for menu options
        self.menu.add_command(label=self.msgs["menu_cut"], command=lambda: self.text_area.event_generate("<<Cut>>"))
        self.menu.add_command(label=self.msgs["menu_copy"], command=lambda: self.text_area.event_generate("<<Copy>>"))
        self.menu.add_command(label=self.msgs["menu_paste"], command=self.app.paste_text)
        
        self.menu.add_separator()
        
        self.menu.add_command(label=self.msgs["menu_select_all"], command=lambda: self.text_area.tag_add("sel", "1.0", "end"))

        # Bind the right mouse button (Button-3 on Linux) to trigger the menu
        self.text_area.bind("<Button-3>", self.show_menu)

    def show_menu(self, event):
        """Displays the context menu at the pointer coordinates."""
        self.menu.tk_popup(event.x_root, event.y_root)
