const app = window.app ??= {}
const view = window.view ??= {}

import * as browser from './browser.js'
import * as player from './player.js'
import * as queue from './queue.js'

export let modules
export const states = {
    PLAYER: 0,
    BROWSER: 1,
    QUEUE: 2
}

export const Init = (name) => {
    app.mode = 1
}

export const View = async () => {
    view.tab = {
        focusedGapLeft: 0
    }
    view.tab.indicator = document.getElementById('tab-indicator')
    view.tab.indicatorLine = document.getElementById('tab-indicator-line')
    view.tab.bar = document.getElementById('tabs')

    modules = new Array(3)
    modules[states.PLAYER] = player
    modules[states.BROWSER] = browser
    modules[states.QUEUE] = queue

    view.tab.order = []

    for(let m of modules) {
        let t = renderTab()
        view.tab.order.push(t)
        await m.View(t)
    }    
    Render()
}

export const renderTab = () => {
    let e = document.createElement('button')
    view.tab.bar.appendChild(e)
    return e
}

export const Display = (name) => {
    document.body.classList = [ name ]
}

export const Render = () => {
    modules[app.mode].Open()

    changeFocus()
    updateIndicator()
    scrollToFocus()
}

export const changeFocus = () => {
    view.tab.focus?.classList.remove('selected')
    view.tab.focus = view.tab.order[app.mode]
    view.tab.focus.classList.add('selected')
}

export const scrollToFocus = () => {
    view.tab.bar.scrollLeft = view.tab.focus.offsetLeft - view.tab.focusedGapLeft
}

export const indicatorMargin = 2
export const updateIndicator = () => {
    let before = 0
    let dashes = []
    let r = 100 - (indicatorMargin * (modules.length - 1))
    let pd = getPrimaryDashWidth()
    let sdc = modules.length - 1
    let sdr = r - pd
    let sd = parseInt(sdr / sdc)
    pd += sdr % sdc

    console.log(r, sdc, pd, sd)

    for(let i = 0; i < modules.length; i++) {
        if(i < app.mode) {
            before += sd + indicatorMargin
        }
        dashes.push(i === app.mode ? pd : sd)
    }

    console.log(dashes, view)

    view.tab.indicatorLine.style.strokeDasharray = dashes
        .join(', ' + indicatorMargin + ', ')
    view.tab.focusedGapLeft = (before / 100) * view.tab.indicator.clientWidth
}

export const getPrimaryDashWidth = () => {
    return parseInt( (view.tab.focus.clientWidth / view.tab.indicator.clientWidth) * 100 )
}

export const Set = (iMode) => {
    app.mode = iMode
    Render()
}

export const Scroll = (distance) => {
    let i = distance + app.mode
    if(i < 0) i = modules.length - 1
    else if(i >= modules.length) i = 0 
    Set(i)
}

export const OnKeydown = (event) => {
    return modules[app.mode].OnKeydown(event)
}