/* QuestionInputs.jsx — questionnaire input primitives for Muna Health.
   Built once, reused across all 65 questions. Reuses RadioOption / CheckOption /
   TextField from the kit; adds the controls the kit didn't have.
   Exports to window: QField, SingleSelect, MultiSelect, FrequencyScale,
   NumberInput, DateInput, TextArea, InlineReveal */

// ─── QField — label + optional help, wrapping any control ───────────────
function QField({ label, help, children, sensitive }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
        <div style={{ font: 'var(--type-h3)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-snug)', textWrap: 'pretty' }}>{label}</div>
        {help && <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)', textWrap: 'pretty' }}>{help}</div>}
      </div>
      {children}
    </div>
  );
}

// ─── SingleSelect — radio-style cards (one choice) ──────────────────────
function SingleSelect({ options, value, onChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {options.map(opt => (
        <RadioOption key={opt} label={opt} selected={value === opt} onClick={() => onChange(opt)}/>
      ))}
    </div>
  );
}

// ─── MultiSelect — checkbox-style cards (many choices) ──────────────────
//   `exclusive` options (e.g. "None of the above") clear the rest when picked.
function MultiSelect({ options, value = [], onChange, exclusive = [] }) {
  const toggle = (opt) => {
    const isExclusive = exclusive.includes(opt);
    let next;
    if (isExclusive) {
      next = value.includes(opt) ? [] : [opt];
    } else {
      next = value.includes(opt) ? value.filter(v => v !== opt) : [...value.filter(v => !exclusive.includes(v)), opt];
    }
    onChange(next);
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {options.map(opt => (
        <CheckOption key={opt} label={opt} selected={value.includes(opt)} onClick={() => toggle(opt)}/>
      ))}
    </div>
  );
}

// ─── FrequencyScale — 5-point segmented control ─────────────────────────
//   Default labels Never→Always; pass `labels` to override (keep 5).
function FrequencyScale({ value, onChange, labels = ['Never', 'Rarely', 'Sometimes', 'Often', 'Always'] }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: `repeat(${labels.length}, 1fr)`, gap: 6,
    }}>
      {labels.map((lab) => {
        const sel = value === lab;
        return (
          <button key={lab} onClick={() => onChange(lab)} style={{
            minHeight: 60, borderRadius: 'var(--radius-s)', cursor: 'pointer',
            border: sel ? '2px solid var(--amber-500)' : '1px solid var(--border-subtle)',
            background: sel ? 'var(--amber-500)' : '#fff',
            color: sel ? '#fff' : 'var(--fg-2)',
            font: 'var(--type-caption)', fontWeight: sel ? 600 : 500,
            padding: '6px 4px', lineHeight: 1.2, textWrap: 'balance',
            transition: 'background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out)',
          }}>{lab}</button>
        );
      })}
    </div>
  );
}

// ─── Bare numeric / text input shell (shared chrome) ───────────────────
function InputShell({ children, focused, error }) {
  const border = error ? 'var(--clay-500)' : focused ? 'var(--amber-500)' : 'var(--border-default)';
  const bw = focused || error ? 2 : 1;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8, background: '#fff',
      border: `${bw}px solid ${border}`, borderRadius: 'var(--radius-m)',
      padding: `${14 - (bw - 1)}px ${15 - (bw - 1)}px`,
      boxShadow: focused ? 'var(--focus-ring)' : 'var(--shadow-xs)',
      transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)',
    }}>{children}</div>
  );
}

// ─── NumberInput — numeric pad, optional unit suffix ────────────────────
function NumberInput({ value, onChange, placeholder, suffix, min, max, width }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ width: width || '100%' }}>
      <InputShell focused={focused}>
        <input
          type="number" inputMode="decimal" value={value ?? ''} placeholder={placeholder}
          min={min} max={max}
          onChange={e => onChange(e.target.value)}
          onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
          style={{ flex: 1, minWidth: 0, border: 0, outline: 'none', background: 'transparent', font: 'var(--type-body)', color: 'var(--fg-1)', padding: 0 }}
        />
        {suffix && <span style={{ font: 'var(--type-body)', color: 'var(--fg-3)', flexShrink: 0 }}>{suffix}</span>}
      </InputShell>
    </div>
  );
}

// ─── DateInput — three numeric fields DD / MM / YYYY ────────────────────
function DateInput({ value = {}, onChange }) {
  const [focus, setFocus] = React.useState(null);
  const cell = (key, ph, maxLen, w) => (
    <div style={{ width: w }}>
      <InputShell focused={focus === key}>
        <input
          inputMode="numeric" maxLength={maxLen} placeholder={ph}
          value={value[key] || ''}
          onChange={e => onChange({ ...value, [key]: e.target.value.replace(/\D/g, '').slice(0, maxLen) })}
          onFocus={() => setFocus(key)} onBlur={() => setFocus(null)}
          style={{ width: '100%', border: 0, outline: 'none', background: 'transparent', font: 'var(--type-body)', color: 'var(--fg-1)', padding: 0, textAlign: 'center' }}
        />
      </InputShell>
    </div>
  );
  const slash = <span style={{ font: 'var(--type-body-l)', color: 'var(--fg-4)' }}>/</span>;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      {cell('d', 'DD', 2, 64)}{slash}{cell('m', 'MM', 2, 64)}{slash}{cell('y', 'YYYY', 4, 92)}
    </div>
  );
}

// ─── TextArea — free text ───────────────────────────────────────────────
function TextArea({ value, onChange, placeholder, rows = 4 }) {
  const [focused, setFocused] = React.useState(false);
  const border = focused ? 'var(--amber-500)' : 'var(--border-default)';
  const bw = focused ? 2 : 1;
  return (
    <textarea
      value={value || ''} placeholder={placeholder} rows={rows}
      onChange={e => onChange(e.target.value)}
      onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
      style={{
        width: '100%', boxSizing: 'border-box', resize: 'none',
        border: `${bw}px solid ${border}`, borderRadius: 'var(--radius-m)',
        padding: `${13 - (bw - 1)}px ${15 - (bw - 1)}px`,
        font: 'var(--type-body)', color: 'var(--fg-1)', background: '#fff',
        boxShadow: focused ? 'var(--focus-ring)' : 'var(--shadow-xs)', outline: 'none',
        fontFamily: 'var(--font-sans)',
        transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)',
      }}
    />
  );
}

// ─── InlineReveal — smooth height/opacity reveal for sub-questions ──────
function InlineReveal({ open, children }) {
  const ref = React.useRef(null);
  const [h, setH] = React.useState(0);
  React.useEffect(() => {
    if (ref.current) setH(open ? ref.current.scrollHeight : 0);
  }, [open, children]);
  return (
    <div style={{
      maxHeight: open ? h + 8 : 0, opacity: open ? 1 : 0,
      overflow: 'hidden',
      transition: 'max-height var(--dur-base) var(--ease-out), opacity var(--dur-base) var(--ease-out)',
    }}>
      <div ref={ref} style={{ paddingTop: 14 }}>{children}</div>
    </div>
  );
}

Object.assign(window, { QField, SingleSelect, MultiSelect, FrequencyScale, NumberInput, DateInput, TextArea, InlineReveal });
