import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="theme"
export default class extends Controller {
    static targets = ["toggle"]

    connect() {
        this.initTheme()
    }

    initTheme() {
        const savedTheme = localStorage.getItem('theme')
        if(savedTheme) {
            document.documentElement.setAttribute('data-theme', savedTheme)
            this.toggleTarget.checked = savedTheme === 'dark'
        }
    }

    toggle(event) {
        const newTheme = event.target.checked ? 'dark' : 'light'
        document.documentElement.setAttribute('data-theme', newTheme)
        localStorage.setItem('theme', newTheme)
    }
}
