package toc

import (
	"fmt"
	"html"
	"strings"
)

func (m *Manager) Render() (string, error) {
	categories, err := m.storage.ListCategories()
	if err != nil {
		return "", err
	}

	entriesByCategory, err := m.storage.GetEntriesByCategory()
	if err != nil {
		return "", err
	}

	var sb strings.Builder
	sb.WriteString("📚 <b>频道目录</b>\n")
	sb.WriteString("━━━━━━━━━━━━━━━\n\n")

	if len(categories) == 0 {
		sb.WriteString("<i>暂无分类</i>")
		return sb.String(), nil
	}

	for _, cat := range categories {
		entries := entriesByCategory[cat.Name]

		sb.WriteString(fmt.Sprintf("📁 <b>%s</b>", html.EscapeString(cat.Name)))
		if len(entries) > 0 {
			sb.WriteString(fmt.Sprintf(" (%d)", len(entries)))
		}
		sb.WriteString("\n")

		if len(entries) == 0 {
			sb.WriteString("   <i>暂无内容</i>\n")
		} else {
			for _, entry := range entries {
				sb.WriteString(fmt.Sprintf("   • <a href=\"%s\">%s</a>", html.EscapeString(entry.MessageLink()), html.EscapeString(entry.Title)))
				if entry.HasDirectLink() {
					sb.WriteString(fmt.Sprintf(" <a href=\"%s\">[直达]</a>", html.EscapeString(entry.DirectLink)))
				}
				sb.WriteString("\n")
			}
		}
		sb.WriteString("\n")
	}

	sb.WriteString("━━━━━━━━━━━━━━━\n")

	return sb.String(), nil
}
