// fields.jsx — reusable form primitives for the Diagnóstico flow
const { useState } = React;

function Field({ label, required, hint, error, span2, children }) {
  return (
    <div className={"field" + (span2 ? " col-2" : "") + (error ? " invalid" : "")}>
      {label && (
        <label>{label}{required && <span className="req">*</span>}</label>
      )}
      {children}
      {error ? <span className="err">{error}</span> : (hint && <span className="hint">{hint}</span>)}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, type = "text" }) {
  return (
    <input
      className="input"
      type={type}
      value={value || ""}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
    />
  );
}

function TextArea({ value, onChange, placeholder }) {
  return (
    <textarea
      className="textarea"
      value={value || ""}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
    />
  );
}

function Select({ value, onChange, options, placeholder = "Selecciona" }) {
  return (
    <select className="select" value={value || ""} onChange={(e) => onChange(e.target.value)}>
      <option value="" disabled>{placeholder}</option>
      {options.map((o) => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

// single-choice large radio cards
function RadioGroup({ value, onChange, options }) {
  return (
    <div className="radios">
      {options.map((o) => (
        <button
          key={o}
          type="button"
          className={"radio-opt" + (value === o ? " sel" : "")}
          onClick={() => onChange(o)}
        >
          <span className="dot"></span>{o}
        </button>
      ))}
    </div>
  );
}

// single-choice pill chips
function ChipSingle({ value, onChange, options }) {
  return (
    <div className="chips">
      {options.map((o) => (
        <button
          key={o}
          type="button"
          className={"chip" + (value === o ? " sel" : "")}
          onClick={() => onChange(o)}
        >{o}</button>
      ))}
    </div>
  );
}

// multi-choice chips with tick
function ChipMulti({ value = [], onChange, options }) {
  const toggle = (o) => {
    if (value.includes(o)) onChange(value.filter((x) => x !== o));
    else onChange([...value, o]);
  };
  return (
    <div className="chips">
      {options.map((o) => {
        const on = value.includes(o);
        return (
          <button
            key={o}
            type="button"
            className={"chip" + (on ? " sel" : "")}
            onClick={() => toggle(o)}
          >
            <span className="tick">✓</span>{o}
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { Field, TextInput, TextArea, Select, RadioGroup, ChipSingle, ChipMulti });
