/* ============================================================
   fields.jsx — reusable controlled field components
   ============================================================ */

function Check() {
  return (
    <svg viewBox="0 0 12 12" fill="none">
      <path d="M2.5 6.2 L5 8.6 L9.5 3.4" stroke="#F3ECD6" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function FieldLabel({ label }) {
  if (!label) return null;
  return <span className="field-label">{label}</span>;
}

function TextField({ f, value, onChange }) {
  return (
    <div className="field">
      <FieldLabel label={f.label} opt={f.opt} />
      <input
        className="input"
        value={value || ""}
        placeholder={f.placeholder}
        onChange={(e) => onChange(e.target.value)}
      />
    </div>
  );
}

function TextArea({ f, value, onChange }) {
  return (
    <div className="field">
      <FieldLabel label={f.label} opt={f.opt} />
      <textarea
        className="textarea"
        rows={3}
        value={value || ""}
        placeholder={f.placeholder}
        onChange={(e) => onChange(e.target.value)}
      />
    </div>
  );
}

function Chips({ f, value, onChange }) {
  const sel = Array.isArray(value) ? value : [];
  const toggle = (opt) => {
    if (sel.includes(opt)) onChange(sel.filter((x) => x !== opt));
    else onChange([...sel, opt]);
  };
  return (
    <div className="field">
      <FieldLabel label={f.label} opt={f.opt} />
      <div className="chips">
        {f.options.map((opt) => {
          const on = sel.includes(opt);
          return (
            <button key={opt} type="button" className={"chip" + (on ? " on" : "")} onClick={() => toggle(opt)}>
              <span className="tick"><Check /></span>
              {opt}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Choice({ f, value, onChange }) {
  return (
    <div className="field">
      <FieldLabel label={f.label} opt={f.opt} />
      <div className="choices">
        {f.options.map((o) => {
          const label = typeof o === "string" ? o : o.v;
          const on = value === label;
          return (
            <button key={label} type="button" className={"choice" + (on ? " on" : "")} onClick={() => onChange(label)}>
              <span className="radio" />
              <span className="c-main">{label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function AccessField({ f, value, onChange }) {
  const state = value || {};
  const set = (item, status) => {
    const next = { ...state };
    if (next[item] === status) delete next[item];
    else next[item] = status;
    onChange(next);
  };
  return (
    <div className="field">
      <div className="access-list">
        {f.items.map((item) => {
          const s = state[item];
          return (
            <div className="access-row" key={item}>
              <span className="a-name">{item}</span>
              <div className="access-seg">
                <button type="button" className={"has" + (s === "has" ? " on" : "")} onClick={() => set(item, "has")}>Tenho</button>
                <button type="button" className={"make" + (s === "make" ? " on" : "")} onClick={() => set(item, "make")}>Criar</button>
                <button type="button" className={"no" + (s === "no" ? " on" : "")} onClick={() => set(item, "no")}>Não sei</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MoneyField({ f, value, onChange }) {
  const raw = (value === undefined || value === null) ? "" : value;
  const num = Number(raw) || 0;
  const pct = Math.min(100, Math.max(0, ((num - f.min) / (f.max - f.min)) * 100));
  return (
    <div className="field">
      <FieldLabel label={f.label} />
      <div className="money">
        <div className="prefix-input money-input">
          <span className="px">R$</span>
          <input className="input" type="number" inputMode="numeric" min={f.min}
            value={raw} placeholder={f.placeholder || "0"}
            onChange={(e) => onChange(e.target.value === "" ? "" : Number(e.target.value))} />
        </div>
        <input className="money-slider" type="range" min={f.min} max={f.max} step={f.step || 1}
          value={num} onChange={(e) => onChange(Number(e.target.value))}
          style={{ "--pct": pct + "%" }} />
        <div className="money-scale"><span>{formatBRL(f.min)}</span><span>{formatBRL(f.max)}+</span></div>
      </div>
    </div>
  );
}

function DateField({ f, value, onChange }) {
  return (
    <div className="field">
      <FieldLabel label={f.label} />
      <input className="input" type="date" value={value || ""} onChange={(e) => onChange(e.target.value)} />
    </div>
  );
}

function Field({ f, value, onChange }) {
  switch (f.type) {
    case "text":     return <TextField f={f} value={value} onChange={onChange} />;
    case "textarea": return <TextArea f={f} value={value} onChange={onChange} />;
    case "chips":    return <Chips f={f} value={value} onChange={onChange} />;
    case "choice":   return <Choice f={f} value={value} onChange={onChange} />;
    case "money":    return <MoneyField f={f} value={value} onChange={onChange} />;
    case "date":     return <DateField f={f} value={value} onChange={onChange} />;
    case "access":   return <AccessField f={f} value={value} onChange={onChange} />;
    default:         return null;
  }
}

/* render a step's fields, grouping consecutive short text fields into rows of 2 */
function FieldGroup({ step, answers, setAnswer }) {
  const fields = step.fields || [];
  const out = [];
  let i = 0;
  while (i < fields.length) {
    const f = fields[i];
    const next = fields[i + 1];
    const pairable = (x) => x && x.type === "text";
    if (pairable(f) && pairable(next)) {
      out.push(
        <div className="field-row" key={f.id}>
          <Field f={f} value={answers[f.id]} onChange={(v) => setAnswer(f.id, v)} />
          <Field f={next} value={answers[next.id]} onChange={(v) => setAnswer(next.id, v)} />
        </div>
      );
      i += 2;
    } else {
      out.push(<Field key={f.id} f={f} value={answers[f.id]} onChange={(v) => setAnswer(f.id, v)} />);
      i += 1;
    }
  }
  return <div className="fields">{out}</div>;
}

Object.assign(window, { Field, FieldGroup });
