"""
Persistent reply keyboards for the bot's main menu.
These keyboards sit at the bottom of the chat and persist across messages.

Labels in Persian (فارسی).

Buttons are CLASSIC plain-text reply buttons — emojis come from the shared
list in utils/emojis.py via ``get_plain_emoji()``.
"""

from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
from aiogram.utils.keyboard import ReplyKeyboardBuilder
from utils.emojis import get_plain_emoji


def main_reply_kb() -> ReplyKeyboardMarkup:
    """Premium-style persistent main menu."""
    return ReplyKeyboardMarkup(
        keyboard=[
            [
                KeyboardButton(
                    text=f"{get_plain_emoji('shopping')} فروشگاه / خدمات",
                ),
            ],
            [
                KeyboardButton(
                    text=f"{get_plain_emoji('user')} پروفایل",
                ),
                KeyboardButton(
                    text=f"{get_plain_emoji('money')} افزایش موجودی",
                ),
            ],
            [
                KeyboardButton(
                    text=f"{get_plain_emoji('clipboard')} سفارشات",
                ),
                KeyboardButton(
                    text=f"{get_plain_emoji('headphone')} پشتیبانی",
                ),
            ],
        ],
        resize_keyboard=True,
        persistent=True,
        input_field_placeholder="✦ انتخاب کنید",
    )


# ─── Virtual Number Services (Reply Keyboard) ──────────────────────
# Kalino API — numeric service_ids.
# The services map (display label → service_id) is fetched live from the
# Kalino API via get_apps_display_map().


def virtual_services_reply_kb(services_map: dict[str, int] | None = None) -> ReplyKeyboardMarkup:
    """Build a ReplyKeyboardMarkup for virtual-number service selection.

    Telegram is pinned to its own row (full width), the other apps are laid
    out in a 3-column RTL grid (reversed for right-to-left reading), and a
    back button closes the keyboard flow.

    Layout:
      Row:     💎 تلگرام پنل اختصاصی
      Row:     ✳️ واتساپ  |  🚀 اینستاگرام  |  🔍 گوگل
      ...
      Footer:  🔙 بازگشت
    """
    builder = ReplyKeyboardBuilder()

    if services_map is None:
        try:
            from utils.kalino import get_apps_display_map
            services_map = get_apps_display_map()  # sync-fallback note: normally awaited by caller
        except Exception:
            services_map = {}

    # Pin Telegram to the top row if it exists (925 -- full width)
    tg_key = next((k for k in services_map.keys() if "تلگرام" in k), None)
    if tg_key:
        builder.row(KeyboardButton(text=tg_key))

    # All other services in a 3-column RTL grid
    other_apps = [name for name in services_map.keys() if name != tg_key]
    buttons = [KeyboardButton(text=name) for name in other_apps]
    for i in range(0, len(buttons), 3):
        chunk = buttons[i : i + 3]
        builder.row(*chunk[::-1])  # reversed for RTL

    # Back button
    builder.row(KeyboardButton(text=f"{get_plain_emoji('back_arrow')} بازگشت"))

    return builder.as_markup(resize_keyboard=True)