// ─────────────────────────────────────────────
// DO_Fields_DateTime.jsx
// DateField, TimeField (Flatpickr), DateTimeField
// Requires: DO_Shared.jsx (S, FieldLabel)
// Requires: Flatpickr CSS+JS loaded in index.html
// ─────────────────────────────────────────────

// ── Date formatting helper ───────────────────
function formatDate(val, fmt) {
  if (!val) return '';
  const parts = String(val).split('-');
  if (parts.length !== 3) return val;
  const y = parseInt(parts[0]), m = parseInt(parts[1]) - 1, d = parseInt(parts[2]);
  const dt = new Date(y, m, d);
  if (isNaN(dt)) return val;
  const MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const MONTHS_LONG  = ['January','February','March','April','May','June',
                        'July','August','September','October','November','December'];
  const mm   = String(m + 1).padStart(2, '0');
  const dd   = String(d).padStart(2, '0');
  const yyyy = String(y);
  switch (fmt) {
    case 'DD/MM/YYYY':  return `${dd}/${mm}/${yyyy}`;
    case 'YYYY-MM-DD':  return `${yyyy}-${mm}-${dd}`;
    case 'MMM D YYYY':  return `${MONTHS_SHORT[m]} ${d} ${yyyy}`;
    case 'MMMM D YYYY': return `${MONTHS_LONG[m]} ${d} ${yyyy}`;
    case 'D MMM YYYY':  return `${d} ${MONTHS_SHORT[m]} ${yyyy}`;
    case 'MM/DD/YYYY':
    default:            return `${mm}/${dd}/${yyyy}`;
  }
}

// ── Time formatting helper ───────────────────
function formatTime(val, fmt) {
  if (!val) return '';
  const parts = String(val).split(':');
  if (parts.length < 2) return val;
  const h24 = parseInt(parts[0]);
  const min  = parts[1].padStart(2, '0');
  if (fmt === '24' || !fmt) return `${String(h24).padStart(2,'0')}:${min}`;
  const ampm = h24 >= 12 ? 'PM' : 'AM';
  const h12  = h24 % 12 || 12;
  return `${h12}:${min} ${ampm}`;
}

// ─────────────────────────────────────────────
// DATE FIELD
// Displays formatted date, click to open native picker
// Stores YYYY-MM-DD, displays per obj.dateformat
// ─────────────────────────────────────────────
function DateField({ obj, value, onChange, onBlur }) {
  const [editing, setEditing] = React.useState(false);
  const fmt   = obj.dateformat || 'MM/DD/YYYY';
  const align = obj.align      || 'left';

  return (
    <div style={S.fieldWrap}>
      <FieldLabel obj={obj} />
      {editing ? (
        <input
          type="date"
          style={{ ...S.input }}
          value={value || ''}
          autoFocus
          onChange={e => onChange(obj.field, e.target.value)}
          onBlur={() => { setEditing(false); if (onBlur) onBlur(obj.field); }}
        />
      ) : (
        <div onClick={() => setEditing(true)}
          style={{ ...S.input, cursor: 'pointer',
            color: value ? undefined : '#94a3b8',
            textAlign: align }}>
          {value ? formatDate(value, fmt) : 'Click to set date…'}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────
// TIME FIELD — Flatpickr
// Stores 24hr (HH:MM), displays per obj.timeformat
// Falls back to native picker on mobile automatically
// ─────────────────────────────────────────────
function TimeField({ obj, value, onChange, onBlur }) {
  const inputRef = React.useRef(null);
  const fpRef    = React.useRef(null);
  const fmt      = obj.timeformat || '12';
  const align    = obj.align      || 'left';
  const is24     = fmt === '24';

  React.useEffect(() => {
    if (!inputRef.current || !window.flatpickr) return;
    fpRef.current = window.flatpickr(inputRef.current, {
      enableTime:  true,
      noCalendar:  true,
      dateFormat:  'H:i',
      time_24hr:   is24,
      defaultDate: value || null,
      onChange: (selectedDates, dateStr) => {
        onChange(obj.field, dateStr);
      },
      onClose: () => {
        if (onBlur) onBlur(obj.field);
      },
    });
    return () => {
      if (fpRef.current) { fpRef.current.destroy(); fpRef.current = null; }
    };
  }, []);

  React.useEffect(() => {
    if (!fpRef.current) return;
    if (value) fpRef.current.setDate(value, false);
    else fpRef.current.clear();
  }, [value]);

  React.useEffect(() => {
    if (fpRef.current) fpRef.current.set('time_24hr', is24);
  }, [is24]);

  return (
    <div style={S.fieldWrap}>
      <FieldLabel obj={obj} />
      <input
        ref={inputRef}
        readOnly
        placeholder="Select time…"
        style={{ ...S.input, cursor: 'pointer', textAlign: align }}
      />
    </div>
  );
}

// ─────────────────────────────────────────────
// DATETIME FIELD
// ─────────────────────────────────────────────
function DateTimeField({ obj, value, onChange, onBlur }) {
  const toInputFormat = (v) => {
    if (!v) return "";
    return v.replace(" ", "T").substring(0, 16);
  };
  const toDBFormat = (v) => {
    if (!v) return "";
    return v.replace("T", " ") + ":00";
  };
  return (
    <div style={S.fieldWrap}>
      <FieldLabel obj={obj} />
      <input
        type="datetime-local"
        style={S.input}
        value={toInputFormat(value)}
        onChange={e => onChange(obj.field, toDBFormat(e.target.value))}
        onBlur={onBlur ? () => onBlur(obj.field) : undefined}
      />
    </div>
  );
}
