# -*- coding: utf-8 -*-
"""
TitlePanel: Lightweight titled panel (Label-like) used instead of full docking.

Provides a simple titled frame with a content area, basic minimize/restore
and visibility API compatible with existing docks so WorkspaceManager can
save/restore state unchanged.
"""
import tkinter as tk
from tkinter import ttk
from typing import Optional, Callable


class TitlePanel(ttk.Frame):
    """Simple titled panel that mimics DockFrame API minimally.

    Use this when you want a lighter weight, non-dockable box with a title
    and a content area that expands to fill available space.
    """

    def __init__(self, parent: tk.Widget, title: str = "", closable: bool = False, on_close: Optional[Callable] = None, **kwargs):
        super().__init__(parent, **kwargs)

        self.title = title
        self.closable = closable
        self.on_close_callback = on_close

        self.is_minimized = False
        self.is_visible = True

        self._create_ui()

    def _create_ui(self):
        # Title area (simple label)
        self.title_bar = ttk.Frame(self, relief=tk.FLAT)
        self.title_bar.pack(side=tk.TOP, fill=tk.X)

        self.title_label = ttk.Label(self.title_bar, text=self.title, font=('Arial', 10, 'bold'), padding=(4, 2))
        self.title_label.pack(side=tk.LEFT)

        if self.closable:
            self.close_btn = ttk.Button(self.title_bar, text='✕', width=3, command=self.close)
            self.close_btn.pack(side=tk.RIGHT, padx=(4, 0))

        # Content container
        self.content_frame = ttk.Frame(self)
        self.content_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

    def populate_content(self):
        """Subclasses should override this to populate `self.content_frame`."""
        pass

    def minimize(self):
        if not self.is_minimized:
            self.content_frame.pack_forget()
            self.is_minimized = True

    def restore(self):
        if self.is_minimized:
            self.content_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
            self.is_minimized = False

    def toggle_minimize(self):
        if self.is_minimized:
            self.restore()
        else:
            self.minimize()

    def close(self):
        self.pack_forget()
        self.is_visible = False
        if self.on_close_callback:
            self.on_close_callback(self)

    def show(self):
        if not self.is_visible:
            self.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
            self.is_visible = True
            if self.is_minimized:
                self.restore()

    def set_title(self, new_title: str):
        self.title = new_title
        self.title_label.configure(text=new_title)
