from pathlib import Path
import copy
import importlib.util
import sys
import tkinter as tk


APP = Path(__file__).resolve().parent
V33_PATH = APP / "racecore_studio_v33.py"
if str(APP) not in sys.path:
    sys.path.insert(0, str(APP))

spec = importlib.util.spec_from_file_location("racecore_v33_for_v34", V33_PATH)
v33 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(v33)

from core.design_toolbox import shape_preset, stripe_preset, text_preset
from core.multi_selection import SelectionItem


class StudioV34(v33.StudioV33):
    """Inklapbare een-klik toolbox voor de meest gebruikte ontwerponderdelen."""

    def __init__(self):
        super().__init__()
        self.title("RaceCore Livery Studio v3.4 - Design Toolbox")

    def build_layout(self):
        super().build_layout()
        header = self.winfo_children()[0]
        for child in header.winfo_children():
            if isinstance(child, tk.Label) and "Livery Studio" in child.cget("text"):
                child.configure(text="Livery Studio  v3.4")

        viewer = self.preview_label.master
        self.toolbox_button = tk.Button(
            viewer, text="+ TOEVOEGEN", command=self.toggle_design_toolbox,
            font=("Segoe UI", 9, "bold"), fg="#071018", bg="#67E8F9",
            activeforeground="#071018", activebackground="#A5F3FC",
            relief="flat", padx=13, pady=7, cursor="hand2",
        )
        self.toolbox_button.place(x=18, y=16)

        panel = tk.Frame(
            viewer, bg="#11151D", width=278, height=492, bd=1, relief="solid"
        )
        panel.place(x=18, y=56, width=278, height=492)
        panel.place_forget()
        panel.pack_propagate(False)
        self.design_toolbox = panel

        title = tk.Frame(panel, bg="#11151D")
        title.pack(fill="x", padx=13, pady=(12, 5))
        tk.Label(
            title, text="DESIGN TOOLBOX", font=("Segoe UI", 11, "bold"),
            fg="#C4B5FD", bg="#11151D",
        ).pack(side="left")
        tk.Button(
            title, text="×", command=self.hide_design_toolbox,
            font=("Segoe UI", 11, "bold"), fg="#94A3B8", bg="#11151D",
            activeforeground="#FFFFFF", activebackground="#252A35",
            relief="flat", padx=6,
        ).pack(side="right")
        tk.Label(
            panel, text="Kies een onderdeel. Het verschijnt midden in beeld.",
            font=("Segoe UI", 8), fg="#94A3B8", bg="#11151D",
            wraplength=245, justify="left",
        ).pack(anchor="w", padx=13, pady=(0, 9))

        self._toolbox_section("VORMEN")
        self._toolbox_grid([
            ("▰  AFGEROND", lambda: self.quick_shape("Afgerond vlak")),
            ("■  RECHTHOEK", lambda: self.quick_shape("Rechthoek")),
            ("●  OVAAL", lambda: self.quick_shape("Ovaal")),
            ("◆  RUIT", lambda: self.quick_shape("Ruit")),
            ("▲  DRIEHOEK", lambda: self.quick_shape("Driehoek")),
        ], "#374151")

        self._toolbox_section("RACE-ELEMENTEN")
        self._toolbox_grid([
            ("━  LIJN", lambda: self.quick_stripe("Rechte lijn")),
            ("═  DUBBEL", lambda: self.quick_stripe("Dubbele lijn")),
            ("⌄  CHEVRON", lambda: self.quick_stripe("Chevron")),
            ("▬  BREED VLAK", lambda: self.quick_stripe("Breed vlak")),
        ], "#164E63")

        self._toolbox_section("TEKST & PATROON")
        self._toolbox_grid([
            ("T  TEAMTEKST", lambda: self.quick_text("team")),
            ("99  NUMMER", lambda: self.quick_text("number")),
            ("CAMO VLOEIEND", lambda: self.quick_pattern("Camo - vloeiend")),
            ("CAMO DIGITAAL", lambda: self.quick_pattern("Camo - digitaal")),
        ], "#4C1D95")
        tk.Button(
            panel, text="PATROON VERFIJNEN…", command=self.pattern_dialog,
            font=("Segoe UI", 8, "bold"), fg="#E5E7EB", bg="#252A35",
            activeforeground="#FFFFFF", activebackground="#374151",
            relief="flat", pady=7,
        ).pack(fill="x", padx=13, pady=(7, 13))
        self.toolbox_button.lift()

    def _toolbox_section(self, text):
        tk.Label(
            self.design_toolbox, text=text, font=("Segoe UI", 8, "bold"),
            fg="#67E8F9", bg="#11151D",
        ).pack(anchor="w", padx=13, pady=(7, 4))

    def _toolbox_grid(self, actions, colour):
        frame = tk.Frame(self.design_toolbox, bg="#11151D")
        frame.pack(fill="x", padx=11)
        for column in range(2):
            frame.grid_columnconfigure(column, weight=1, uniform="tool")
        for index, (text, command) in enumerate(actions):
            tk.Button(
                frame, text=text, command=command,
                font=("Segoe UI", 8, "bold"), fg="#F8FAFC", bg=colour,
                activeforeground="#FFFFFF", activebackground="#475569",
                relief="flat", padx=5, pady=7, anchor="w",
            ).grid(
                row=index // 2, column=index % 2, sticky="ew", padx=2, pady=2
            )

    def toggle_design_toolbox(self):
        if self.design_toolbox.winfo_ismapped():
            self.hide_design_toolbox()
        else:
            self.design_toolbox.place(x=18, y=56, width=278, height=492)
            self.design_toolbox.lift()
            self.toolbox_button.configure(text="− TOEVOEGEN")
            self.toolbox_button.lift()

    def hide_design_toolbox(self):
        self.design_toolbox.place_forget()
        self.toolbox_button.configure(text="+ TOEVOEGEN")
        self.toolbox_button.lift()

    def canvas_focus_center(self):
        return self.focus_viewport.center_x, self.focus_viewport.center_y

    def quick_shape(self, shape):
        layer = self.normalise_shape(shape_preset(
            shape, self.canvas_focus_center(), self.accent.get(),
            len(self.shape_layers) + 1,
        ))
        self.shape_layers.append(layer)
        self._finish_quick_add("shape", layer, "Vorm toegevoegd")

    def quick_stripe(self, shape):
        self.preset.set("Geen strepen")
        layer = self.normalise_stripe(stripe_preset(
            shape, self.canvas_focus_center(), self.accent.get(),
            len(self.stripe_layers) + 1,
        ))
        self.stripe_layers.append(layer)
        self._finish_quick_add("stripe", layer, "Race-element toegevoegd")

    def quick_text(self, kind):
        layer = self.normalise_text(text_preset(
            kind, self.canvas_focus_center(), self.accent.get(),
            len(self.text_layers) + 1,
        ))
        self.text_layers.append(layer)
        self._finish_quick_add("text", layer, "Tekst toegevoegd")

    def quick_pattern(self, kind):
        pattern = copy.deepcopy(self.body_pattern)
        pattern.update({"enabled": True, "kind": kind})
        self.body_pattern = pattern
        self.focus_mode.set("lmu")
        self._refresh_mode_buttons()
        self.sticker_toggle.configure(state="disabled")
        self.changed()
        self.hide_design_toolbox()
        self.status.set(f"{kind} toegepast | verfijn kleuren via Patroon")

    def _finish_quick_add(self, kind, layer, label):
        self.reconcile_layer_order()
        uid = layer["layerUid"]
        self.preview_selected_uid = uid
        self.preview_selected_instance = 0
        self.multi_selection = [SelectionItem(uid, 0)]
        self.record_state()
        self.autosave()
        self.schedule_preview()
        self.refresh_layer_sidebar(uid)
        self.inline_properties.load_selected()
        self.update_multi_count()
        self.focus_mode.set("design")
        self._refresh_mode_buttons()
        self.sticker_toggle.configure(state="normal")
        self.hide_design_toolbox()
        self.show_selection_overlay()
        self.preview_label.focus_set()
        self.status.set(f"{label} | sleep hem direct op zijn plek")

    def show_selection_overlay(self):
        super().show_selection_overlay()
        if hasattr(self, "toolbox_button"):
            self.toolbox_button.lift()
        if hasattr(self, "design_toolbox") and self.design_toolbox.winfo_ismapped():
            self.design_toolbox.lift()
            self.toolbox_button.lift()


if __name__ == "__main__":
    StudioV34().mainloop()
