// Componente centralizado de DatePicker (Flatpickr) — padrão dd-mm-yyyy, locale pt-BR
// Sem dependências adicionais além do Flatpickr
(function(){
  function isISO(s){ return /^\d{4}-\d{2}-\d{2}$/.test(String(s||'')); }
  function isSlashBR(s){ return /^\d{2}\/\d{2}\/\d{4}$/.test(String(s||'')); }
  function toBR(s){
    if (!s) return '';
    try {
      if (typeof window !== 'undefined' && typeof window.fmtDateBR === 'function') return window.fmtDateBR(s);
    } catch(_){}
    const d = new Date(s); if (isNaN(d)) return String(s);
    const pad = n=>String(n).padStart(2,'0');
    return `${pad(d.getDate())}-${pad(d.getMonth()+1)}-${d.getFullYear()}`;
  }
  function parseBR(str){
    if (!str) return null;
    const m = String(str).match(/^(\d{2})-(\d{2})-(\d{4})$/);
    if (!m) return null;
    const dd = Number(m[1]); const mm = Number(m[2]) - 1; const yyyy = Number(m[3]);
    const d = new Date(yyyy, mm, dd);
    return isNaN(d) ? null : d;
  }
  function setValidity(inp, valid){ inp.setAttribute('aria-invalid', valid ? 'false' : 'true'); }

  function normalizeInput(inp){
    if (!inp || inp.dataset.datepickerInitialized === '1') return;
    // Transformar type=date para text mantendo atributos
    const isNative = (inp.type && inp.type.toLowerCase() === 'date');
    if (isNative) {
      try {
        const cur = inp.value;
        inp.setAttribute('type','text');
        if (!inp.placeholder) inp.setAttribute('placeholder','dd-mm-yyyy');
        if (cur) inp.value = toBR(cur);
      } catch(_){}
    } else {
      if (!inp.placeholder) inp.setAttribute('placeholder','dd-mm-yyyy');
    }
    inp.setAttribute('pattern','\\d{2}-\\d{2}-\\d{4}');
    if (!inp.classList.contains('js-datepicker')) inp.classList.add('js-datepicker');
    inp.setAttribute('aria-haspopup','dialog');
    inp.setAttribute('autocomplete','off');
    // Normalizar valores já presentes (retrocompatibilidade)
    if (isISO(inp.value)) inp.value = toBR(inp.value);
    else if (isSlashBR(inp.value)) inp.value = String(inp.value).replace(/\//g,'-');
    setValidity(inp, !!parseBR(inp.value));
    // Validação e normalização automática em input/change/blur
    const onUserInput = ()=>{
      const v = inp.value;
      if (isISO(v)) inp.value = toBR(v);
      else if (isSlashBR(v)) inp.value = v.replace(/\//g,'-');
      const d = parseBR(inp.value);
      setValidity(inp, !!d);
    };
    inp.addEventListener('input', onUserInput);
    inp.addEventListener('change', onUserInput);
    inp.addEventListener('blur', onUserInput);
  }

  function initOne(inp, opts){
    normalizeInput(inp);
    try {
      const instance = flatpickr(inp, {
        dateFormat: 'd-m-Y',
        allowInput: true,
        disableMobile: true,
        locale: (window.flatpickr && window.flatpickr.l10ns && window.flatpickr.l10ns.pt) ? window.flatpickr.l10ns.pt : undefined,
        ...opts,
        onOpen: [function(){ inp.setAttribute('aria-expanded','true'); }].concat(opts && opts.onOpen || []),
        onClose: [function(){ inp.setAttribute('aria-expanded','false'); }].concat(opts && opts.onClose || []),
        onChange: [function(selectedDates, dateStr){
          // Garantir formato dd-mm-yyyy no valor do input
          try {
            if (selectedDates && selectedDates[0] instanceof Date) {
              inp.value = toBR(selectedDates[0]);
            } else if (dateStr) {
              inp.value = isISO(dateStr) ? toBR(dateStr) : dateStr;
            }
          } catch(_){}
          setValidity(inp, !!parseBR(inp.value));
        }].concat(opts && opts.onChange || []),
      });
      inp.dataset.datepickerInitialized = '1';
      return instance;
    } catch(e){ return null; }
  }

  function init(selector, options){
    if (typeof flatpickr === 'undefined') return false;
    const sel = selector || 'input.js-datepicker, input[type="date"]:not([data-native-date="true"])';
    const nodes = Array.from(document.querySelectorAll(sel));
    nodes.forEach(inp => initOne(inp, options||{}));
    return true;
  }

  function refresh(container){
    const root = container || document;
    init(null, {});
  }

  window.DatePicker = { init, refresh };
})();