// fields.jsx — field renderers, step body, review body
const { useState } = React;

function Field({ id, value, onChange, error }) {
  const f = window.FF_FIELDS[id];
  if (!f) return null;
  const labelEl = (
    <label className="form-label">
      {f.label}{f.required ? <span className="req">*</span> : null}
    </label>
  );

  let control = null;
  if (f.type === 'text' || f.type === 'email') {
    control = (
      <input
        type={f.type}
        className="tff-input"
        placeholder={f.placeholder || ''}
        value={value || ''}
        onChange={(e) => onChange(id, e.target.value)}
      />
    );
  } else if (f.type === 'textarea') {
    control = (
      <textarea
        className="tff-textarea"
        placeholder={f.placeholder || ''}
        value={value || ''}
        onChange={(e) => onChange(id, e.target.value)}
      />
    );
  } else if (f.type === 'select') {
    control = (
      <select className="tff-select" value={value || ''} onChange={(e) => onChange(id, e.target.value)}>
        <option value="">Select</option>
        {f.options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    );
  } else if (f.type === 'checkbox') {
    const set = new Set(value || []);
    const toggle = (o) => {
      const next = new Set(set);
      next.has(o) ? next.delete(o) : next.add(o);
      onChange(id, [...next]);
    };
    control = (
      <div className="checkbox-grid">
        {f.options.map((o) => (
          <label className="checkbox-item" key={o}>
            <input type="checkbox" checked={set.has(o)} onChange={() => toggle(o)} />
            {o}
          </label>
        ))}
      </div>
    );
  } else if (f.type === 'scale') {
    control = (
      <div>
        <div className="scale-wrap">
          {[1, 2, 3, 4, 5].map((n) => (
            <div
              key={n}
              className={'scale-opt' + (value === n ? ' selected' : '')}
              onClick={() => onChange(id, n)}
            >{n}</div>
          ))}
        </div>
        <div className="scale-ends"><span>{f.ends[0]}</span><span>{f.ends[1]}</span></div>
      </div>
    );
  }

  return (
    <div className={'form-field' + (error ? ' invalid' : '')}>
      {labelEl}
      {f.hint ? <span className="form-hint">{f.hint}</span> : null}
      {control}
      {error ? <div className="field-error">{error}</div> : null}
    </div>
  );
}

function StepBody({ step, values, errors, onChange }) {
  return (
    <div>
      {step.groups.map((g, gi) => (
        <div key={gi} className={g.subhead ? 'sub-block' : 'form-group'}>
          {g.subhead ? <div className="sub-head">{g.subhead}</div> : null}
          {g.rows.map((row, ri) => (
            row.length > 1 ? (
              <div className="input-row" key={ri}>
                {row.map((fid) => (
                  <Field key={fid} id={fid} value={values[fid]} error={errors[fid]} onChange={onChange} />
                ))}
              </div>
            ) : (
              <Field key={ri} id={row[0]} value={values[row[0]]} error={errors[row[0]]} onChange={onChange} />
            )
          ))}
        </div>
      ))}
    </div>
  );
}

// ---- Review ----
function fmt(id, v) {
  if (v == null || v === '' || (Array.isArray(v) && v.length === 0)) return null;
  if (Array.isArray(v)) return v.join(', ');
  if (window.FF_FIELDS[id].type === 'scale') return v + ' / 5';
  return String(v);
}

function ReviewBody({ values, onEditStep }) {
  const steps = window.FF_STEPS.filter((s) => !s.review);
  return (
    <div className="review-grid">
      {steps.map((s) => {
        const ids = [];
        s.groups.forEach((g) => g.rows.forEach((r) => r.forEach((id) => ids.push(id))));
        return (
          <div className="review-sec" key={s.id}>
            <div className="review-sec-label">
              {s.title}
              <button className="review-edit" onClick={() => onEditStep(s.id)}>Edit</button>
            </div>
            {ids.map((id) => {
              const val = fmt(id, values[id]);
              return (
                <div className="review-pair" key={id}>
                  <div className="review-k">{window.FF_FIELDS[id].review}</div>
                  <div className={'review-v' + (val ? '' : ' empty')}>{val || 'Not provided'}</div>
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Field, StepBody, ReviewBody });
