# -*- coding: utf-8 -*-
"""
Nút / style macOS-safe — tránh chữ trắng xoá (tk.Button bỏ qua bg/fg trên Aqua).
Dùng Canvas vẽ nền + chữ, hoặc ttk clam ép màu.
"""

from __future__ import annotations

import tkinter as tk
from tkinter import ttk


def solid_button(
    parent,
    text,
    command=None,
    bg="#15803d",
    fg="#ffffff",
    hover=None,
    border=None,
    font=("Helvetica", 11, "bold"),
    height=36,
    min_width=120,
    padx=14,
    state="normal",
):
    """
    Nút Canvas — luôn hiện chữ rõ trên macOS.
    Trả về Frame; có .set_state('normal'|'disabled'), .config(state=...).
    """
    hover = hover or bg
    border = border or bg
    parent_bg = "#e2e8f0"
    try:
        parent_bg = parent.cget("bg") or parent_bg
    except Exception:
        pass

    wrap = tk.Frame(parent, bg=parent_bg, highlightthickness=0)
    canvas = tk.Canvas(
        wrap,
        height=height,
        bg=parent_bg,
        highlightthickness=0,
        bd=0,
        cursor="hand2",
    )
    canvas.pack(fill="x", expand=True)

    st = {"bg": bg, "enabled": str(state) not in ("disabled", "0")}

    def _measure():
        # ước lượng width theo text
        return max(min_width, len(text) * 8 + padx * 2)

    def _draw(fill_c=None):
        canvas.delete("all")
        tw = max(canvas.winfo_width(), _measure())
        if tw < 40:
            tw = _measure()
        canvas.configure(width=tw)
        if st["enabled"]:
            fill = fill_c or st["bg"]
            tfg = fg
            bdr = border
        else:
            fill = "#cbd5e1"
            tfg = "#64748b"
            bdr = "#94a3b8"
        canvas.create_rectangle(1, 1, tw - 2, height - 2, fill=fill, outline=bdr, width=2)
        canvas.create_text(
            tw // 2, height // 2, text=text, fill=tfg, font=font, anchor="center",
        )

    def _go(_e=None):
        if st["enabled"] and command:
            command()

    def _in(_e=None):
        if st["enabled"]:
            st["bg"] = hover
            _draw(hover)

    def _out(_e=None):
        st["bg"] = bg
        _draw(bg if st["enabled"] else None)

    def set_state(value):
        st["enabled"] = str(value) not in ("disabled", "0")
        canvas.configure(cursor="hand2" if st["enabled"] else "arrow")
        st["bg"] = bg
        _draw()

    def _config(*args, **kwargs):
        if args and isinstance(args[0], dict):
            kwargs = {**args[0], **kwargs}
        if "state" in kwargs:
            set_state(kwargs.pop("state"))
        if "text" in kwargs:
            # not redrawing text change often — ignore or rebuild
            pass
        if kwargs:
            return tk.Frame.configure(wrap, **kwargs)
        return None

    canvas.bind("<Configure>", lambda e: _draw())
    canvas.bind("<Button-1>", _go)
    canvas.bind("<Enter>", _in)
    canvas.bind("<Leave>", _out)
    wrap.set_state = set_state  # type: ignore
    wrap.config = _config  # type: ignore
    wrap.configure = _config  # type: ignore
    wrap.after(10, _draw)
    return wrap


def setup_contrast_ttk(root=None):
    """Ép theme clam + style nút tương phản cao cho Toplevel/app phụ."""
    style = ttk.Style(root)
    try:
        style.theme_use("clam")
    except Exception:
        pass
    # Primary — nền đậm + chữ trắng
    style.configure(
        "Primary.TButton",
        background="#15803d",
        foreground="#ffffff",
        bordercolor="#14532d",
        darkcolor="#15803d",
        lightcolor="#15803d",
        focuscolor="#166534",
        padding=(12, 8),
        font=("Helvetica", 11, "bold"),
    )
    style.map(
        "Primary.TButton",
        background=[("disabled", "#94a3b8"), ("active", "#166534"), ("pressed", "#14532d"), ("!disabled", "#15803d")],
        foreground=[("disabled", "#e2e8f0"), ("!disabled", "#ffffff"), ("active", "#ffffff"), ("pressed", "#ffffff")],
    )
    style.configure(
        "Info.TButton",
        background="#1d4ed8",
        foreground="#ffffff",
        bordercolor="#1e3a8a",
        darkcolor="#1d4ed8",
        lightcolor="#1d4ed8",
        padding=(12, 8),
        font=("Helvetica", 11, "bold"),
    )
    style.map(
        "Info.TButton",
        background=[("disabled", "#94a3b8"), ("active", "#1e40af"), ("pressed", "#1e3a8a"), ("!disabled", "#1d4ed8")],
        foreground=[("disabled", "#e2e8f0"), ("!disabled", "#ffffff"), ("active", "#ffffff"), ("pressed", "#ffffff")],
    )
    style.configure(
        "Warn.TButton",
        background="#b91c1c",
        foreground="#ffffff",
        bordercolor="#7f1d1d",
        darkcolor="#b91c1c",
        lightcolor="#b91c1c",
        padding=(12, 8),
        font=("Helvetica", 11, "bold"),
    )
    style.map(
        "Warn.TButton",
        background=[("disabled", "#fca5a5"), ("active", "#991b1b"), ("pressed", "#7f1d1d"), ("!disabled", "#b91c1c")],
        foreground=[("disabled", "#7f1d1d"), ("!disabled", "#ffffff"), ("active", "#ffffff"), ("pressed", "#ffffff")],
    )
    style.configure(
        "Muted.TButton",
        background="#475569",
        foreground="#ffffff",
        bordercolor="#334155",
        darkcolor="#475569",
        lightcolor="#475569",
        padding=(12, 8),
        font=("Helvetica", 11, "bold"),
    )
    style.map(
        "Muted.TButton",
        background=[("disabled", "#cbd5e1"), ("active", "#334155"), ("!disabled", "#475569")],
        foreground=[("disabled", "#64748b"), ("!disabled", "#ffffff"), ("active", "#ffffff")],
    )
    # Nút thường: nền xám + chữ đen
    style.configure(
        "TButton",
        background="#94a3b8",
        foreground="#0f172a",
        bordercolor="#475569",
        darkcolor="#94a3b8",
        lightcolor="#94a3b8",
        padding=(10, 7),
        font=("Helvetica", 10, "bold"),
    )
    style.map(
        "TButton",
        background=[("disabled", "#e2e8f0"), ("active", "#64748b"), ("!disabled", "#94a3b8")],
        foreground=[("disabled", "#94a3b8"), ("!disabled", "#0f172a"), ("active", "#0f172a")],
    )
    return style
