"""
Utility functions for the auto clicker application.
"""

import tkinter as tk
from .constants import FONT


class TooltipMixin:
    """Mixin class to add tooltip functionality to widgets."""
    
    def add_tooltip(self, widget, text):
        """Add a tooltip to a widget."""
        def on_enter(event):
            self.tooltip = tk.Toplevel(widget)
            self.tooltip.wm_overrideredirect(True)
            # Position tooltip to the right of the widget in minimized mode
            if hasattr(self, 'is_minimized') and self.is_minimized:
                x = widget.winfo_rootx() + widget.winfo_width() + 5
                y = widget.winfo_rooty()
            else:
                # Default positioning above the widget
                x = widget.winfo_rootx()
                y = widget.winfo_rooty() - 25
            self.tooltip.wm_geometry(f'+{x}+{y}')
            label = tk.Label(
                self.tooltip, 
                text=text, 
                bg='#222', 
                fg='#fff', 
                font=('Segoe UI', 9), 
                padx=6, 
                pady=2, 
                relief='solid', 
                borderwidth=1
            )
            label.pack()
            
        def on_leave(event):
            if hasattr(self, 'tooltip'):
                self.tooltip.destroy()
                self.tooltip = None
                
        widget.bind('<Enter>', on_enter)
        widget.bind('<Leave>', on_leave)


class LoaderMixin:
    """Mixin class to add loader functionality."""
    
    def __init__(self):
        self._loader_popup = None
    
    def show_loader(self, message='Processing...'):
        """Show a loading popup with the given message."""
        if hasattr(self, '_loader_popup') and self._loader_popup and self._loader_popup.winfo_exists():
            return  # Already showing
            
        self._loader_popup = tk.Toplevel(self)
        self._loader_popup.title('Please wait')
        self._loader_popup.geometry('220x80')
        self._loader_popup.configure(bg='#f0f0f0')
        self._loader_popup.transient(self)
        self._loader_popup.grab_set()
        self._loader_popup.resizable(False, False)
        
        label = tk.Label(
            self._loader_popup, 
            text=message, 
            font=('Segoe UI', 11), 
            bg='#f0f0f0', 
            fg='#007bff'
        )
        label.pack(pady=20)
        self._loader_popup.update()

    def hide_loader(self):
        """Hide the loading popup."""
        if hasattr(self, '_loader_popup') and self._loader_popup and self._loader_popup.winfo_exists():
            self._loader_popup.grab_release()
            self._loader_popup.destroy()
            self._loader_popup = None


def show_text_popup(parent, title, text):
    """Show a text popup window (currently disabled)."""
    # Disabled all text popups
    return


def calculate_screen_position(screen_height, window_height):
    """Calculate centered position for window on screen."""
    return int((screen_height - window_height) / 2)


# --- Grid/column utilities ----------------------------------------------------
def column_index_to_label(column_index: int) -> str:
    """Convert a 1-based column index to an Excel-style label.

    Examples: 1->A, 26->Z, 27->AA, 28->AB, 52->AZ, 53->BA.
    Returns an empty string for invalid input (<1).
    """
    try:
        n = int(column_index)
        if n < 1:
            return ""
        label_chars = []
        # Excel-style base-26 (A..Z) with no zero digit.
        while n > 0:
            n, rem = divmod(n - 1, 26)
            label_chars.append(chr(65 + rem))
        return "".join(reversed(label_chars))
    except Exception:
        return ""


def column_label_to_index(column_label: str) -> int:
    """Convert an Excel-style column label to a 1-based index.

    Examples: A->1, Z->26, AA->27, AB->28. Returns 0 for invalid input.
    """
    try:
        if not column_label:
            return 0
        s = str(column_label).strip().upper()
        total = 0
        for ch in s:
            if not ('A' <= ch <= 'Z'):
                return 0
            total = total * 26 + (ord(ch) - 64)
        return total
    except Exception:
        return 0