// ─────────────────────────────────────────────
// DO_Fields_Choice.jsx
// SelectField — handles dropdown, checkbox, radio
// Requires: DO_Shared.jsx (S, CHECK, BORDER, FieldLabel, resolveOptions)
// ─────────────────────────────────────────────

// ─────────────────────────────────────────────
// SELECT FIELD
// Handles three display modes based on obj.type:
//   select   → <select> dropdown (single or multi)
//   checkbox → custom checkbox group (multi by default)
//   radio    → custom radio group (single)
//
// Options sources:
//   obj.source = 'local'  → from app's valuelist (valueListMap)
//   obj.source = 'inline' → from obj.options array (plain or Label|Value)
//   (default)             → obj.options array
//
// Storage:
//   single select → string value
//   multi select  → array of strings
// ─────────────────────────────────────────────
function SelectField({ obj, value, onChange, onBlur, valueListMap }) {
  const options = resolveOptions(obj, valueListMap);

  // Determine style (select vs check) and behavior (single vs multi)
  let style    = obj.style    || null;
  let behavior = obj.behavior || null;

  if (!style) {
    if      (obj.type === "checkbox") { style = "check";  behavior = behavior || "multi"; }
    else if (obj.type === "radio")    { style = "check";  behavior = "single"; }
    else                              { style = "select"; behavior = behavior || "single"; }
  }
  // Also respect obj.multi from inspector
  if (obj.multi === 'yes' && style === 'check') behavior = 'multi';
  if (obj.multi === 'no'  && style === 'check') behavior = 'single';
  if (!behavior) behavior = style === "select" ? "single" : "multi";

  // ── Dropdown (select element) ──
  if (style === "select") {
    if (behavior === "multi") {
      const selected = Array.isArray(value) ? value : (value ? [value] : []);
      return (
        <div style={S.fieldWrap}>
          <FieldLabel obj={obj} />
          <select
            multiple
            style={{ ...S.input, height: "auto", minHeight: "80px" }}
            value={selected}
            onChange={e => {
              const vals = Array.from(e.target.selectedOptions).map(o => o.value);
              onChange(obj.field, vals);
            }}
            onBlur={onBlur ? () => onBlur(obj.field) : undefined}
          >
            {options.map((opt, i) => (
              <option key={i} value={opt.value}>{opt.label}</option>
            ))}
          </select>
          <div style={S.fieldHint}>Hold Ctrl / Cmd to select multiple</div>
        </div>
      );
    }
    return (
      <div style={S.fieldWrap}>
        <FieldLabel obj={obj} />
        <select
          style={S.input}
          value={value || ""}
          onChange={e => onChange(obj.field, e.target.value)}
          onBlur={onBlur ? () => onBlur(obj.field) : undefined}
        >
          <option value="">— Select —</option>
          {options.map((opt, i) => (
            <option key={i} value={opt.value}>{opt.label}</option>
          ))}
        </select>
      </div>
    );
  }

  // ── Checkbox / Radio group ──
  const selected = Array.isArray(value)
    ? value.map(String)
    : (value ? [String(value)] : []);

  const isChecked = (val) =>
    behavior === "single"
      ? String(value) === String(val)
      : selected.includes(String(val));

  const toggle = (val) => {
    if (behavior === "single") {
      const newVal = String(value) === String(val) ? "" : String(val);
      onChange(obj.field, newVal);
    } else {
      const updated = selected.includes(String(val))
        ? selected.filter(v => v !== String(val))
        : [...selected, String(val)];
      onChange(obj.field, updated);
    }
    if (onBlur) setTimeout(() => onBlur(obj.field), 0);
  };

  const isVertical = obj.display === 'vertical' || obj.layout === 'vertical';

  return (
    <div style={S.fieldWrap}>
      <FieldLabel obj={obj} />
      <div style={{
        ...S.optionGroup,
        flexDirection: isVertical ? 'column' : 'row',
      }}>
        {options.map((opt, i) => (
          <label key={i} style={S.optionLabel} onClick={() => toggle(opt.value)}>
            <span style={{
              ...S.customCheck,
              background:   isChecked(opt.value) ? CHECK : '#fafbfc',
              borderColor:  isChecked(opt.value) ? CHECK : BORDER,
              borderRadius: behavior === 'single' ? '50%' : 3,
            }}>
              {isChecked(opt.value) && (
                behavior === "single"
                  ? <span style={S.radioDot} />
                  : <span style={S.checkMark}>✓</span>
              )}
            </span>
            <span style={S.optionText}>{opt.label}</span>
          </label>
        ))}
      </div>
    </div>
  );
}
