"""Market defpage setup — registers layouts, page helpers, and loads .sx pages."""
from __future__ import annotations

from typing import Any


def setup_market_pages() -> None:
    """Register market-specific layouts, page helpers, and load page definitions."""
    _register_market_layouts()
    _register_market_helpers()
    _load_market_page_files()


def _load_market_page_files() -> None:
    import os
    from shared.sx.pages import load_page_dir
    load_page_dir(os.path.dirname(__file__), "market")


# ---------------------------------------------------------------------------
# Layouts
# ---------------------------------------------------------------------------

def _register_market_layouts() -> None:
    from shared.sx.layouts import register_custom_layout
    register_custom_layout("market", _market_full, _market_oob, _market_mobile)
    register_custom_layout("market-admin", _market_admin_full, _market_admin_oob)


def _market_full(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import root_header_sx, header_child_sx
    from sx.sx_components import _post_header_sx, _market_header_sx

    root_hdr = root_header_sx(ctx)
    child = "(<> " + _post_header_sx(ctx) + " " + _market_header_sx(ctx) + ")"
    return "(<> " + root_hdr + " " + header_child_sx(child) + ")"


def _market_oob(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import oob_header_sx
    from sx.sx_components import _post_header_sx, _market_header_sx, _clear_deeper_oob

    oobs = oob_header_sx("post-header-child", "market-header-child",
                             _market_header_sx(ctx))
    oobs = "(<> " + oobs + " " + _post_header_sx(ctx, oob=True) + " "
    oobs += _clear_deeper_oob("post-row", "post-header-child",
                               "market-row", "market-header-child") + ")"
    return oobs


def _market_mobile(ctx: dict, **kw: Any) -> str:
    from sx.sx_components import _mobile_nav_panel_sx
    return _mobile_nav_panel_sx(ctx)


def _market_admin_full(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import root_header_sx, header_child_sx
    from sx.sx_components import (
        _post_header_sx, _market_header_sx, _market_admin_header_sx,
    )

    selected = kw.get("selected", "")
    root_hdr = root_header_sx(ctx)
    child = "(<> " + _post_header_sx(ctx) + " " + _market_header_sx(ctx) + " "
    child += _market_admin_header_sx(ctx, selected=selected) + ")"
    return "(<> " + root_hdr + " " + header_child_sx(child) + ")"


def _market_admin_oob(ctx: dict, **kw: Any) -> str:
    from shared.sx.helpers import oob_header_sx
    from sx.sx_components import (
        _market_header_sx, _market_admin_header_sx, _clear_deeper_oob,
    )

    selected = kw.get("selected", "")
    oobs = "(<> " + _market_header_sx(ctx, oob=True) + " "
    oobs += oob_header_sx("market-header-child", "market-admin-header-child",
                              _market_admin_header_sx(ctx, selected=selected)) + " "
    oobs += _clear_deeper_oob("post-row", "post-header-child",
                               "market-row", "market-header-child",
                               "market-admin-row", "market-admin-header-child") + ")"
    return oobs


# ---------------------------------------------------------------------------
# Page helpers
# ---------------------------------------------------------------------------

def _register_market_helpers() -> None:
    from shared.sx.pages import register_page_helpers

    register_page_helpers("market", {
        "all-markets-content": _h_all_markets_content,
        "page-markets-content": _h_page_markets_content,
        "page-admin-content": _h_page_admin_content,
        "market-home-content": _h_market_home_content,
        "market-admin-content": _h_market_admin_content,
    })


def _h_all_markets_content():
    from quart import g, url_for, request
    from shared.utils import route_prefix

    data = getattr(g, "all_markets_data", None)
    if not data:
        from sx.sx_components import _no_markets_sx
        return _no_markets_sx()

    markets = data["markets"]
    has_more = data["has_more"]
    page_info = data["page_info"]
    page = data["page"]

    prefix = route_prefix()
    next_url = prefix + url_for("all_markets.markets_fragment", page=page + 1)

    from sx.sx_components import _market_cards_sx, _markets_grid, _no_markets_sx
    if markets:
        cards = _market_cards_sx(markets, page_info, page, has_more, next_url)
        content = _markets_grid(cards)
    else:
        content = _no_markets_sx()
    return "(<> " + content + " " + '(div :class "pb-8")' + ")"


def _h_page_markets_content():
    from quart import g, url_for
    from shared.utils import route_prefix

    data = getattr(g, "page_markets_data", None)
    if not data:
        from sx.sx_components import _no_markets_sx
        return _no_markets_sx("No markets for this page")

    markets = data["markets"]
    has_more = data["has_more"]
    page = data["page"]
    post_slug = data.get("post_slug", "")

    prefix = route_prefix()
    next_url = prefix + url_for("page_markets.markets_fragment", page=page + 1)

    from sx.sx_components import _market_cards_sx, _markets_grid, _no_markets_sx
    if markets:
        cards = _market_cards_sx(markets, {}, page, has_more, next_url,
                                    show_page_badge=False, post_slug=post_slug)
        content = _markets_grid(cards)
    else:
        content = _no_markets_sx("No markets for this page")
    return "(<> " + content + " " + '(div :class "pb-8")' + ")"


def _h_page_admin_content():
    # Content pre-rendered by before_request (async _markets_admin_panel_sx)
    from quart import g
    content = getattr(g, "page_admin_content", "")
    return '(div :id "main-panel" ' + content + ')'


def _h_market_home_content():
    from quart import g
    post_data = getattr(g, "post_data", {})
    post = post_data.get("post", {})
    from sx.sx_components import _market_landing_content_sx
    return _market_landing_content_sx(post)


def _h_market_admin_content():
    return '"market admin"'
