// Public participant bootstrap — renders at /surveys/<slug>

function PublicApp() {
  const [state, setState] = React.useState({ status: 'loading' });
  const [submitted, setSubmitted] = React.useState(false);
  const [enteredDraw, setEnteredDraw] = React.useState(false);
  const startTimeRef = React.useRef(Date.now());

  const slug = (window.location.pathname.match(/^\/surveys\/([^/]+)/) || [])[1];

  React.useEffect(() => {
    if (!slug) { setState({ status: 'notfound' }); return; }
    fetch('/surveys/api/public/' + encodeURIComponent(slug))
      .then(r => {
        if (r.status === 404) { setState({ status: 'notfound' }); return null; }
        if (!r.ok) throw new Error('load failed');
        return r.json();
      })
      .then(survey => {
        if (!survey) return;
        setState({ status: 'ready', survey });
        startTimeRef.current = Date.now();
      })
      .catch(() => setState({ status: 'error' }));
  }, [slug]);

  const handleSubmit = async (answers, prizeEmail) => {
    try {
      const durationSec = Math.round((Date.now() - startTimeRef.current) / 1000);
      const r = await fetch('/surveys/api/public/' + encodeURIComponent(slug) + '/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ answers, durationSec, prizeEmail: prizeEmail || undefined }),
      });
      if (!r.ok) {
        const j = await r.json().catch(() => ({}));
        const L = state.survey && state.survey.lang;
        alert(j.error === 'missing required' ? tr(L, 'alertRequired')
          : j.error === 'invalid email' ? tr(L, 'alertEmail') : tr(L, 'alertFailed'));
        return;
      }
      setEnteredDraw(!!prizeEmail);
      setSubmitted(true);
      window.scrollTo(0, 0);
    } catch (e) {
      alert(tr(state.survey && state.survey.lang, 'alertOffline'));
    }
  };

  if (state.status === 'loading') {
    return <div style={{ padding: 60, textAlign: 'center', color: 'var(--muted)' }}>Loading…</div>;
  }
  if (state.status === 'notfound') {
    return (
      <div style={{
        minHeight: '100vh', background: 'var(--paper)', display: 'flex',
        flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center',
      }}>
        <Wordmark size={28} />
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 36, margin: '24px 0 12px' }}>Survey not found</h1>
        <p style={{ color: 'var(--muted)', fontSize: 14, maxWidth: 360 }}>
          This survey may have closed or the link may be wrong. Check with whoever shared the link.
        </p>
      </div>
    );
  }
  if (state.status === 'error') {
    return <div style={{ padding: 60, textAlign: 'center', color: 'var(--red)' }}>Could not load survey.</div>;
  }

  return (
    <div style={{ maxWidth: 520, margin: '0 auto', background: 'var(--paper)', minHeight: '100vh' }}>
      <PublicSurvey
        survey={state.survey}
        onSubmit={handleSubmit}
        submitted={submitted}
        enteredDraw={enteredDraw}
      />
    </div>
  );
}

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