// appui/assets/js/alpine.js
import Alpine from 'alpinejs'
import sort from '@alpinejs/sort'
import collapse from '@alpinejs/collapse'

import TimeAgo from '@marcreichel/alpine-timeago';
import { format } from 'date-fns'
import { de, enUS } from 'date-fns/locale'

Alpine.plugin(collapse)
Alpine.plugin(sort)
// locale from PHP
let localeCode = window.APP_LOCALE || 'en'
let locale = enUS

switch (localeCode) {
    case 'de':
        locale = de
        break
    case 'en':
        locale = enUS
        break
    default:
        locale = enUS
        break
}

Alpine.plugin(TimeAgo.configure({
    locale: locale,
}))

Alpine.data('animatedNumber', (initialValue) => ({
    displayValue: initialValue,
    isAnimating: true,
    update(newValue) {
        if (this.displayValue === newValue) return;

        this.isAnimating = false; // Reset animation state
        this.displayValue = newValue;

        this.$nextTick(() => {
            this.$el.offsetHeight; // Force reflow to restart animation
            this.isAnimating = true;
        });
    },
    get digits() {
        return String(this.displayValue).split('');
    }
}));

window.Alpine = Alpine
Alpine.start()

// ---- BeezUI globals (date-fns based formatting + schedule summary helper) ----
;(function(){

  const g = (typeof window !== 'undefined') ? window : globalThis
  g.BeezUI = g.BeezUI || {}

  // Expose the chosen date-fns locale so helpers can use it
  g.BeezUI.locale = (typeof locale !== 'undefined') ? locale : enUS

  // Safe date parser for "YYYY-MM-DD" or any Date-parsable input
  function toDateSafe(v) {
    if (!v) return null
    try {
      const s = String(v)
      // Prefer interpreting as local midnight when date-only string
      const d = (s.length >= 10 && /^\d{4}-\d{2}-\d{2}/.test(s)) ? new Date(s + 'T00:00:00') : new Date(s)
      return isNaN(d.getTime()) ? null : d
    } catch (_) { return null }
  }

  // Localized date formatter. Default pattern uses locale-appropriate medium date.
  g.BeezUI.formatDate = function(value, pattern = 'PP') {
    const d = toDateSafe(value)
    if (!d) return String(value ?? '')
    try { return format(d, pattern, { locale: g.BeezUI.locale || enUS }) } catch (_) { return d.toLocaleDateString() }
  }

  // Helper to seed start/end if empty: start = tomorrow, end = start+7 days
  // src: optional reactive form object; falls back to window.form
  g.BeezUI.seedDefaultStartEnd = function(startField, endField, src) {
    try {
      const form = src || g.form
      if (!form) return
      const sName = String(startField)
      const eName = String(endField)
      const d = new Date(); d.setHours(0,0,0,0); d.setDate(d.getDate()+1)
      const fmt = (dd)=> dd.getFullYear()+ '-' + String(dd.getMonth()+1).padStart(2,'0') + '-' + String(dd.getDate()).padStart(2,'0')

      const isInvalid = (v) => !v || v === '1000-01-01' || v === '0000-00-00' || v.startsWith('0000');

      if (isInvalid(form[sName])) form[sName] = fmt(d)

      // Only seed end date if schedule type requires it (e.g. scheduled_window)
      // Bulk mail and Automation default to no end date (completed / never)
      const st = form['schedule_type'] || 'bulk_mail'
      if (st !== 'bulk_mail' && st !== 'automation') {
        if (isInvalid(form[eName])) {
          const e = new Date(d); e.setDate(e.getDate()+7)
          form[eName] = fmt(e)
        }
      }
    } catch(_) { /* no-op */ }
  }

  // Build a localized schedule summary line using a provided source (Alpine form) or global form
  // fieldMap: { schedule_type, start_mode, start_date, end_date, automation_end }
  // tokens: { starts_now, starts_on, stops_finished, stops_on, runs_indefinitely, on_word? }
  // src: the reactive object that holds field values (e.g., Alpine 'form'); falls back to window.form
  g.BeezUI.scheduleSummary = function(fieldMap, tokens, src) {
    try {
      const form = src || g.form || {}
      const f = fieldMap || {}
      const t = tokens || {}
      const sm = form[f.start_mode] || 'now'
      const sd = form[f.start_date] || ''
      const st = form[f.schedule_type] || ''
      const ed = form[f.end_date] || ''
      const ae = form[f.automation_end] || 'never'

      // Locale-aware preposition between verb and date (e.g., "on" in EN, "am" in DE)
      const lc = String(g.APP_LOCALE || '').toLowerCase()
      const joiner = ' '; // (typeof t.on_word === 'string' && t.on_word) ? ' ' + t.on_word.trim() + ' ': (lc.startsWith('de') ? ' am ' : ' on ')

      const parts = []
      if (sm === 'date' && sd) parts.push((t.starts_on || 'Starts') + joiner + g.BeezUI.formatDate(sd))
      else parts.push(t.starts_now || 'Starts immediately')

      if (st === 'bulk_mail') {
        parts.push(t.stops_finished || 'Stops when finished')
        if (ed) parts.push((t.stops_on || 'Stops') + joiner + g.BeezUI.formatDate(ed))
      } else if (st === 'scheduled_window') {
        if (ed) parts.push((t.stops_on || 'Stops') + joiner + g.BeezUI.formatDate(ed))
      } else if (st === 'automation') {
        if (ae === 'date' && ed) parts.push((t.stops_on || 'Stops') + joiner + g.BeezUI.formatDate(ed))
        else parts.push(t.runs_indefinitely || 'Runs indefinitely')
      }
      return parts.join('. ') + '.'
    } catch(_) { return '' }
  }
})()