// Form: progressive — auto-detects segment from job title, adapts questions per segment.

function SegmentBadge({ segment, onChange }) {
  return (
    <div className="segment-choice">
      <span>Área sugerida: <strong>{segment.label}</strong></span>
      <button type="button" onClick={onChange}>Alterar área</button>
    </div>
  );
}

function SegmentPicker({ onPick, onClose }) {
  return (
    <div>
      <label className="field-label" htmlFor="career-segment">Qual área descreve melhor seu trabalho?</label>
      <select id="career-segment" className="field-select" defaultValue="" onChange={e => onPick(e.target.value)}>
        <option value="" disabled>Escolha uma área</option>
        {Object.values(window.AdM_SEGMENTS).map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
      </select>
      <div className="segment-choice"><button type="button" onClick={onClose}>Fechar</button></div>
    </div>
  );
}

function SegmentField({ field, value, onChange, direction }) {
  const dirA = direction === 'a';
  const fieldId = 'field-seg-' + field.id;
  return (
    <div>
      <label className="field-label" htmlFor={fieldId}>{field.label}</label>
      {field.textarea ? (
        <textarea
          id={fieldId}
          className="field-textarea"
          placeholder={field.placeholder}
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
        />
      ) : (
        <input
          id={fieldId}
          className="field-input"
          placeholder={field.placeholder}
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
        />
      )}
    </div>
  );
}

function TranslatorForm({ direction, onSubmit, isLoading, initialValues, onChangePersona }) {
  const defaultCity = (window.AdM_CITIES && window.AdM_CITIES.getPreferred()) || 'dublin';
  const defaultCountry = window.AdM_CITIES
    ? window.AdM_CITIES.countryForCity(defaultCity)
    : 'Ireland';

  const [form, setForm] = React.useState({
    brTitle: '', company: '', industry: '', years: '',
    duties: '', targetCountry: defaultCountry, targetCity: defaultCity, targetRole: '', jobDescription: '',
    segment: null, segmentData: {}, ...initialValues,
  });
  const [showPicker, setShowPicker] = React.useState(false);
  const [showOtherCountry, setShowOtherCountry] = React.useState(() =>
    Boolean(initialValues?.targetCountry && !window.AdM_CITIES.list.some(c => c.country === initialValues.targetCountry))
  );

  const selectCity = (cityId) => {
    if (!window.AdM_CITIES) return;
    window.AdM_CITIES.setPreferred(cityId);
    setForm((f) => ({
      ...f,
      targetCity: cityId,
      targetCountry: window.AdM_CITIES.countryForCity(cityId),
    }));
    setShowOtherCountry(false);
  };

  const onCountryChange = (country) => {
    const match = window.AdM_CITIES && window.AdM_CITIES.list.find((c) => c.country === country);
    setForm((f) => ({
      ...f,
      targetCountry: country,
      targetCity: match ? match.id : null,
    }));
    if (match && window.AdM_CITIES) window.AdM_CITIES.setPreferred(match.id);
  };

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const updateSegmentField = (k) => (v) => setForm({ ...form, segmentData: { ...form.segmentData, [k]: v } });

  // Auto-detect segment when brTitle blurs (or changes meaningfully)
  const onTitleBlur = () => {
    if (form.segment) return; // user already chose
    const detected = window.AdM_DETECT_SEGMENT(form.brTitle);
    if (detected) {
      setForm((f) => ({ ...f, segment: detected }));
    }
  };

  const pickSegment = (id) => {
    setForm({ ...form, segment: id });
    setShowPicker(false);
  };

  const dirA = direction === 'a';
  const segObj = form.segment ? window.AdM_SEGMENTS[form.segment] : null;
  const segFields = form.segment ? window.AdM_SEGMENT_FIELDS[form.segment] : null;

  const canSubmit = form.brTitle.trim() && form.duties.trim() && form.targetCountry;

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

  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
      {/* Quick personas */}
      <details className="career-options">
        <summary>Preencher com um exemplo</summary>
        <div className="sample-roles">
          {SAMPLE_PERSONAS.map((p) => (
            <button
              key={p.id}
              type="button"
              onClick={() => {
                const detected = window.AdM_DETECT_SEGMENT(p.form.brTitle);
                const segmentData = Object.fromEntries((window.AdM_SEGMENT_FIELDS[detected] || [])
                  .filter(field => p.form[field.id]).map(field => [field.id, p.form[field.id]]));
                setForm({ ...p.form, targetCountry: form.targetCountry, targetCity: form.targetCity, segment: detected, segmentData });
                setShowPicker(false);
                onChangePersona && onChangePersona(p.id);
              }}
            >
              {p.label}
            </button>
          ))}
        </div>
      </details>

      <div className="rule-thin" style={{ height: 1, background: dirA ? 'var(--a-rule)' : 'var(--b-rule)' }} />

      {/* Essentials */}
      <div className="form-grid-2col">
        <div>
          <label className="field-label" htmlFor="field-br-title">Cargo no Brasil <span style={{ color: '#dc2626' }}>*</span></label>
          <input
            id="field-br-title"
            className="field-input"
            name="brTitle"
            autoComplete="organization-title"
            placeholder="Ex: Eletricista, Analista de Produto, Cabeleireira"
            value={form.brTitle}
            onChange={update('brTitle')}
            onBlur={onTitleBlur}
            required
          />
          <div className="field-hint">Pode ser emprego formal, estágio, trabalho autônomo ou voluntário.</div>
        </div>
        <div>
          <label className="field-label" htmlFor="field-years">Anos no cargo (opcional)</label>
          <input
            id="field-years"
            className="field-input"
            name="years"
            type="number" min="0" step="any"
            inputMode="decimal"
            placeholder="3"
            value={form.years}
            onChange={update('years')}
          />
        </div>
      </div>

      {/* Segment badge or picker */}
      {segObj && !showPicker && (
        <SegmentBadge segment={segObj} direction={direction} onChange={() => setShowPicker(true)} />
      )}
      {showPicker && (
        <SegmentPicker
          direction={direction}
          onPick={pickSegment}
          onClose={() => setShowPicker(false)}
        />
      )}
      {!segObj && !showPicker && form.brTitle && (
        <button
          type="button"
          onClick={() => setShowPicker(true)}
          style={{
            alignSelf: 'flex-start',
            fontSize: 14, fontWeight: 600,
            color: dirA ? 'var(--a-teal)' : 'var(--b-gold)',
            textDecoration: 'underline', textUnderlineOffset: 4,
          }}
        >
          Indicar área de atuação (opcional)
        </button>
      )}

      {/* Daily duties */}
      <div>
        <label className="field-label" htmlFor="field-duties">O que você fazia no dia a dia <span style={{ color: '#dc2626' }}>*</span></label>
        <textarea
          id="field-duties"
          className="field-textarea"
          name="duties"
          placeholder="Escreva como falaria pra um amigo. Pode ser bagunçado, em português, sem métricas.&#10;&#10;Ex: Atendia clientes, organizava estoque, dava suporte ao caixa, ajudava o gerente com planilhas..."
          value={form.duties}
          onChange={update('duties')}
          required
        />
        <div className="field-hint">Conte o que você fez, para quem e com quais ferramentas. Se lembrar de um resultado, inclua também.</div>
      </div>

      <div>
        <span className="field-label" id="field-destino-label">Cidade de destino <span style={{ color: '#dc2626' }}>*</span></span>
        {window.CityChips && (
          <CityChips
            direction={direction}
            value={form.targetCity}
            onChange={selectCity}
            ariaLabelledBy="field-destino-label"
          />
        )}
        <div style={{ marginTop: 12 }}>
          <button
            type="button"
            onClick={() => showOtherCountry ? selectCity(form.targetCity || defaultCity) : setShowOtherCountry(true)}
            style={{
              fontSize: 13,
              fontWeight: 600,
              color: dirA ? 'var(--a-teal)' : 'var(--b-gold)',
              textDecoration: 'underline',
              textUnderlineOffset: 3,
            }}
          >
            {showOtherCountry ? 'Usar Dublin, Londres ou Berlim' : 'Outro país da UE →'}
          </button>
        </div>
        {showOtherCountry && (
          <div style={{ marginTop: 12 }}>
            <label className="field-label" htmlFor="field-target-country">País de destino (outro)</label>
            <select
              id="field-target-country"
              className="field-select"
              name="targetCountry"
              value={form.targetCountry}
              onChange={(e) => onCountryChange(e.target.value)}
            >
              {TARGET_COUNTRIES.map((c) => <option key={c} value={c}>{COUNTRY_LABELS[c]}</option>)}
            </select>
            <div className="field-hint">Portugal, Holanda, Espanha e outros. Sem guia por cidade ainda.</div>
          </div>
        )}
        {!showOtherCountry && form.targetCity && window.AdM_CITIES && (
          <div className="field-hint" style={{ marginTop: 8 }}>
            Adaptando ao mercado de {window.AdM_CITIES.byId[form.targetCity].label}.
          </div>
        )}
      </div>

      {/* Segment-specific fields */}
      <details className="career-options">
        <summary>Acrescentar detalhes ou uma vaga (opcional)</summary>
        <div className="career-details">
          {(segFields || []).map((f) => (
            <SegmentField
              key={f.id}
              field={f}
              direction={direction}
              value={form.segmentData?.[f.id]}
              onChange={updateSegmentField(f.id)}
            />
          ))}
          <div className="form-grid-2col">
            <div>
              <label className="field-label" htmlFor="field-company">Empresa (opcional)</label>
              <input id="field-company" className="field-input" name="company" placeholder="Nubank, Drogasil, autônoma..." value={form.company} onChange={update('company')} />
            </div>
            <div>
              <label className="field-label" htmlFor="field-target-role">Cargo-alvo (opcional)</label>
              <input id="field-target-role" className="field-input" name="targetRole" placeholder="Ex: Product Analyst, Electrician" value={form.targetRole} onChange={update('targetRole')} />
            </div>
          </div>
          <div>
            <label className="field-label" htmlFor="field-job-description">Descrição da vaga (opcional)</label>
            <textarea id="field-job-description" name="jobDescription" className="field-textarea"
              value={form.jobDescription || ''} onChange={update('jobDescription')}
              placeholder="Cole as responsabilidades e os requisitos que aparecem no anúncio."
              aria-describedby="job-description-hint" />
            <div className="field-hint" id="job-description-hint">O anúncio ajuda a escolher quais exemplos da sua experiência destacar.</div>
          </div>
        </div>
      </details>

      <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" /> Traduzindo…</> : <>Gerar textos em inglês</>}
        </button>
        <span style={{ fontSize: 13, color: dirA ? 'var(--a-text-2)' : 'var(--b-text-2)' }}>
          {canSubmit ? 'Usa 1 crédito.' : 'Preencha o cargo e as atividades para continuar.'}
        </span>
      </div>
    </form>
  );
}

window.TranslatorForm = TranslatorForm;
