/* ============================================================
   Questionnaire — controller, progress, brief, success, tweaks
   ============================================================ */
var { useState, useEffect, useRef, useMemo } = React;
const { StepBasics, StepStyle, StepConcept, StepColor, StepUsage } = window.QStepComponents;
const { STEPS: QSTEPS } = window.QShared;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "stylePicker": "cards",
  "tagInput": "chips",
  "progress": "stepper",
  "editorial": true,
  "accent": "balanced"
}/*EDITMODE-END*/;

/* ---- progress indicators ---- */
function Stepper({ current }) {
  return (
    <div className="stepper">
      {QSTEPS.map((s, i) => (
        <div className="stepper-item" key={s.id}>
          <div className={`step-dot ${i < current ? "is-done" : ""} ${i === current ? "is-active" : ""}`}>
            {i < current ? <Icon name="check" size={14} stroke={2.6} /> : String(i + 1).padStart(2, "0")}
          </div>
          {i < QSTEPS.length - 1 && (
            <div className="step-line"><div className="fill" style={{ transform: `scaleX(${i < current ? 1 : 0})` }} /></div>
          )}
        </div>
      ))}
    </div>
  );
}
function ProgressBar({ current }) {
  const pct = Math.round(((current) / QSTEPS.length) * 100);
  return (
    <div style={{ marginBottom: "var(--space-6)" }}>
      <div className="progress-meta">
        <span className="label">{QSTEPS[current].label}</span>
        <span className="label">{current + 1} / {QSTEPS.length}</span>
      </div>
      <div className="progress-track"><div className="bar" style={{ width: `${Math.max(pct, 6)}%` }} /></div>
    </div>
  );
}

/* ---- confirmation screen ---- */
function ConfirmationScreen({ submissionId, onReset, T }) {
  return (
    <div className="app">
      <div className="topbar">
        <Logo />
        <div className="topbar-right">
          <span className="topbar-meta">Submitted</span>
        </div>
      </div>
      <div className="brief-stage">
        <div className="brief-hero">
          <div className="brief-badge"><Icon name="check" size={14} stroke={2.6} /> Questionnaire sent</div>
          <h1 className="brief-title">{T.editorial ? <>Thank you, we received your logo <em>questionnaire</em></> : "Thank you, we received your logo questionnaire"}</h1>
          <p className="brief-lede">Your responses have been sent to Arigato Studio. The design team now has your logo brief and reference details.</p>
          <div className="brief-actions">
            <button className="btn btn-outline" onClick={onReset}>Start a new questionnaire</button>
          </div>
          {submissionId && (
            <div className="confirmation-ref">
              Reference ID: <code>{submissionId}</code>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---- main app ---- */
function QuestionnaireApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [current, setCurrent] = useState(0);
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [submissionId, setSubmissionId] = useState("");
  const [answers, setAnswers] = useState(() => {
    try { const d = sessionStorage.getItem("arigato_draft"); if (d) return { ...emptyAnswers(), ...JSON.parse(d) }; } catch {}
    return emptyAnswers();
  });
  const [errors, setErrors] = useState({});
  const set = (patch) => setAnswers(a => ({ ...a, ...patch }));

  useEffect(() => { try { sessionStorage.setItem("arigato_draft", JSON.stringify(answers)); } catch {} }, [answers]);
  useEffect(() => { window.scrollTo({ top: 0, behavior: "smooth" }); }, [current, done]);

  const validate = (step) => {
    const e = {};
    if (step === 0) {
      if (!answers.brandName.trim()) e.brandName = true;
      if (!answers.description.trim()) e.description = true;
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    setSubmitError("");
    try {
      const result = await submitQuestionnaire(answers);
      setSubmissionId(result.submission.id);
      setDone(true);
      try { sessionStorage.removeItem("arigato_draft"); } catch {}
    } catch (err) {
      setSubmitError(err.message || "Could not send your questionnaire. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const next = () => {
    if (!validate(current)) return;
    if (current < QSTEPS.length - 1) setCurrent(current + 1);
    else submit();
  };
  const back = () => { if (!submitting && current > 0) setCurrent(current - 1); };

  const T = t;
  const stepProps = { a: answers, set, errors, T };
  const StepEl = [
    <StepBasics {...stepProps} />, <StepStyle {...stepProps} />, <StepConcept {...stepProps} />,
    <StepColor {...stepProps} />, <StepUsage {...stepProps} />,
  ][current];

  if (done) {
    return <>
      <ConfirmationScreen submissionId={submissionId} T={T}
        onReset={() => { setAnswers(emptyAnswers()); setDone(false); setCurrent(0); setSubmissionId(""); try { sessionStorage.removeItem("arigato_draft"); } catch {} }} />
      <TweaksUI t={t} setTweak={setTweak} />
    </>;
  }

  return (
    <div className="app">
      <div className="topbar">
        <Logo />
        <div className="topbar-right">
          <span className="topbar-meta">~ 5 min · {current + 1} of {QSTEPS.length}</span>
        </div>
      </div>

      <div className="form-stage">
        {T.progress === "stepper" ? <Stepper current={current} /> : <ProgressBar current={current} />}
        {StepEl}
      </div>

      <div className="form-footer">
        <div className="form-footer-inner">
          <div>
            {current > 0
              ? <button className="btn btn-ghost" onClick={back} disabled={submitting}><Icon name="arrow-left" size={16} /> Back</button>
              : <span className="footer-hint">Required fields are marked <span className="req">*</span></span>}
          </div>
          {submitError && <div className="submit-error"><Icon name="alert" size={14} /> {submitError}</div>}
          <button className={`btn ${current === QSTEPS.length - 1 ? "btn-coral" : "btn-primary"} btn-lg`} onClick={next} disabled={submitting}>
            {current === QSTEPS.length - 1
              ? submitting ? <>Sending...</> : <>Submit questionnaire <Icon name="send" size={16} /></>
              : <>Continue <Icon name="arrow-right" size={16} /></>}
          </button>
        </div>
      </div>

      <TweaksUI t={t} setTweak={setTweak} />
    </div>
  );
}

/* ---- tweaks panel ---- */
function TweaksUI({ t, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Layout variations" />
      <TweakRadio label="Style picker" value={t.stylePicker} options={["cards", "list"]} onChange={(v) => setTweak("stylePicker", v)} />
      <TweakRadio label="Multi-select" value={t.tagInput} options={["chips", "checklist"]} onChange={(v) => setTweak("tagInput", v)} />
      <TweakRadio label="Progress" value={t.progress} options={["stepper", "bar"]} onChange={(v) => setTweak("progress", v)} />
      <TweakSection label="Tone" />
      <TweakToggle label="Editorial titles" value={t.editorial} onChange={(v) => setTweak("editorial", v)} />
    </TweaksPanel>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<QuestionnaireApp />);
