// Generic tool form + result runner. Drives any AdM_TOOLS[id] config.

function ToolField({ field, value, onChange, direction }) {
  const dirA = direction === 'a';
  const fieldId = 'field-tool-' + field.id;
  const opts = typeof field.options === 'string'
    ? (window.AdM_RESOLVE_OPTIONS ? window.AdM_RESOLVE_OPTIONS(field.options) : [])
    : field.options;

  return (
    <div>
      <label className="field-label" htmlFor={fieldId}>
        {field.label}
        {field.required && <span style={{ color: '#dc2626' }}> *</span>}
      </label>
      {field.type === 'textarea' ? (
        <textarea
          id={fieldId}
          className="field-textarea"
          name={field.id}
          rows={field.rows || 5}
          placeholder={field.placeholder}
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
        />
      ) : field.type === 'select' ? (
        <select
          id={fieldId}
          className="field-select"
          name={field.id}
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
        >
          <option value="">Selecione...</option>
          {(opts || []).map((o) => <option key={o} value={o}>{field.options === 'countries' ? COUNTRY_LABELS[o] : o}</option>)}
        </select>
      ) : (
        <input
          id={fieldId}
          className="field-input"
          name={field.id}
          type={field.type === 'number' ? 'number' : 'text'}
          inputMode={field.type === 'number' ? 'numeric' : undefined}
          placeholder={field.placeholder}
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
        />
      )}
    </div>
  );
}

function GenericToolForm({ tool, direction, isLoading, onSubmit, initialValues }) {
  const [form, setForm] = React.useState(() => {
    if (initialValues) return initialValues;
    const countryField = tool.fields.find(field => field.options === 'countries');
    return countryField ? { [countryField.id]: window.AdM_CITIES.countryForCity(window.AdM_CITIES.getPreferred()) } : {};
  });
  const update = (id) => (v) => setForm({ ...form, [id]: v });

  const canSubmit = tool.fields.every((f) => !f.required || (form[f.id] && String(form[f.id]).trim()));

  const submit = (e) => {
    e.preventDefault();
    if (canSubmit && !isLoading) onSubmit(form);
  };

  const dirA = direction === 'a';
  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {tool.fields.map((f) => (
        <ToolField
          key={f.id}
          field={f}
          direction={direction}
          value={form[f.id]}
          onChange={update(f.id)}
        />
      ))}
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 8, flexWrap: 'wrap' }}>
        <button
          type="submit"
          className="btn btn-primary"
          disabled={!canSubmit || isLoading}
          style={{
            opacity: (!canSubmit || isLoading) ? 0.5 : 1,
            cursor: (!canSubmit || isLoading) ? 'not-allowed' : 'pointer',
          }}
        >
          {isLoading ? <><span className="spinner" /> Processando…</> : 'Gerar análise'}
        </button>
        <span style={{ fontSize: 13, color: dirA ? 'var(--a-text-2)' : 'var(--b-text-2)' }}>
          Usa 1 crédito.
        </span>
      </div>
    </form>
  );
}

async function runTool(toolType, form, tone) {
  const credits = window.AdM_CREDITS;
  const apiBase = (window.ADM_API_BASE || 'https://alemdomar-auth.luanagbc.workers.dev').replace(/\/+$/, '');
  const response = await fetch(apiBase + '/api/tools/run', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Device-Id': credits.getDeviceId() },
    body: JSON.stringify({ toolType, form, tone }),
  });
  if (response.status === 402) {
    await credits.syncFromServer();
    throw Object.assign(new Error('no_credits'), { code: 'no_credits' });
  }
  if (!response.ok) throw new Error('tool_service_error_' + response.status);
  const data = await response.json();
  credits.applyServerCredits(data.credits);
  return data.result;
}

window.GenericToolForm = GenericToolForm;
window.runTool = runTool;
