"""
Reusable layout primitives - return Manim mobjects ready to .add() to a scene.

All coordinate constants come from _theme.Layout. Chrome is minimal: optional
section label at top-left, thin rule, optional footer. Full-bleed slides
(cover, thank you) set SECTION=None, WITH_FOOTER=False to skip it.
"""

from manim import (
    Text, Line, VGroup, MathTex, Tex,
    LEFT, RIGHT, UP, DOWN, ORIGIN, UL, UR, DL, DR,
)
from ._theme import Palette, Fonts, Sizes, Layout


def section_label(section_text: str, on_dark: bool = True) -> VGroup:
    """Small uppercase section indicator at top-left."""
    color = Palette.FG_DIM if on_dark else Palette.FG_MUTED
    label = Text(
        section_text.upper(),
        font=Fonts.SANS,
        font_size=Sizes.EYEBROW,
        color=color,
        weight="MEDIUM",
    )
    label.move_to([Layout.LEFT_EDGE + Layout.MARGIN_X + label.width / 2,
                   Layout.HEADER_Y, 0])
    return VGroup(label)


def horizontal_rule(y: float = Layout.HEADER_RULE_Y, on_dark: bool = True) -> Line:
    color = Palette.RULE if on_dark else Palette.FG_MUTED
    return Line(
        [Layout.LEFT_EDGE + Layout.MARGIN_X,  y, 0],
        [Layout.RIGHT_EDGE - Layout.MARGIN_X, y, 0],
        color=color,
        stroke_width=1.2,
        stroke_opacity=0.55,
    )


def footer(left_text: str = "Zero-Click, Old Tricks  -  SCSS 2026",
           right_text: str = "UNSTPB  -  mcs.danielwagner.ro",
           on_dark: bool = True) -> VGroup:
    color = Palette.FG_DIM if on_dark else Palette.FG_MUTED
    L = Text(left_text.upper(), font=Fonts.SANS, font_size=Sizes.CAPTION - 2,
             color=color, weight="MEDIUM")
    R = Text(right_text.upper(), font=Fonts.SANS, font_size=Sizes.CAPTION - 2,
             color=color, weight="MEDIUM")
    L.move_to([Layout.LEFT_EDGE + Layout.MARGIN_X + L.width / 2,
               Layout.FOOTER_Y, 0])
    R.move_to([Layout.RIGHT_EDGE - Layout.MARGIN_X - R.width / 2,
               Layout.FOOTER_Y, 0])
    return VGroup(L, R)


def slide_title(text: str, *, font_size: int = Sizes.TITLE,
                color=None, italic: bool = False,
                with_accent_rule: bool = False) -> VGroup:
    color = color or Palette.FG
    title = Text(text, font=Fonts.SERIF, font_size=font_size,
                 color=color, weight=("MEDIUM" if not italic else "BOLD"))
    out = VGroup(title)

    if with_accent_rule:
        rule = Line([0, 0, 0], [1.2, 0, 0],
                    color=Palette.WARN, stroke_width=2.5)
        rule.next_to(title, DOWN, buff=0.20).align_to(title, LEFT)
        out.add(rule)

    return out


def lead_text(text: str, *, color=None) -> Text:
    color = color or Palette.FG_MUTED
    return Text(text, font=Fonts.SERIF, font_size=Sizes.SUBTITLE,
                color=color)


def eyebrow(text: str, *, color=None) -> Text:
    color = color or Palette.FG_DIM
    return Text(text.upper(), font=Fonts.SANS, font_size=Sizes.EYEBROW,
                color=color, weight="MEDIUM")


def num_badge(label: str, *, color=None) -> Text:
    color = color or Palette.WARN
    return Text(label, font=Fonts.SERIF, font_size=Sizes.BADGE,
                color=color)


def chrome(section: str | None = None, *, with_footer: bool = True,
           on_dark: bool = True) -> VGroup:
    parts = []
    if section is not None:
        parts.append(section_label(section, on_dark=on_dark))
        parts.append(horizontal_rule(on_dark=on_dark))
    if with_footer:
        parts.append(footer(on_dark=on_dark))
    return VGroup(*parts)


def code_panel_bg(width: float, height: float):
    """Returns a dark panel rectangle for code blocks."""
    from manim import Rectangle
    panel = Rectangle(
        width=width, height=height,
        fill_color=Palette.BG_PANEL, fill_opacity=1.0,
        stroke_color=Palette.RULE, stroke_width=1.0, stroke_opacity=0.7,
    )
    return panel


# ----- Terminal-style panel (matches the site's lab-pane-dark) ---------------

def terminal_panel(header_text: str, *, width: float, height: float,
                   header_extra: str | None = None):
    """
    Build a dark rounded panel with a header bar. Returns (frame, header).
    header_text is the label in the header (uppercase chip on the left).
    header_extra (optional) is a monospace inline detail next to the header.

    Position by calling .move_to((x, y, 0)) on the returned VGroup containing
    (frame, header).  Inner content must be positioned relative to frame.
    """
    from manim import RoundedRectangle, Rectangle, Text, VGroup

    frame = RoundedRectangle(
        corner_radius=0.08,
        width=width, height=height,
        fill_color=Palette.BG_PANEL, fill_opacity=1.0,
        stroke_color=Palette.RULE, stroke_width=1.4,
    )

    # Header band (top of panel)
    header_band = RoundedRectangle(
        corner_radius=0.08,
        width=width, height=0.55,
        fill_color=Palette.RULE, fill_opacity=0.30,
        stroke_color=Palette.RULE, stroke_width=0.8,
    )
    header_band.next_to(frame.get_top(), DOWN, buff=0).align_to(frame, UP)
    header_band.shift(DOWN * (header_band.height / 2 - 0.27))

    # Header label (uppercase, small, FG_MUTED)
    label = Text(header_text.upper(), font=Fonts.SANS, font_size=Sizes.CAPTION,
                 color=Palette.FG_MUTED, weight="BOLD")
    label.next_to(frame.get_corner([-1, 1, 0]), [1, -1, 0], buff=0.18)

    items = [frame, header_band, label]

    if header_extra:
        extra = Text(header_extra, font=Fonts.MONO, font_size=Sizes.CAPTION - 1,
                     color=Palette.FG, weight="MEDIUM")
        extra.next_to(label, RIGHT, buff=0.35)
        items.append(extra)

    return VGroup(*items)


def panel_content_top(panel) -> tuple[float, float]:
    """Return (x_left, y_top) for placing content inside a terminal_panel."""
    frame = panel[0]
    return (frame.get_left()[0] + 0.30, frame.get_top()[1] - 0.85)


# ----- Bounding-box overlap detection (debug helper) ------------------------

def bbox_overlap(a, b, slack: float = 0.02) -> bool:
    """True if two mobjects' axis-aligned bounding boxes intersect (with slack)."""
    a_l = a.get_left()[0]  + slack
    a_r = a.get_right()[0] - slack
    a_t = a.get_top()[1]   - slack
    a_b = a.get_bottom()[1] + slack
    b_l = b.get_left()[0]  + slack
    b_r = b.get_right()[0] - slack
    b_t = b.get_top()[1]   - slack
    b_b = b.get_bottom()[1] + slack
    return (a_l < b_r) and (b_l < a_r) and (a_b < b_t) and (b_b < a_t)


def assert_no_overlap(named: list[tuple[str, object]], *, scene_name: str = ""):
    """
    Print a warning for every overlapping pair. Doesn't raise so the render
    still completes. Useful as a sanity check inside construct_content():

        assert_no_overlap([
            ("title", title), ("layout", layout), ("rules", rules),
        ], scene_name=type(self).__name__)
    """
    issues = []
    n = len(named)
    for i in range(n):
        for j in range(i + 1, n):
            name_i, m_i = named[i]
            name_j, m_j = named[j]
            if bbox_overlap(m_i, m_j):
                issues.append(f"  [{scene_name}] overlap: '{name_i}' x '{name_j}'")
    if issues:
        print(f"=== LAYOUT WARNINGS ({scene_name}) ===")
        for issue in issues:
            print(issue)
        print("=== END ===")
