//
//  MenuViewController.swift
//  DashSmash
//
//  Title screen. Player picks a song source (library, Apple Music search,
//  MIDI search) or jumps back into a saved level.
//

import UIKit

final class MenuViewController: UIViewController {

    /// Flip to `true` once the project is enrolled in the Apple Developer
    /// Program and the MusicKit capability is enabled on the App ID — at
    /// that point the "Search Apple Music" entry reappears. Without the
    /// entitlement, MusicKit catalog requests return 403, so the button is
    /// hidden to avoid surfacing a broken flow.
    private static let appleMusicEnabled = false

    private let titleLabel = UILabel()
    private let subtitleLabel = UILabel()
    private let libraryButton = UIButton(type: .system)
    private let appleMusicButton = UIButton(type: .system)
    private let midiButton = UIButton(type: .system)
    private let savedButton = UIButton(type: .system)
    private let runnerToggleRow = UIView()
    private let runnerToggleLabel = UILabel()
    private let runnerToggleSwitch = UISwitch()
    private let scrollView = UIScrollView()
    private let stack = UIStackView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        setupUI()
    }

    override var prefersStatusBarHidden: Bool { true }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask { .allButUpsideDown }

    private func setupUI() {
        titleLabel.text = "GROOVE RIDER"
        titleLabel.textColor = .white
        titleLabel.font = UIFont(name: "AvenirNext-Heavy", size: 44) ?? UIFont.boldSystemFont(ofSize: 44)
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        titleLabel.lineBreakMode = .byWordWrapping
        titleLabel.adjustsFontSizeToFitWidth = true
        titleLabel.minimumScaleFactor = 0.6

        subtitleLabel.text = "Pick a song to play"
        subtitleLabel.textColor = UIColor.white.withAlphaComponent(0.7)
        subtitleLabel.font = UIFont(name: "AvenirNext-Medium", size: 15) ?? UIFont.systemFont(ofSize: 15)
        subtitleLabel.numberOfLines = 0
        subtitleLabel.textAlignment = .center

        stylePrimary(libraryButton, title: "Pick from Your Library")
        libraryButton.addTarget(self, action: #selector(libraryTapped), for: .touchUpInside)

        if Self.appleMusicEnabled {
            styleSecondary(appleMusicButton, title: "Search Apple Music")
            appleMusicButton.addTarget(self, action: #selector(appleMusicTapped), for: .touchUpInside)
        }

        styleSecondary(midiButton, title: "Search MIDI")
        midiButton.addTarget(self, action: #selector(midiTapped), for: .touchUpInside)

        styleSecondary(savedButton, title: "Saved Levels")
        savedButton.addTarget(self, action: #selector(savedTapped), for: .touchUpInside)

        configureRunnerToggleRow()

        scrollView.alwaysBounceVertical = true
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(scrollView)

        stack.axis = .vertical
        stack.spacing = 16
        stack.alignment = .fill
        stack.translatesAutoresizingMaskIntoConstraints = false

        stack.addArrangedSubview(titleLabel)
        stack.addArrangedSubview(subtitleLabel)
        stack.setCustomSpacing(36, after: subtitleLabel)
        stack.addArrangedSubview(libraryButton)
        if Self.appleMusicEnabled {
            stack.addArrangedSubview(appleMusicButton)
        }
        stack.addArrangedSubview(midiButton)
        stack.addArrangedSubview(savedButton)
        stack.setCustomSpacing(28, after: savedButton)
        stack.addArrangedSubview(runnerToggleRow)

        scrollView.addSubview(stack)
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),

            stack.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor, constant: 24),
            stack.leadingAnchor.constraint(equalTo: scrollView.frameLayoutGuide.leadingAnchor, constant: 32),
            stack.trailingAnchor.constraint(equalTo: scrollView.frameLayoutGuide.trailingAnchor, constant: -32),
            stack.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -24),
            libraryButton.heightAnchor.constraint(equalToConstant: 56),
            midiButton.heightAnchor.constraint(equalToConstant: 48),
            savedButton.heightAnchor.constraint(equalToConstant: 48)
        ])
        if Self.appleMusicEnabled {
            appleMusicButton.heightAnchor.constraint(equalToConstant: 48).isActive = true
        }
    }

    private func stylePrimary(_ button: UIButton, title: String) {
        button.setTitle(title, for: .normal)
        button.titleLabel?.font = UIFont(name: "AvenirNext-Heavy", size: 22) ?? .boldSystemFont(ofSize: 22)
        button.setTitleColor(.black, for: .normal)
        button.backgroundColor = .white
        button.layer.cornerRadius = 12
    }

    private func styleSecondary(_ button: UIButton, title: String) {
        button.setTitle(title, for: .normal)
        button.titleLabel?.font = UIFont(name: "AvenirNext-Medium", size: 17) ?? .systemFont(ofSize: 17)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .clear
        button.layer.cornerRadius = 12
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.white.withAlphaComponent(0.35).cgColor
    }

    @objc private func libraryTapped() {
        let host = LibraryPickerHostViewController()
        navigationController?.pushViewController(host, animated: true)
    }

    @objc private func appleMusicTapped() {
        let picker = AppleMusicPickerViewController()
        navigationController?.pushViewController(picker, animated: true)
    }

    @objc private func midiTapped() {
        let picker = MIDIPickerViewController()
        navigationController?.pushViewController(picker, animated: true)
    }

    @objc private func savedTapped() {
        let vc = SavedLevelsViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    // MARK: - Runner toggle

    private func configureRunnerToggleRow() {
        runnerToggleLabel.text = "Use Runner Character"
        runnerToggleLabel.textColor = UIColor.white.withAlphaComponent(0.85)
        runnerToggleLabel.font = UIFont(name: "AvenirNext-Medium", size: 15) ?? .systemFont(ofSize: 15)
        runnerToggleLabel.translatesAutoresizingMaskIntoConstraints = false

        runnerToggleSwitch.isOn = UserSettings.shared.useRunnerCharacter
        runnerToggleSwitch.onTintColor = UIColor(white: 0.95, alpha: 1)
        runnerToggleSwitch.translatesAutoresizingMaskIntoConstraints = false
        runnerToggleSwitch.addTarget(self, action: #selector(runnerToggleChanged), for: .valueChanged)

        runnerToggleRow.translatesAutoresizingMaskIntoConstraints = false
        runnerToggleRow.addSubview(runnerToggleLabel)
        runnerToggleRow.addSubview(runnerToggleSwitch)
        NSLayoutConstraint.activate([
            runnerToggleLabel.leadingAnchor.constraint(equalTo: runnerToggleRow.leadingAnchor),
            runnerToggleLabel.centerYAnchor.constraint(equalTo: runnerToggleRow.centerYAnchor),
            runnerToggleSwitch.trailingAnchor.constraint(equalTo: runnerToggleRow.trailingAnchor),
            runnerToggleSwitch.centerYAnchor.constraint(equalTo: runnerToggleRow.centerYAnchor),
            runnerToggleRow.heightAnchor.constraint(equalToConstant: 36)
        ])
    }

    @objc private func runnerToggleChanged(_ sender: UISwitch) {
        UserSettings.shared.useRunnerCharacter = sender.isOn
    }
}
