// 键盘面板 SwiftUI 视图（对照 doc/frontend-design.html 6.1/6.2 与 design/ 硬规则）：
// 自上而下：工具条 / 提示条（深色玻璃）/ MicBar 56 胶囊 / 功能键行。
// 面板底色 surface-2 + 顶部 1px border-1；唯一强调色 accent；无渐变；UI 无 emoji。
//
// 14D：键盘内不再录音（1A spike 平台硬限制），MicBar 从"按住说话"改为
// "按一下 · 去 dudu 说话"（deep link dudu://dictate 去主 App 听写）；
// 录音态 UI（波形 / 计时 / 上滑取消 / partial 流式条）移至主 App DictationView，
// 提示条改为静态引导文案，工具条短暂显示"已上屏"（pending_text 自动上屏后）。
import SwiftUI
import UIKit

struct KeyboardRootView: View {
    @ObservedObject var model: KeyboardViewModel
    /// 地球键 handleInputModeList 必须是 UIKit target-action，弱持有避免与 hosting 成环
    weak var inputController: UIInputViewController?

    /// iPad 适配（14E）：regular 宽度下 MicBar / 提示条 / 功能键行收窄到 560 居中，
    /// 行距与左右边距放大（全宽 56 胶囊在 iPad 横屏会夸张地拉长）
    @Environment(\.horizontalSizeClass) private var hSizeClass
    private var isRegular: Bool { hSizeClass == .regular }
    private var contentMaxWidth: CGFloat { isRegular ? 560 : .infinity }

    var body: some View {
        VStack(spacing: isRegular ? DuduTheme.space3 : DuduTheme.space2) {
            toolbar
            Group {
                HintBar(model: model)
                MicBarView(model: model)
                FunctionKeyRow(model: model, inputController: inputController)
            }
            .frame(maxWidth: contentMaxWidth) // regular 收窄
            .frame(maxWidth: .infinity)       // 居中
        }
        .padding(.horizontal, isRegular ? DuduTheme.space6 : DuduTheme.space3)
        .padding(.top, DuduTheme.space2)
        .padding(.bottom, DuduTheme.space2)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
        .background(DuduTheme.surface2)
        .overlay(alignment: .top) {
            DuduTheme.border1.frame(height: 1) // 面板顶部 1px 分隔线
        }
    }

    // MARK: - 工具条：左 logo 文字，右 状态文案 + 设置齿轮

    private var toolbar: some View {
        HStack(spacing: DuduTheme.space1) {
            Text("dudu")
                .font(.system(size: 13, weight: .bold, design: .rounded))
                .foregroundStyle(DuduTheme.accent)
            Text("语音输入")
                .font(.system(size: DuduTheme.textXs))
                .foregroundStyle(DuduTheme.text2)
            Spacer()
            statusText
            Button { model.onOpenApp("settings") } label: {
                Image(systemName: "gearshape")
                    .font(.system(size: 14))
                    .foregroundStyle(DuduTheme.text2)
                    .frame(width: 28, height: 24) // 触达区域
            }
        }
        .frame(height: 24)
    }

    /// 工具条右侧状态文案（6.2 四态；14D：pending_text 上屏后短暂显示"已上屏"）
    @ViewBuilder
    private var statusText: some View {
        if let toast = model.toast {
            HStack(spacing: 3) {
                Image(systemName: "checkmark").font(.system(size: 11, weight: .semibold))
                Text(toast)
            }
            .font(.system(size: DuduTheme.textXs, weight: .medium))
            .foregroundStyle(DuduTheme.positive)
        } else {
            switch model.account {
            case .ok:
                HStack(spacing: 3) {
                    Text("余额 \(model.balanceSeconds / 60) 分钟")
                    Image(systemName: "checkmark").font(.system(size: 11, weight: .semibold))
                }
                .font(.system(size: DuduTheme.textXs))
                .foregroundStyle(DuduTheme.text3)
            case .trial:
                Text("试用剩余 \(model.trialRemainingSeconds) 秒")
                    .font(.system(size: DuduTheme.textXs))
                    .foregroundStyle(DuduTheme.text3)
            case .guest:
                Text("未登录")
                    .font(.system(size: DuduTheme.textXs))
                    .foregroundStyle(DuduTheme.text3)
            case .quota:
                Text("时长用完了")
                    .font(.system(size: DuduTheme.textXs))
                    .foregroundStyle(DuduTheme.warning)
            }
        }
    }
}

// MARK: - 提示条（深色玻璃 rgba(24,26,34,.95) = DuduTheme.overlayBg）
// 14D：识别流式文本移到主 App 听写页，这里改为按账户态的静态引导文案

private struct HintBar: View {
    @ObservedObject var model: KeyboardViewModel

    private var hint: String {
        switch model.account {
        case .ok, .trial:
            return "按一下说话 · 说完回到这里自动上屏"
        case .guest:
            return "登录后开始用"
        case .quota:
            return "时长用完了 · 充值后接着说"
        }
    }

    var body: some View {
        HStack {
            Text(hint)
                .font(.system(size: DuduTheme.textMd))
                .foregroundStyle(DuduTheme.overlayText3)
            Spacer(minLength: 0)
        }
        .padding(.vertical, 9)
        .padding(.horizontal, 12)
        .frame(minHeight: 40, alignment: .leading)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(DuduTheme.overlayBg)
        .clipShape(RoundedRectangle(cornerRadius: DuduTheme.radiusMd))
    }
}

// MARK: - MicBar（56 胶囊；14D：按一下 deep link 去主 App 听写，不再按住录音）

private struct MicBarView: View {
    @ObservedObject var model: KeyboardViewModel

    private enum BarState { case idle, disabled, quota }

    private var barState: BarState {
        switch model.account {
        case .ok, .trial: return .idle
        case .guest: return .disabled
        case .quota: return .quota
        }
    }

    var body: some View {
        Button(action: tap) {
            HStack(spacing: DuduTheme.space2) {
                Image(systemName: "mic")
                    .font(.system(size: 20))
                Text(label)
                    .font(.system(size: DuduTheme.textMd, weight: .semibold))
            }
            .foregroundStyle(foreground)
            .frame(maxWidth: .infinity)
            .frame(height: DuduTheme.controlXl)
            .background(Capsule().fill(background))
            .contentShape(Capsule())
        }
        .buttonStyle(.plain)
    }

    private func tap() {
        switch barState {
        case .idle: model.onOpenApp("dictate")      // 14D：去主 App 听写
        case .disabled: model.onOpenApp("login")    // guest：先登录
        case .quota: model.onOpenApp("purchase")    // quota：去充值
        }
    }

    private var label: String {
        switch barState {
        case .idle: return "按一下 · 去 dudu 说话"
        case .disabled: return "登录后开始用 · 打开 dudu"
        case .quota: return "时长用完了 · 去充值"
        }
    }

    private var background: Color {
        switch barState {
        case .idle: return DuduTheme.accent
        case .disabled: return DuduTheme.surface3
        case .quota: return DuduTheme.warning
        }
    }

    private var foreground: Color {
        barState == .disabled ? DuduTheme.text3 : DuduTheme.textOnAccent
    }
}

// MARK: - 功能键行：地球(1.3) / ，/ 。/ 退格(1.3) / 回车(1.3)，键帽高 40 圆角 6

private struct FunctionKeyRow: View {
    @ObservedObject var model: KeyboardViewModel
    weak var inputController: UIInputViewController?

    private let spacing: CGFloat = 6

    var body: some View {
        GeometryReader { geo in
            row(unit: unitWidth(total: geo.size.width))
        }
        .frame(height: 40)
    }

    /// 键宽基数：地球/退格/回车占 1.3 份，，。各占 1 份
    private func unitWidth(total: CGFloat) -> CGFloat {
        let totalFlex: CGFloat = model.needsInputModeSwitch ? 5.9 : 4.6
        let keyCount: CGFloat = model.needsInputModeSwitch ? 5 : 4
        return (total - spacing * (keyCount - 1)) / totalFlex
    }

    private func row(unit: CGFloat) -> some View {
        HStack(spacing: spacing) {
            if model.needsInputModeSwitch {
                InputModeSwitchKey(inputController: inputController)
                    .frame(width: unit * 1.3, height: 40)
                    .background(keycapBackground)
            }
            key("，", width: unit) { model.onInsert("，") }
            key("。", width: unit) { model.onInsert("。") }
            iconKey("delete.left", width: unit * 1.3) { model.onDelete() }
            iconKey("return", width: unit * 1.3) { model.onReturn() }
        }
    }

    private var keycapBackground: some View {
        RoundedRectangle(cornerRadius: DuduTheme.radiusSm)
            .fill(DuduTheme.surfaceCard)
            .shadow(color: .black.opacity(0.18), radius: 0, y: 1) // shadow-key 底边
    }

    private func key(_ title: String, width: CGFloat, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Text(title)
                .font(.system(size: DuduTheme.textMd))
                .foregroundStyle(DuduTheme.text1)
                .frame(width: width, height: 40)
                .background(keycapBackground)
        }
        .buttonStyle(.plain)
    }

    private func iconKey(_ systemName: String, width: CGFloat, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Image(systemName: systemName)
                .font(.system(size: 17))
                .foregroundStyle(DuduTheme.text1)
                .frame(width: width, height: 40)
                .background(keycapBackground)
        }
        .buttonStyle(.plain)
    }
}

/// 地球键：handleInputModeList(from:with:) 只能走 UIKit target-action（系统据此弹键盘切换菜单），
/// 因此用 UIViewRepresentable 桥接一个 UIButton。
private struct InputModeSwitchKey: UIViewRepresentable {
    weak var inputController: UIInputViewController?

    func makeUIView(context: Context) -> UIButton {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: "globe"), for: .normal)
        button.tintColor = UIColor.label
        if let controller = inputController {
            // allTouchEvents：长按弹输入法列表、轻点直接切换，均由系统处理
            button.addTarget(controller,
                             action: #selector(UIInputViewController.handleInputModeList(from:with:)),
                             for: .allTouchEvents)
        }
        return button
    }

    func updateUIView(_ uiView: UIButton, context: Context) {}
}
