// 登录页（对照 doc/frontend-design.html 第七章 ②）：
// 居中 logo 64 + "dudu" + 副题；底部微信绿胶囊按钮"微信一键登录"（56px，全产品唯一例外色）；
// 登录流：WechatAuthing 拿 code → POST /v1/auth/wechat 换 token → AccountStore（App Group，
// 键盘扩展立即可见）→ GET /v1/me 刷余额 → 关闭。
import SwiftUI

struct LoginView: View {
    @EnvironmentObject private var account: AccountStore
    @Environment(\.dismiss) private var dismiss

    @State private var busy = false
    @State private var errorText: String?

    // TODO(wechat-sdk): 凭证就绪后换 WechatOpenSDKAuth（见 WechatAuth.swift）
    private let wechat: WechatAuthing = MockWechatAuth()

    /// 微信品牌绿 #07C160：设计文档第七章 ② 指定的唯一例外色（不进 DuduTheme 令牌）
    private let wechatGreen = Color(.sRGB, red: 0x07 / 255.0, green: 0xC1 / 255.0, blue: 0x60 / 255.0)

    var body: some View {
        VStack(spacing: 0) {
            Spacer()

            // logo 64
            RoundedRectangle(cornerRadius: DuduTheme.radiusXl)
                .fill(DuduTheme.accent)
                .frame(width: 64, height: 64)
                .overlay(
                    Image(systemName: "mic.fill")
                        .font(.system(size: 28))
                        .foregroundStyle(DuduTheme.textOnAccent)
                )
            Text("dudu")
                .font(.system(size: DuduTheme.text2xl, weight: .bold, design: .rounded))
                .tracking(1)
                .foregroundStyle(DuduTheme.text1)
                .padding(.top, DuduTheme.space4)
            Text("大模型语音输入 · 说话即上屏")
                .font(.system(size: DuduTheme.textBase))
                .foregroundStyle(DuduTheme.text2)
                .padding(.top, DuduTheme.space2)

            Spacer()

            if let errorText {
                Text(errorText)
                    .font(.system(size: DuduTheme.textSm))
                    .foregroundStyle(DuduTheme.danger)
                    .padding(.bottom, DuduTheme.space3)
            }

            Button(action: login) {
                HStack(spacing: DuduTheme.space2) {
                    if busy {
                        ProgressView().tint(DuduTheme.textOnAccent)
                    } else {
                        Image(systemName: "bubble.left.and.bubble.right.fill")
                            .font(.system(size: 18))
                    }
                    Text(busy ? "正在登录" : "微信一键登录")
                        .font(.system(size: DuduTheme.textLg, weight: .medium))
                }
                .foregroundStyle(DuduTheme.textOnAccent)
                .frame(maxWidth: .infinity)
                .frame(height: DuduTheme.controlXl)
                .background(Capsule().fill(wechatGreen))
            }
            .disabled(busy)
            .padding(.horizontal, DuduTheme.space6)

            Text("登录即同意《用户协议》与《隐私政策》")
                .font(.system(size: DuduTheme.textXs))
                .foregroundStyle(DuduTheme.text3)
                .padding(.top, DuduTheme.space3)
                .padding(.bottom, DuduTheme.space8)
        }
        .frame(maxWidth: 480) // iPad sheet 内容自适应收窄
        .frame(maxWidth: .infinity)
        .background(DuduTheme.bgApp.ignoresSafeArea())
    }

    private func login() {
        guard !busy else { return }
        busy = true
        errorText = nil
        Task {
            do {
                let code = try await wechat.requestCode()
                let resp = try await Api.client.wechatLogin(code: code)
                account.applyLogin(token: resp.token, nicknameMasked: resp.user.nicknameMasked)
                // 登录后立刻拉一次余额（失败不阻断，前台刷新会兜底）
                if let me = try? await Api.client.me(token: resp.token) {
                    account.applyMe(me)
                }
                MetricsQueue.shared.track(.loginSuccess)
                dismiss()
            } catch {
                errorText = "登录失败，稍后再试"
            }
            busy = false
        }
    }
}

#Preview {
    LoginView().environmentObject(AccountStore())
}
