/* New Evaluation form */
(() => {
const { useState: useStateNE } = React;

function NewEvaluation({ onCreated, intaker }) {
  const [form, setForm] = useStateNE({
    intaker: intaker || '',
    client_name: '',
    client_email: '',
    client_phone: '',
    client_state: '',
    client_city: '',
    defendant_name: '',
    defendant_phone: '',
    defendant_domain: '',
    violation_type: '',
    violation_count: '',
    last_violation_date: '',
    stop_sent: '',
    dnc_registered: 'unknown',
    message_purpose: '',
    notes: '',
  });
  const [submitting, setSubmitting] = useStateNE(false);
  const [err, setErr] = useStateNE('');

  function bind(name) {
    return {
      value: form[name],
      onChange: e => setForm({ ...form, [name]: e.target.value }),
    };
  }

  async function submit(e) {
    e.preventDefault();
    if (!form.defendant_name) {
      setErr('Defendant name is required.');
      return;
    }
    setSubmitting(true); setErr('');
    try {
      const payload = { ...form, violation_count: form.violation_count ? parseInt(form.violation_count, 10) : null };
      const ev = await api.createEvaluation(payload);
      onCreated(ev);
    } catch (e) {
      setErr(e.message || 'Failed to create evaluation');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
      <div className="text-sm font-bold text-ink-3 uppercase tracking-wider mb-1">New Evaluation</div>
      <div className="text-xs text-ink-4 mb-5">Full defendant workup — research, score, and generate demand letter + exhibits.</div>

      <form onSubmit={submit} className="space-y-5">
        <Section title="Intaker">
          <Field label="Your name">
            <input className="field-input" {...bind('intaker')} placeholder="e.g. Gonzalo Vega" />
          </Field>
        </Section>

        <Section title="Client (Plaintiff)">
          <Grid2>
            <Field label="Client name"><input className="field-input" {...bind('client_name')} placeholder="Full legal name" /></Field>
            <Field label="Client email"><input className="field-input" {...bind('client_email')} placeholder="client@example.com" /></Field>
          </Grid2>
          <Grid3>
            <Field label="Phone"><input className="field-input" {...bind('client_phone')} placeholder="(555) 555-1212" /></Field>
            <Field label="State">
              <select className="field-input" {...bind('client_state')}>
                <option value="">—</option>
                {['CA','FL','NY','TX','IL','WA','AZ','NV','GA','MA','NJ','OH','PA'].map(s => <option key={s} value={s}>{s}</option>)}
                <option value="OTHER">Other</option>
              </select>
            </Field>
            <Field label="City"><input className="field-input" {...bind('client_city')} placeholder="e.g. Los Angeles" /></Field>
          </Grid3>
        </Section>

        <Section title="Defendant">
          <Field label={<>Company name <span className="text-red-600">*</span></>}>
            <input className="field-input" {...bind('defendant_name')} placeholder="e.g. QuickLoans Direct LLC" />
          </Field>
          <Grid2>
            <Field label="Defendant phone"><input className="field-input" {...bind('defendant_phone')} placeholder="(305) 555-0199" /></Field>
            <Field label="Website / domain"><input className="field-input" {...bind('defendant_domain')} placeholder="example.com" /></Field>
          </Grid2>
        </Section>

        <Section title="Violation Facts">
          <Field label="Violation type">
            <select className="field-input" {...bind('violation_type')}>
              <option value="">— Select —</option>
              <option value="texts_after_stop">Texts after STOP (§ 227(c))</option>
              <option value="quiet_hours_text">Quiet-hours texts (§ 227(c))</option>
              <option value="dnc_text">Texts to DNC number (§ 227(c))</option>
              <option value="prerecorded_voicemail">Prerecorded/AI voicemail (§ 227(b))</option>
              <option value="junk_fax">Junk fax (§ 227(b)(1)(C))</option>
              <option value="cipa">California CIPA wiretap/pen register</option>
            </select>
          </Field>
          <Grid3>
            <Field label="Number of violations"><input type="number" min="1" className="field-input" {...bind('violation_count')} placeholder="e.g. 12" /></Field>
            <Field label="Date of last violation"><input type="date" className="field-input" {...bind('last_violation_date')} /></Field>
            <Field label="Message purpose">
              <select className="field-input" {...bind('message_purpose')}>
                <option value="">—</option>
                <option value="marketing">Marketing</option>
                <option value="recruitment">Recruitment</option>
                <option value="debt_collection">Debt collection</option>
                <option value="political">Political</option>
                <option value="other">Other</option>
              </select>
            </Field>
          </Grid3>
          <Grid2>
            <Field label="STOP sent?">
              <select className="field-input" {...bind('stop_sent')}>
                <option value="">N/A</option>
                <option value="yes">Yes</option>
                <option value="no">No</option>
              </select>
            </Field>
            <Field label="On DNC registry?">
              <select className="field-input" {...bind('dnc_registered')}>
                <option value="unknown">Unknown</option>
                <option value="yes">Yes</option>
                <option value="no">No</option>
              </select>
            </Field>
          </Grid3>
        </Section>

        <Section title="Notes">
          <textarea
            rows={4}
            className="field-input"
            value={form.notes}
            onChange={e => setForm({ ...form, notes: e.target.value })}
            placeholder="Any extra facts the intaker captured — defendant aliases, prior contact attempts, screenshots received, etc."
          />
        </Section>

        {err && <div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded p-3">{err}</div>}

        <button
          type="submit"
          disabled={submitting}
          className="w-full bg-brand hover:bg-brand-dark text-white font-semibold py-3 rounded-lg transition disabled:opacity-50 flex items-center justify-center gap-2"
        >
          {submitting ? 'Starting evaluation…' : '▶ Run Evaluation'}
        </button>
      </form>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div>
      <div className="text-[11px] font-bold text-ink-4 uppercase tracking-wider mb-2">{title}</div>
      <div className="space-y-3">{children}</div>
    </div>
  );
}
function Field({ label, children }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-ink-3 mb-1">{label}</label>
      {children}
    </div>
  );
}
function Grid2({ children }) { return <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{children}</div>; }
function Grid3({ children }) { return <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">{children}</div>; }

window.NewEvaluation = NewEvaluation;
})();
