const { useState, useEffect, useRef, useMemo } = React;

const STORAGE_KEY = 'pmt_anamnese_v1';

function loadSaved() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { values: {}, step: -1, completedSteps: [] };
    const parsed = JSON.parse(raw);
    return {
      values: parsed.values || {},
      step: typeof parsed.step === 'number' ? parsed.step : -1,
      completedSteps: parsed.completedSteps || [],
    };
  } catch { return { values: {}, step: -1, completedSteps: [] }; }
}

function validateField(field, value) {
  if (!field.required) return null;
  const v = (value ?? '').toString().trim();
  if (!v) return 'Campo obrigatório';
  if (field.type === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return 'E-mail inválido';
  if (field.type === 'number' && isNaN(Number(v))) return 'Digite um número';
  return null;
}

function validateSection(section, values) {
  const errors = {};
  for (const f of section.fields) {
    const err = validateField(f, values[f.id]);
    if (err) errors[f.id] = err;
  }
  return errors;
}

// ── Logo component (tipográfica, criada do zero)
function LogoPMT() {
  return (
    <a href="#" className="logo-pmt" onClick={e => e.preventDefault()}>
      <span className="logo-mark">PMT.</span>
      <span className="logo-meta">
        <span className="name">Pedro Matias</span>
        <span className="role">Consultoria Online</span>
      </span>
    </a>
  );
}

function SaveIndicator({ status }) {
  const label =
    status === 'saving' ? 'Salvando...' :
    status === 'saved'  ? 'Progresso salvo' : 'Auto-save ativo';
  return (
    <div className="save-indicator" title="Suas respostas são salvas automaticamente no seu dispositivo.">
      <span className={'save-dot' + (status === 'saving' ? ' saving' : '')}></span>
      <span>{label}</span>
    </div>
  );
}

function Stepper({ sections, step, completedSteps, onJump }) {
  return (
    <nav className="stepper" aria-label="Seções do formulário">
      {sections.map((s, i) => {
        const active = i === step;
        const done = completedSteps.includes(i);
        const num = String(i + 1).padStart(2, '0');
        return (
          <button
            key={s.id}
            type="button"
            className={'step' + (active ? ' active' : '') + (done ? ' done' : '')}
            onClick={() => onJump(i)}
            disabled={!done && !active && i > step}
          >
            <span className="step-num">{num}</span>
            <span className="step-label">{s.label}</span>
            <span className="step-check">{done ? '✓' : ''}</span>
          </button>
        );
      })}
    </nav>
  );
}

function Intro({ onStart, hasSaved }) {
  return (
    <div className="intro-wrap page-enter">
      <div className="kicker">Ficha de anamnese</div>
      <h2>Um novo caminho pra sua <em>evolução</em> começa com boas perguntas.</h2>
      <p className="lead">
        Preencha esta ficha com calma e honestidade — quanto mais real você for, mais certeiro vai ser o seu plano.
        Suas respostas ficam salvas automaticamente, então você pode pausar e voltar quando quiser.
      </p>

      <div className="intro-meta">
        <div className="meta-cell">
          <div className="k">Tempo estimado</div>
          <div className="v">10–15 minutos</div>
        </div>
        <div className="meta-cell">
          <div className="k">Seções</div>
          <div className="v">7 blocos temáticos</div>
        </div>
        <div className="meta-cell">
          <div className="k">Privacidade</div>
          <div className="v">Apenas o Pedro verá</div>
        </div>
      </div>

      <div style={{display:'flex', gap:12, marginTop:24, flexWrap:'wrap'}}>
        <button className="btn btn-primary" onClick={onStart}>
          {hasSaved ? 'Continuar de onde parei' : 'Começar agora'}
          <span className="arrow">→</span>
        </button>
        {hasSaved && (
          <button
            className="btn btn-ghost"
            onClick={() => {
              if (confirm('Apagar respostas salvas e começar do zero?')) {
                localStorage.removeItem(STORAGE_KEY);
                location.reload();
              }
            }}
          >Recomeçar do zero</button>
        )}
      </div>
    </div>
  );
}

function Success({ values, onEdit }) {
  const entries = Object.entries(values).filter(([, v]) => v && String(v).trim());
  return (
    <div className="success-wrap page-enter">
      <div className="success-mark">✓</div>
      <h2>Ficha enviada</h2>
      <p>
        Obrigado pela confiança, <b style={{color:'#fff'}}>{values.nome?.split(' ')[0] || 'atleta'}</b>.
        O Pedro vai revisar tudo e te chamar no WhatsApp nas próximas 24h com o próximo passo.
      </p>
      <div className="summary">
        <div><b>Resumo</b></div>
        <div>— {entries.length} respostas registradas</div>
        <div>— Enviado em {new Date().toLocaleString('pt-BR')}</div>
        <div>— ID: PMT-{Math.random().toString(36).slice(2, 8).toUpperCase()}</div>
      </div>
      <button className="btn btn-ghost" style={{marginTop:24}} onClick={onEdit}>
        Revisar respostas
      </button>
    </div>
  );
}

function App() {
  const saved = useMemo(loadSaved, []);
  const [values, setValues] = useState(saved.values);
  const [step, setStep] = useState(saved.step); // -1 = intro, SCHEMA.length = success
  const [completedSteps, setCompletedSteps] = useState(saved.completedSteps);
  const [errors, setErrors] = useState({});
  const [saveStatus, setSaveStatus] = useState('saved');
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const saveTimer = useRef(null);
  const startedAtRef = useRef(null);
  const honeypotRef = useRef(null);

  useEffect(() => { startedAtRef.current = Date.now(); }, []);

  // Auto-save (não persiste depois que a ficha foi enviada)
  useEffect(() => {
    if (step >= SCHEMA.length) return;
    setSaveStatus('saving');
    clearTimeout(saveTimer.current);
    saveTimer.current = setTimeout(() => {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify({ values, step, completedSteps }));
        setSaveStatus('saved');
      } catch { setSaveStatus('saved'); }
    }, 400);
    return () => clearTimeout(saveTimer.current);
  }, [values, step, completedSteps]);

  const totalFields = useMemo(
    () => SCHEMA.reduce((n, s) => n + s.fields.filter(f => f.required).length, 0),
    []
  );
  const filledRequired = useMemo(
    () => SCHEMA.reduce((n, s) =>
      n + s.fields.filter(f => f.required && (values[f.id] ?? '').toString().trim()).length, 0),
    [values]
  );
  const progressPct = step < 0 ? 0 : step >= SCHEMA.length ? 100 : Math.round((filledRequired / totalFields) * 100);

  const handleChange = (id, v) => {
    setValues(prev => ({ ...prev, [id]: v }));
    if (errors[id]) setErrors(prev => ({ ...prev, [id]: null }));
  };

  const goNext = async () => {
    const section = SCHEMA[step];
    const errs = validateSection(section, values);
    if (Object.keys(errs).length) {
      setErrors(errs);
      // scroll to first error
      setTimeout(() => {
        const firstErr = document.querySelector('.input.error, .textarea.error, .err-msg');
        if (firstErr) firstErr.scrollIntoView ? null : null;
      }, 10);
      return;
    }
    setErrors({});

    // Última seção: envia a ficha em vez de só avançar
    if (step === SCHEMA.length - 1) {
      setSubmitting(true);
      setSubmitError(null);
      try {
        const payload = {
          ...values,
          website: honeypotRef.current ? honeypotRef.current.value : '',
          _startedAt: startedAtRef.current,
        };
        const res = await fetch('/api/submit', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error(data.error || `Erro ${res.status}`);
        }
        localStorage.removeItem(STORAGE_KEY);
        setCompletedSteps(prev => prev.includes(step) ? prev : [...prev, step]);
        setStep(step + 1);
        window.scrollTo({ top: 0, behavior: 'smooth' });
      } catch (err) {
        setSubmitError(err.message || 'Não foi possível enviar. Tente novamente.');
      } finally {
        setSubmitting(false);
      }
      return;
    }

    setCompletedSteps(prev => prev.includes(step) ? prev : [...prev, step]);
    setStep(step + 1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const goPrev = () => {
    setErrors({});
    setStep(Math.max(-1, step - 1));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const jumpTo = (i) => {
    if (completedSteps.includes(i) || i === step || i < step) {
      setErrors({});
      setStep(i);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const handleStart = () => setStep(step < 0 ? 0 : step);

  const isIntro = step < 0;
  const isSuccess = step >= SCHEMA.length;
  const section = !isIntro && !isSuccess ? SCHEMA[step] : null;
  const hasSaved = Object.keys(saved.values).length > 0 || saved.step >= 0;

  return (
    <div className="shell">
      <input
        ref={honeypotRef}
        className="hp"
        type="text"
        name="website"
        tabIndex={-1}
        autoComplete="off"
        aria-hidden="true"
      />
      <header className="topbar">
        <LogoPMT />
        <div className="topbar-right">
          <SaveIndicator status={saveStatus} />
        </div>
      </header>

      <div className="layout">
        <aside className="sidebar">
          <h1>Ficha de<br/>Anamnese<span className="pill">PMT</span></h1>
          <p className="lead">Quanto mais honesta for sua resposta, mais certeiro vai ser o plano que o Pedro vai montar pra você.</p>

          {!isIntro && !isSuccess && (
            <Stepper
              sections={SCHEMA}
              step={step}
              completedSteps={completedSteps}
              onJump={jumpTo}
            />
          )}
        </aside>

        <main className="form-card">
          {isIntro && <Intro onStart={handleStart} hasSaved={hasSaved} />}

          {isSuccess && <Success values={values} onEdit={() => setStep(SCHEMA.length - 1)} />}

          {section && (
            <div className="page-enter" key={section.id}>
              <div className="section-head">
                <div>
                  <div className="eyebrow">{section.eyebrow}</div>
                  <h2>{section.title}</h2>
                </div>
                <div className="count">
                  {String(step + 1).padStart(2,'0')} / {String(SCHEMA.length).padStart(2,'0')}
                </div>
              </div>

              <div className="fields">
                <FieldList
                  fields={section.fields}
                  values={values}
                  errors={errors}
                  onChange={handleChange}
                />
              </div>

              <footer className="form-footer">
                <div className="progress-wrap">
                  <div className="progress-label">
                    <span>Progresso</span>
                    <span><b>{progressPct}%</b></span>
                  </div>
                  <div className="progress-track">
                    <div className="progress-bar" style={{width: progressPct + '%'}}></div>
                  </div>
                </div>

                {submitError && (
                  <div className="err-msg" style={{marginBottom:10}} role="alert">
                    {submitError} — suas respostas continuam salvas; pode tentar novamente.
                  </div>
                )}
                <div style={{display:'flex', gap:10}}>
                  <button
                    className="btn btn-ghost"
                    onClick={goPrev}
                    disabled={step === 0 || submitting}
                  >
                    ← Voltar
                  </button>
                  <button
                    className="btn btn-primary"
                    onClick={goNext}
                    disabled={submitting}
                  >
                    {submitting
                      ? 'Enviando...'
                      : step === SCHEMA.length - 1 ? 'Enviar ficha' : 'Próximo'}
                    {!submitting && <span className="arrow">→</span>}
                  </button>
                </div>
              </footer>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
