/**
 * DatePicker Component Module
 */
globalThis.Component.register('DatePicker', container => {
    container._thisObj = container;
        container.state = globalThis.NewState({ start: '', end: '' })

        container.addEventListener('bind', e => {
                container.state.start = e.detail || ''
                const form = container.closest('AutoForm')
                const name = container.getAttribute('name')
                const item = form?.state?.schema?.find(i => i.name === name)
                const rangeEnd = item?.setting?.rangeEnd || container.rangeEnd
                if (form && rangeEnd) {
                        container.state.end = form.data[rangeEnd] || ''
                }
        })

        Object.defineProperty(container, 'isRange', {
                get: () => {
                        const form = container.closest('AutoForm')
                        const name = container.getAttribute('name')
                        const item = form?.state?.schema?.find(i => i.name === name)
                        return !!(item?.setting?.rangeEnd || container.rangeEnd)
                }
        })

        Object.defineProperty(container, 'value', {
                get: () => container.state.start,
                set: v => { container.state.start = v || ''; }
        })

        container.updateStart = (val) => {
                container.state.start = val
                container.dispatchEvent(new CustomEvent('change', { bubbles: true, detail: val }))
        }

        container.updateEnd = (val) => {
                container.state.end = val
                const form = container.closest('AutoForm')
                const name = container.getAttribute('name')
                const item = form?.state?.schema?.find(i => i.name === name)
                const rangeEnd = item?.setting?.rangeEnd || container.rangeEnd
                if (form && rangeEnd) {
                        form.data[rangeEnd] = val
                }
        }
}, globalThis.Util.makeDom(/*html*/`
<div class="d-flex align-items-center gap-1 w-100">
  <input type="date" class="form-control h-100" $bind="this.state.start" $onchange="this.updateStart(thisNode.value)">
  <template $if="this.isRange">
    <span class="text-muted mx-1">-</span>
    <input type="date" class="form-control h-100" $bind="this.state.end" $onchange="this.updateEnd(thisNode.value)">
  </template>
</div>
`))

if (globalThis.AutoForm) {
    globalThis.AutoForm.register('DatePicker')
}
