// Package bot contains the Telegram bot: dispatch loop, command handlers,
// inline keyboards, per-user FSM for the key-creation flow and admin commands.
package bot

import (
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

// Callback data prefixes keep button routing in one place.
const (
	cbLangFA      = "lang_fa"
	cbLangEN      = "lang_en"
	cbNewKey      = "newkey_start"
	cbCancel      = "cancel"
	cbMyKeys      = "mykeys"
	cbAdminStats  = "admin_stats"
	cbAdminUsers  = "admin_users"
	cbRevokePrefix = "revoke:"
	cbRefresh     = "refresh"
)

// mainMenu builds the primary inline keyboard shown on /start.
func mainMenu() tgbotapi.InlineKeyboardMarkup {
	return tgbotapi.NewInlineKeyboardMarkup(
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("🚀 "+tr0("en", "Start create", "ساخت کلید"), cbNewKey),
			tgbotapi.NewInlineKeyboardButtonData("🗂 "+tr0("en", "My keys", "کلیدهای من"), cbMyKeys),
		),
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("🌐 Language / زبان", "lang_menu"),
		),
	)
}

func langMenu() tgbotapi.InlineKeyboardMarkup {
	return tgbotapi.NewInlineKeyboardMarkup(
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("🇮🇷 فارسی", cbLangFA),
			tgbotapi.NewInlineKeyboardButtonData("🇬🇧 English", cbLangEN),
		),
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("↩️", cbCancel),
		),
	)
}

func cancelKeyboard() tgbotapi.InlineKeyboardMarkup {
	return tgbotapi.NewInlineKeyboardMarkup(
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("❌ "+tr0("en", "Cancel", "لغو"), cbCancel),
		),
	)
}

func adminMenu() tgbotapi.InlineKeyboardMarkup {
	return tgbotapi.NewInlineKeyboardMarkup(
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("📊 Stats", cbAdminStats),
			tgbotapi.NewInlineKeyboardButtonData("👥 Users", cbAdminUsers),
		),
	)
}

// revokeKeyboard offers a confirm + cancel pair for a key id.
func revokeKeyboard(keyID int64) tgbotapi.InlineKeyboardMarkup {
	return tgbotapi.NewInlineKeyboardMarkup(
		tgbotapi.NewInlineKeyboardRow(
			tgbotapi.NewInlineKeyboardButtonData("✅ Confirm revoke", cbRevokePrefix+itoa(keyID)),
			tgbotapi.NewInlineKeyboardButtonData("❌ Cancel", cbCancel),
		),
	)
}

// tr0 is a tiny local helper so keyboard labels can be bilingual without
// pulling the full i18n bundle into this file. If lang == en the first string
// is used, otherwise the second (Persian).
func tr0(lang, en, fa string) string {
	if lang == "en" {
		return en
	}
	return fa
}

func itoa(i int64) string {
	if i == 0 {
		return "0"
	}
	neg := i < 0
	if neg {
		i = -i
	}
	var buf [20]byte
	pos := len(buf)
	for i > 0 {
		pos--
		buf[pos] = byte('0' + i%10)
		i /= 10
	}
	if neg {
		pos--
		buf[pos] = '-'
	}
	return string(buf[pos:])
}
