/* Nexpersona - 7-step inquiry form */

const { useState: useStateF, useEffect: useEffectF, useRef: useRefF, useMemo: useMemoF } = React;

const FORM_KEY = 'nx_inquiry';

const STEP_IDS = ['identity', 'profile', 'reach', 'goals', 'budget', 'context', 'submit'];

const PROFILE_IDS = ['creator', 'personal', 'business', 'other'];
const REACH_IDS = [1, 2, 3, 4, 5];
const GOAL_IDS = [1, 2, 3, 4, 5, 6, 7];
const BUDGET_IDS = [1, 2, 3, 4, 5];
const TIMELINE_IDS = [1, 2, 3, 4];

function validEmail(v) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v || '');
}

function loadSaved() {
  try {
    const raw = localStorage.getItem(FORM_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch { return null; }
}

function defaultData() {
  return {
    name: '', email: '',
    profile: '',
    handle: '', reach: '',
    goals: [],
    budget: '', timeline: '',
    context: '',
    submitted: false,
  };
}

function InquiryForm() {
  const { t, tR } = window.useT();
  const [step, setStep] = useStateF(0);
  const [data, setData] = useStateF(() => loadSaved() || defaultData());
  const [errors, setErrors] = useStateF({});
  const [anim, setAnim] = useStateF('enter');
  const [confirmed, setConfirmed] = useStateF(false);
  const [submitting, setSubmitting] = useStateF(false);
  const [submitError, setSubmitError] = useStateF(null);
  const inputRef = useRefF(null);

  const STEPS_DEF = STEP_IDS.map((id) => ({
    id,
    label: t(`form.step.label.${id}`),
    total: STEP_IDS.length,
  }));

  const PROFILE_OPTS = PROFILE_IDS.map(id => ({ id, label: t(`form.profile.${id}`) }));
  const REACH_OPTS = REACH_IDS.map(i => t(`form.reach.${i}`));
  const GOAL_OPTS = GOAL_IDS.map(i => t(`form.goal.${i}`));
  const BUDGET_OPTS = BUDGET_IDS.map(i => t(`form.budget.${i}`));
  const TIMELINE_OPTS = TIMELINE_IDS.map(i => t(`form.timeline.${i}`));

  useEffectF(() => {
    localStorage.setItem(FORM_KEY, JSON.stringify(data));
  }, [data]);

  const userInteractedRef = useRefF(false);

  useEffectF(() => {
    // Don't auto-focus on initial mount - focusing scrolls the form into view
    // and the page would jump to step 07 on load. Only focus after the user
    // has interacted (clicked Continue / Back / a quick-edit).
    if (!userInteractedRef.current) return;
    const tid = setTimeout(() => {
      if (inputRef.current) {
        try {
          inputRef.current.focus({ preventScroll: true });
        } catch {
          inputRef.current.focus();
        }
      }
    }, 380);
    return () => clearTimeout(tid);
  }, [step]);

  const set = (patch) => setData(d => ({ ...d, ...patch }));
  const toggleGoal = (g) => {
    setData(d => {
      const has = d.goals.includes(g);
      return { ...d, goals: has ? d.goals.filter(x => x !== g) : [...d.goals, g] };
    });
  };

  const validateStep = (s = step) => {
    const e = {};
    if (s === 0) {
      if (!data.name.trim()) e.name = t('form.err.required');
      if (!validEmail(data.email)) e.email = t('form.err.email');
    }
    if (s === 1 && !data.profile) e.profile = t('form.err.pick_one');
    if (s === 2) {
      if (!data.handle.trim()) e.handle = t('form.err.required');
      if (!data.reach) e.reach = t('form.err.pick_one');
    }
    if (s === 3 && data.goals.length === 0) e.goals = t('form.err.pick_one_more');
    if (s === 4) {
      if (!data.budget) e.budget = t('form.err.pick_range');
      if (!data.timeline) e.timeline = t('form.err.pick_timeline');
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const animateTo = (next) => {
    setAnim('exit');
    setTimeout(() => {
      setStep(next);
      setAnim('enter');
    }, 250);
  };

  const next = () => {
    userInteractedRef.current = true;
    if (validateStep()) animateTo(Math.min(step + 1, STEPS_DEF.length - 1));
  };
  const back = () => {
    userInteractedRef.current = true;
    setErrors({});
    animateTo(Math.max(step - 1, 0));
  };
  const goToStep = (s) => {
    userInteractedRef.current = true;
    setStep(s);
  };

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch('/api/inquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...data, lang: window.NXLang || 'EN' }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || 'Submit failed');
      }
      set({ submitted: true });
      setConfirmed(true);
    } catch (err) {
      console.error('inquiry submit error', err);
      setSubmitError(t('form.err.network'));
    } finally {
      setSubmitting(false);
    }
  };

  const reset = () => {
    localStorage.removeItem(FORM_KEY);
    setData(defaultData());
    setConfirmed(false);
    setSubmitError(null);
    setStep(0);
  };

  const onKeyDown = (e) => {
    if (confirmed || submitting) return;
    if (e.target.tagName === 'TEXTAREA') return;
    if (e.key === 'Enter') {
      e.preventDefault();
      if (step === STEPS_DEF.length - 1) submit();
      else next();
    }
  };

  const progress = ((step + 1) / STEPS_DEF.length) * 100;
  const firstName = (data.name || '').split(' ')[0] || t('form.confirm.fallback');

  return (
    <section className="section form-section" id="start">
      <div className="shell">
        <div className="form-grid">
          <div className="form-side reveal">
            <div className="eyebrow-row" style={{marginBottom: 28}}>
              <span className="dot"></span>
              <span className="mono">{t('form.eyebrow')}</span>
              <span className="line"></span>
            </div>
            <h2>{tR('form.title')}</h2>
            <p className="lead">{t('form.lead')}</p>
            <div style={{display:'flex', flexDirection:'column', gap: 16}}>
              {[1, 2, 3].map((i) => (
                <div key={i} style={{display:'flex', gap: 12, alignItems:'baseline'}}>
                  <span className="mono" style={{minWidth: 24, color: 'var(--text-muted)'}}>{String(i).padStart(2,'0')}</span>
                  <div>
                    <div style={{fontWeight: 500}}>{t(`form.process.${i}.k`)}</div>
                    <div style={{fontSize: 13, color:'var(--text-2)'}}>{t(`form.process.${i}.v`)}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="form-card reveal" onKeyDown={onKeyDown}>
            <div className="form-progress">
              <span className="step-count">{t('form.steps.of', { n: step + 1, total: STEPS_DEF.length })}</span>
              <div className="bar"><div className="fill" style={{width: `${progress}%`}}></div></div>
              <span className="step-count" style={{color: 'var(--accent-alt)'}}>{STEPS_DEF[step].label}</span>
            </div>

            {confirmed ? (
              <div className={`confirm step-anim-enter`} key="confirm">
                <div className="check-big">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>
                </div>
                <h3 className="serif" style={{fontSize: 40, lineHeight: 1, letterSpacing: '-0.01em', marginBottom: 16}}>
                  {tR('form.confirm.title', { name: firstName })}
                </h3>
                <p style={{color: 'var(--text-2)', fontSize: 16, lineHeight: 1.55, maxWidth: 440, marginBottom: 24}}>
                  {t('form.confirm.body')}
                </p>
                <div style={{display: 'flex', gap: 10, flexWrap:'wrap'}}>
                  <button className="btn btn-ghost btn-sm" onClick={reset}>{t('form.confirm.another')}</button>
                  <a className="btn btn-primary btn-sm" href="#top">{t('form.confirm.top')} <span className="arrow">↑</span></a>
                </div>
              </div>
            ) : (
              <div className={`step-anim-${anim}`} key={step}>
                {step === 0 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.identity')}</h3>
                    <div className="form-fields">
                      <div>
                        <label className="field-label">{t('form.label.name')}</label>
                        <input
                          ref={inputRef}
                          className={`input ${errors.name ? 'error' : ''}`}
                          placeholder={t('form.placeholder.name')}
                          value={data.name}
                          onChange={e => set({ name: e.target.value })}
                        />
                        {errors.name && <div className="field-error">{errors.name}</div>}
                      </div>
                      <div>
                        <label className="field-label">{t('form.label.email')}</label>
                        <input
                          className={`input ${errors.email ? 'error' : ''}`}
                          type="email"
                          inputMode="email"
                          autoComplete="email"
                          placeholder={t('form.placeholder.email')}
                          value={data.email}
                          onChange={e => set({ email: e.target.value })}
                        />
                        {errors.email && <div className="field-error">{errors.email}</div>}
                      </div>
                    </div>
                  </>
                )}

                {step === 1 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.profile')}</h3>
                    <div className="options">
                      {PROFILE_OPTS.map((o, i) => (
                        <button
                          key={o.id}
                          type="button"
                          ref={i === 0 ? inputRef : null}
                          className={`option-card ${data.profile === o.id ? 'selected' : ''}`}
                          onClick={() => set({ profile: o.id })}
                        >
                          <span className="dot-wrap"></span>
                          <span style={{flex: 1}}>{o.label}</span>
                          <span className="kbd">{i + 1}</span>
                        </button>
                      ))}
                    </div>
                    {errors.profile && <div className="field-error" style={{marginTop: 12}}>{errors.profile}</div>}
                  </>
                )}

                {step === 2 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.reach')}</h3>
                    <div className="form-fields">
                      <div>
                        <label className="field-label">{t('form.label.handle')}</label>
                        <input
                          ref={inputRef}
                          className={`input ${errors.handle ? 'error' : ''}`}
                          placeholder={t('form.placeholder.handle')}
                          value={data.handle}
                          onChange={e => set({ handle: e.target.value })}
                        />
                        {errors.handle && <div className="field-error">{errors.handle}</div>}
                      </div>
                      <div>
                        <label className="field-label">{t('form.label.audience')}</label>
                        <div className="chips">
                          {REACH_OPTS.map(r => (
                            <button
                              key={r}
                              type="button"
                              className={`chip ${data.reach === r ? 'selected' : ''}`}
                              onClick={() => set({ reach: r })}
                            >{r}</button>
                          ))}
                        </div>
                        {errors.reach && <div className="field-error">{errors.reach}</div>}
                      </div>
                    </div>
                  </>
                )}

                {step === 3 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.goals')}</h3>
                    <p style={{color: 'var(--text-2)', fontSize: 14, marginTop: -16, marginBottom: 20}}>{t('form.hint.goals')}</p>
                    <div className="chips">
                      {GOAL_OPTS.map((g, i) => (
                        <button
                          key={g}
                          type="button"
                          ref={i === 0 ? inputRef : null}
                          className={`chip ${data.goals.includes(g) ? 'selected' : ''}`}
                          onClick={() => toggleGoal(g)}
                        >
                          <span className="check">✓</span>{g}
                        </button>
                      ))}
                    </div>
                    {errors.goals && <div className="field-error" style={{marginTop: 16}}>{errors.goals}</div>}
                  </>
                )}

                {step === 4 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.budget')}</h3>
                    <div className="form-fields">
                      <div>
                        <label className="field-label">{t('form.label.budget')}</label>
                        <div className="chips">
                          {BUDGET_OPTS.map((b, i) => (
                            <button
                              key={b}
                              type="button"
                              ref={i === 0 ? inputRef : null}
                              className={`chip ${data.budget === b ? 'selected' : ''}`}
                              onClick={() => set({ budget: b })}
                            >{b}</button>
                          ))}
                        </div>
                        {errors.budget && <div className="field-error">{errors.budget}</div>}
                      </div>
                      <div>
                        <label className="field-label">{t('form.label.timeline')}</label>
                        <div className="chips">
                          {TIMELINE_OPTS.map(tl => (
                            <button
                              key={tl}
                              type="button"
                              className={`chip ${data.timeline === tl ? 'selected' : ''}`}
                              onClick={() => set({ timeline: tl })}
                            >{tl}</button>
                          ))}
                        </div>
                        {errors.timeline && <div className="field-error">{errors.timeline}</div>}
                      </div>
                    </div>
                  </>
                )}

                {step === 5 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.context')}</h3>
                    <p style={{color: 'var(--text-2)', fontSize: 14, marginTop: -16, marginBottom: 20}}>{t('form.hint.context')}</p>
                    <textarea
                      ref={inputRef}
                      className="textarea"
                      placeholder={t('form.placeholder.context')}
                      value={data.context}
                      onChange={e => set({ context: e.target.value })}
                    />
                  </>
                )}

                {step === 6 && (
                  <>
                    <h3 className="form-question serif">{tR('form.q.review')}</h3>
                    <div className="summary-list">
                      <Row k={t('form.row.name')} v={data.name} onEdit={() => goToStep(0)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.email')} v={data.email} onEdit={() => goToStep(0)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.profile')} v={PROFILE_OPTS.find(o => o.id === data.profile)?.label || '-'} onEdit={() => goToStep(1)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.handle')} v={data.handle} onEdit={() => goToStep(2)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.audience')} v={data.reach || '-'} onEdit={() => goToStep(2)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.goals')} v={data.goals.join(' · ') || '-'} onEdit={() => goToStep(3)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.budget')} v={data.budget || '-'} onEdit={() => goToStep(4)} editLabel={t('form.edit')}/>
                      <Row k={t('form.row.timeline')} v={data.timeline || '-'} onEdit={() => goToStep(4)} editLabel={t('form.edit')}/>
                      {data.context && <Row k={t('form.row.context')} v={data.context.length > 80 ? data.context.slice(0, 80) + '…' : data.context} onEdit={() => goToStep(5)} editLabel={t('form.edit')}/>}
                    </div>
                    {submitError && (
                      <div className="field-error" style={{marginTop: 16}}>{submitError}</div>
                    )}
                  </>
                )}
              </div>
            )}

            {!confirmed && (
              <div className="form-actions">
                <div style={{display:'flex', gap: 8}}>
                  {step > 0 && (
                    <button className="btn btn-ghost btn-sm" onClick={back} disabled={submitting}>
                      <span style={{transform:'rotate(180deg)', display:'inline-block'}}>→</span> {t('form.btn.back')}
                    </button>
                  )}
                </div>
                <div style={{display:'flex', alignItems:'center', gap: 16}}>
                  {step < STEPS_DEF.length - 1 ? (
                    <button className="btn btn-primary btn-sm" onClick={next}>
                      {t('form.btn.continue')} <span className="arrow">→</span>
                    </button>
                  ) : (
                    <button className="btn btn-violet btn-sm" onClick={submit} disabled={submitting}>
                      {submitting ? t('form.btn.sending') : t('form.btn.submit')} <span className="arrow">→</span>
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Row({ k, v, onEdit, editLabel }) {
  return (
    <div className="row">
      <span className="k">{k}</span>
      <span className="v">{v || <span style={{color:'var(--text-muted)'}}>-</span>}</span>
      <button className="edit" onClick={onEdit}>{editLabel}</button>
    </div>
  );
}

window.NXForm = InquiryForm;
