// SubmissionForm — three free-text fields + submit
const { useRef, useEffect } = React;

function AutoTextarea({ value, onChange, placeholder, id, disabled }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    el.style.height = "auto";
    el.style.height = Math.max(el.scrollHeight, 96) + "px";
  }, [value]);
  return (
    <textarea
      id={id}
      ref={ref}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      disabled={disabled}
      rows={3}
      className="field__textarea"
    />
  );
}

function SubmissionForm({ answers, setAnswers, onSubmit, submitting, disabled }) {
  const fields = [
    {
      key: "positioning",
      label: "Comms positioning",
      hint: "Your core elevator pitch — the headline message and rebuttals to likely pushback.",
      placeholder: "How will you frame this? What's the one-sentence story, and what are the counter-arguments ready for the obvious objections?"
    },
    {
      key: "channels",
      label: "Channel choices",
      hint: "Where and how you'll reach this persona. Owned, earned, paid, internal — be specific.",
      placeholder: "Which channels, in what order, and why are they right for this audience?"
    },
    {
      key: "challenges",
      label: "Challenges",
      hint: "Risks, trade-offs, open questions, things you're not sure about.",
      placeholder: "What could go wrong? What are you uncertain about? What would you want to pressure-test?"
    }
  ];

  const canSubmit = !submitting && !disabled &&
    answers.positioning.trim() && answers.channels.trim() && answers.challenges.trim();

  return (
    <form
      className="form"
      onSubmit={(e) => { e.preventDefault(); if (canSubmit) onSubmit(); }}
    >
      {fields.map((f, i) => (
        <div key={f.key} className="field">
          <div className="field__header">
            <label htmlFor={f.key} className="field__label">
              <span className="field__num">{String(i + 1).padStart(2, "0")}</span>
              {f.label}
            </label>
            <span className="field__hint">{f.hint}</span>
          </div>
          <AutoTextarea
            id={f.key}
            value={answers[f.key]}
            onChange={(v) => setAnswers({ ...answers, [f.key]: v })}
            placeholder={f.placeholder}
            disabled={submitting || disabled}
          />
        </div>
      ))}

      <div className="form__submit-row">
        <button
          type="submit"
          className="submit-btn"
          disabled={!canSubmit}
          aria-busy={submitting}
        >
          {submitting ? "Testing against persona…" : "Test against persona"}
          <span className="submit-btn__arrow" aria-hidden="true">→</span>
        </button>
      </div>
    </form>
  );
}

window.SubmissionForm = SubmissionForm;
