class Leaderboard {
    constructor(songId, difficulty, songTitle, onClose) {
        this.songId = songId
        this.difficulty = difficulty
        this.songTitle = songTitle
        this.onClose = onClose
        this.entries = []
        this.loading = true
        this.error = null
        this.font = strings.font

        this.init()
    }

    init() {
        this.createModal()
        this.fetchLeaderboard()
        this.addEventListeners()
    }

    createModal() {
        // Create overlay
        this.overlay = document.createElement("div")
        this.overlay.id = "leaderboard-overlay"
        this.overlay.innerHTML = `
			<div id="leaderboard-modal">
				<div id="leaderboard-header">
					<div id="leaderboard-title">${strings.leaderboardTitle}</div>
					<div id="leaderboard-song-title">${this.songTitle}</div>
					<div id="leaderboard-difficulty">${this.getDifficultyName()}</div>
				</div>
				<div id="leaderboard-content">
					<div id="leaderboard-loading">${strings.loading}</div>
				</div>
				<div id="leaderboard-footer">
					<button id="leaderboard-close-btn">${strings.close}</button>
				</div>
			</div>
		`
        document.body.appendChild(this.overlay)
    }

    getDifficultyName() {
        const diffNames = {
            easy: strings.easy,
            normal: strings.normal,
            hard: strings.hard,
            oni: strings.oni,
            ura: strings.oni
        }
        return diffNames[this.difficulty] || this.difficulty
    }

    addEventListeners() {
        this.overlay.querySelector("#leaderboard-close-btn").addEventListener("click", () => this.close())
        this.overlay.addEventListener("click", (e) => {
            if (e.target === this.overlay) {
                this.close()
            }
        })

        // Keyboard support
        this.keyHandler = (e) => {
            if (e.key === "Escape") {
                this.close()
            }
        }
        document.addEventListener("keydown", this.keyHandler)
    }

    fetchLeaderboard() {
        const url = `api/leaderboard?song_id=${encodeURIComponent(this.songId)}&difficulty=${encodeURIComponent(this.difficulty)}`

        loader.ajax(url).then(response => {
            const data = JSON.parse(response)
            if (data.status === "ok") {
                this.entries = data.entries
                this.monthKey = data.month_key
                this.loading = false
                this.render()
            } else {
                throw new Error("Failed to load leaderboard")
            }
        }).catch(error => {
            console.error("Leaderboard fetch error:", error)
            this.error = error
            this.loading = false
            this.render()
        })
    }

    render() {
        const content = this.overlay.querySelector("#leaderboard-content")

        if (this.error) {
            content.innerHTML = `<div id="leaderboard-error">${strings.errorOccured}</div>`
            return
        }

        if (this.entries.length === 0) {
            content.innerHTML = `<div id="leaderboard-empty">${strings.noEntries}</div>`
            return
        }

        // Build entries table
        let html = `
			<div id="leaderboard-table">
				<div class="leaderboard-row leaderboard-header-row">
					<div class="leaderboard-rank">${strings.leaderboardRank}</div>
					<div class="leaderboard-name">${strings.leaderboardPlayer}</div>
					<div class="leaderboard-score">${strings.leaderboardScore}</div>
				</div>
		`

        for (const entry of this.entries) {
            const rankClass = entry.rank <= 3 ? `leaderboard-rank-${entry.rank}` : ""
            html += `
				<div class="leaderboard-row ${rankClass}">
					<div class="leaderboard-rank">${entry.rank}</div>
					<div class="leaderboard-name">${this.escapeHtml(entry.username)}</div>
					<div class="leaderboard-score">${entry.score_value.toLocaleString()}</div>
				</div>
			`
        }

        html += `</div>`
        content.innerHTML = html
    }

    escapeHtml(text) {
        const div = document.createElement("div")
        div.textContent = text
        return div.innerHTML
    }

    close() {
        document.removeEventListener("keydown", this.keyHandler)
        this.overlay.remove()
        if (this.onClose) {
            this.onClose()
        }
    }
}

// Score submission modal for when players qualify for leaderboard
class LeaderboardSubmit {
    constructor(songId, difficulty, score, rank, onSubmit, onClose) {
        this.songId = songId
        this.difficulty = difficulty
        this.score = score
        this.rank = rank
        this.onSubmit = onSubmit
        this.onClose = onClose
        this.submitting = false

        this.init()
    }

    init() {
        this.createModal()
        this.addEventListeners()
    }

    createModal() {
        this.overlay = document.createElement("div")
        this.overlay.id = "leaderboard-submit-overlay"

        const rankText = strings.newRecord.replace("%s", this.rank)

        this.overlay.innerHTML = `
			<div id="leaderboard-submit-modal">
				<div id="leaderboard-submit-title">${rankText}</div>
				<div id="leaderboard-submit-score">${this.score.toLocaleString()} ${strings.points}</div>
				<div id="leaderboard-submit-form">
					<label for="leaderboard-name-input">${strings.enterName}</label>
					<input type="text" id="leaderboard-name-input" maxlength="10" autocomplete="off">
				</div>
				<div id="leaderboard-submit-buttons">
					<button id="leaderboard-submit-btn">${strings.submit}</button>
					<button id="leaderboard-cancel-btn">${strings.cancel}</button>
				</div>
			</div>
		`
        document.body.appendChild(this.overlay)

        // Focus input
        setTimeout(() => {
            this.overlay.querySelector("#leaderboard-name-input").focus()
        }, 100)
    }

    addEventListeners() {
        const submitBtn = this.overlay.querySelector("#leaderboard-submit-btn")
        const cancelBtn = this.overlay.querySelector("#leaderboard-cancel-btn")
        const input = this.overlay.querySelector("#leaderboard-name-input")

        submitBtn.addEventListener("click", () => this.submit())
        cancelBtn.addEventListener("click", () => this.close())

        input.addEventListener("keydown", (e) => {
            if (e.key === "Enter") {
                this.submit()
            } else if (e.key === "Escape") {
                this.close()
            }
        })
    }

    submit() {
        if (this.submitting) return

        const input = this.overlay.querySelector("#leaderboard-name-input")
        const username = input.value.trim()

        if (username.length < 1 || username.length > 10) {
            input.classList.add("error")
            return
        }

        this.submitting = true
        const submitBtn = this.overlay.querySelector("#leaderboard-submit-btn")
        submitBtn.disabled = true
        submitBtn.textContent = strings.loading

        const data = {
            song_id: String(this.songId),
            difficulty: this.difficulty,
            username: username,
            score: this.score
        }

        const xhr = new XMLHttpRequest()
        xhr.open("POST", "api/score/leaderboard/save")
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.onload = () => {
            if (xhr.status === 200) {
                try {
                    const result = JSON.parse(xhr.responseText)
                    if (result.status === "ok") {
                        this.close()
                        if (this.onSubmit) {
                            this.onSubmit(username)
                        }
                    } else {
                        handleError(result.message || "Submit failed")
                    }
                } catch (e) {
                    handleError("Invalid response")
                }
            } else {
                handleError("Server error " + xhr.status)
            }
        }
        xhr.onerror = () => {
            handleError("Network error")
        }

        const handleError = (msg) => {
            console.error("Leaderboard submit error:", msg)
            this.submitting = false
            submitBtn.disabled = false
            submitBtn.textContent = strings.submit
            input.classList.add("error")
        }

        xhr.send(JSON.stringify(data))
    }

    close() {
        this.overlay.remove()
        if (this.onClose) {
            this.onClose()
        }
    }
}
