import { api } from '../lib/api.mjs'; class WoForm extends HTMLElement { #woId = null; #wo = null; static get observedAttributes() { return ['wo-id']; } attributeChangedCallback(_, __, val) { this.#woId = val ? +val : null; this.#load(); } connectedCallback() { this.attachShadow({ mode: 'open' }); this.#render(); if (this.#woId) this.#load(); } async #load() { if (!this.#woId) return; this.#wo = await api.get(`/work-orders/${this.#woId}`); this.#render(); } #render() { const wo = this.#wo ?? {}; this.shadowRoot.innerHTML = `
`; this.shadowRoot.querySelector('#cancel').addEventListener('click', () => this.dispatchEvent(new CustomEvent('wo:cancel', { bubbles: true, composed: true }))); this.shadowRoot.querySelector('form').addEventListener('submit', async e => { e.preventDefault(); // Read fields directly — Shadow DOM + FormData has unreliable browser support const val = name => (this.shadowRoot.querySelector(`[name="${name}"]`)?.value ?? '').trim(); // datetime-local gives "YYYY-MM-DDTHH:MM"; convert to full ISO so Go can parse it const dt = name => { const v = val(name); return v ? new Date(v).toISOString() : null; }; const body = { title: val('title'), priority: val('priority') || 'normal', site_name: val('site_name'), address: val('address'), scheduled_start: dt('scheduled_start'), scheduled_end: dt('scheduled_end'), description: val('description'), instructions: val('instructions'), access_notes: val('access_notes'), }; if (!body.title) { this.shadowRoot.querySelector('#err').textContent = 'Title is required.'; return; } this.shadowRoot.querySelector('#err').textContent = ''; try { const wo = this.#woId ? await api.put(`/work-orders/${this.#woId}`, body) : await api.post('/work-orders', body); this.dispatchEvent(new CustomEvent('wo:saved', { detail: { wo }, bubbles: true, composed: true })); } catch (err) { this.shadowRoot.querySelector('#err').textContent = err.message; } }); } } customElements.define('wo-form', WoForm);