import pygame
import json
import os

pygame.init()
W, H = 900, 600
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("📖 Pygame 博客")
clock = pygame.time.Clock()
FPS = 60

# 字体容错
try:
    font = pygame.font.SysFont("simhei", 22)
    title_font = pygame.font.SysFont("simhei", 28)
    small_font = pygame.font.SysFont("simhei", 18)
except:
    font = pygame.font.Font(None, 22)
    title_font = pygame.font.Font(None, 28)
    small_font = pygame.font.Font(None, 18)

# 颜色
BG = (248, 248, 248)
SIDEBAR = (45, 55, 70)
BUTTON = (60, 130, 200)
BUTTON_HOVER = (80, 160, 230)
TEXT_WHITE = (255,255,255)
TEXT_BLACK = (20,20,20)
LINE = (210,210,210)
RED = (200,50,50)

# 数据文件
DATA_FILE = "blog.json"
def load_articles():
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return []
def save_articles(articles):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(articles, f, ensure_ascii=False, indent=2)

articles = load_articles()

# 页面状态：home / new / view
page = "home"
current_view_id = None
input_title = ""
input_content = ""
focus_input = "title"
mouse_hover = ""

# 按钮类
class Button:
    def __init__(self, x, y, w, h, text, tag):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.text = text
        self.tag = tag
    def draw(self, hover=False):
        color = BUTTON_HOVER if hover else BUTTON
        pygame.draw.rect(screen, color, (self.x, self.y, self.w, self.h), border_radius=6)
        t = font.render(self.text, True, TEXT_WHITE)
        screen.blit(t, (self.x + 10, self.y + 6))
    def check(self, mx, my):
        return self.x < mx < self.x+self.w and self.y < my < self.y+self.h

# 侧边栏按钮
btn_home = Button(10, 80, 160, 40, "🏠 首页", "home")
btn_new = Button(10, 140, 160, 40, "✏️ 新建文章", "new")

# 首页文章按钮缓存
article_btns = []

running = True
while running:
    screen.fill(BG)
    mx, my = pygame.mouse.get_pos()
    hover_tag = ""

    # 侧边栏
    pygame.draw.rect(screen, SIDEBAR, (0, 0, 180, H))
    title_surf = title_font.render("我的博客", True, TEXT_WHITE)
    screen.blit(title_surf, (30, 20))

    for b in [btn_home, btn_new]:
        if b.check(mx, my):
            hover_tag = b.tag
        b.draw(hover_tag == b.tag)

    # 主内容区
    content_x = 190
    if page == "home":
        # 首页文章列表
        t = title_font.render("文章列表", True, TEXT_BLACK)
        screen.blit(t, (content_x, 20))
        article_btns.clear()
        y_offset = 70
        for idx, art in enumerate(articles):
            r = pygame.Rect(content_x, y_offset, 680, 42)
            pygame.draw.rect(screen, (255,255,255), r, border_radius=4)
            pygame.draw.rect(screen, LINE, r, 1)
            s = font.render(art["title"], True, TEXT_BLACK)
            screen.blit(s, (content_x + 12, y_offset + 8))
            article_btns.append({"rect":r, "id":idx})
            y_offset += 52

    elif page == "new":
        # 新建文章页面
        t = title_font.render("写新文章", True, TEXT_BLACK)
        screen.blit(t, (content_x, 20))
        # 标题输入框
        pygame.draw.rect(screen, (255,255,255), (content_x, 70, 650, 36), border_radius=4)
        pygame.draw.rect(screen, (80,140,220) if focus_input=="title" else LINE, (content_x,70,650,36),2)
        title_s = font.render(input_title, True, TEXT_BLACK)
        screen.blit(title_s, (content_x+10,76))
        screen.blit(small_font.render("标题",True,(100,100,100)), (content_x,50))

        # 正文输入框
        pygame.draw.rect(screen, (255,255,255), (content_x,130,650,380), border_radius=4)
        pygame.draw.rect(screen, (80,140,220) if focus_input=="content" else LINE, (content_x,130,650,380),2)
        screen.blit(small_font.render("正文",True,(100,100,100)), (content_x,110))
        # 简单文字换行显示
        show_lines = []
        line = ""
        for ch in input_content:
            line += ch
            if len(line) > 32:
                show_lines.append(line)
                line = ""
        if line:
            show_lines.append(line)
        yy = 138
        for l in show_lines[:14]:
            ts = small_font.render(l, True, TEXT_BLACK)
            screen.blit(ts, (content_x+10, yy))
            yy += 24

        # 保存按钮
        save_btn = Button(content_x, 530, 120, 38, "保存文章", "save")
        if save_btn.check(mx,my):
            hover_tag = "save"
        save_btn.draw(hover_tag=="save")

    elif page == "view":
        # 查看文章
        art = articles[current_view_id]
        t = title_font.render(art["title"], True, TEXT_BLACK)
        screen.blit(t, (content_x, 20))
        # 正文
        yy = 70
        line = ""
        for ch in art["content"]:
            line += ch
            if len(line) > 35:
                s = small_font.render(line, True, TEXT_BLACK)
                screen.blit(s, (content_x, yy))
                yy += 26
                line = ""
        if line:
            s = small_font.render(line, True, TEXT_BLACK)
            screen.blit(s, (content_x, yy))

        # 删除按钮
        del_btn = Button(content_x, 530, 120, 38, "删除文章", "delete")
        if del_btn.check(mx,my):
            hover_tag = "delete"
        del_btn.draw(hover_tag=="delete")

    # 事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            # 侧边栏点击
            if btn_home.check(mx,my):
                page = "home"
            if btn_new.check(mx,my):
                page = "new"
                input_title = ""
                input_content = ""
                focus_input = "title"
            # 首页点击文章
            if page == "home":
                for item in article_btns:
                    if item["rect"].collidepoint(mx,my):
                        page = "view"
                        current_view_id = item["id"]
            # 新建页点击输入框
            if page == "new":
                if pygame.Rect(content_x,70,650,36).collidepoint(mx,my):
                    focus_input = "title"
                elif pygame.Rect(content_x,130,650,380).collidepoint(mx,my):
                    focus_input = "content"
                # 保存
                if Button(content_x, 530, 120, 38, "", "").check(mx,my):
                    if input_title.strip() != "":
                        articles.append({"title":input_title, "content":input_content})
                        save_articles(articles)
                        page = "home"
            # 查看页删除
            if page == "view":
                if Button(content_x, 530, 120, 38, "", "").check(mx,my):
                    articles.pop(current_view_id)
                    save_articles(articles)
                    page = "home"

        if event.type == pygame.KEYDOWN and page == "new":
            if focus_input == "title":
                if event.key == pygame.K_BACKSPACE:
                    input_title = input_title[:-1]
                else:
                    if len(input_title) < 24:
                        input_title += event.unicode
            elif focus_input == "content":
                if event.key == pygame.K_BACKSPACE:
                    input_content = input_content[:-1]
                elif event.key == pygame.K_RETURN:
                    input_content += "\n"
                else:
                    input_content += event.unicode

    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()
