// ============================================
// PAYMENT-RETURN — gebruiker komt hier terug na Mollie
// ============================================

function PaymentReturnPage({ navigate }) {
  const { Reveal, Icon } = window.LM_UI;
  const { t } = window.LM_CMS;

  // Lees id uit hash: #/payment-return?id=s_xxx
  const getIdFromHash = () => {
    const h = window.location.hash || '';
    const m = h.match(/[?&]id=([^&]+)/);
    return m ? decodeURIComponent(m[1]) : '';
  };

  const [id] = React.useState(getIdFromHash);
  const [status, setStatus] = React.useState(null);
  const [polling, setPolling] = React.useState(true);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    if (!id) { setError('Geen referentie gevonden in de URL.'); setPolling(false); return; }
    let cancelled = false;
    let timer = null;
    let tries = 0;
    const tick = async () => {
      tries++;
      try {
        const s = await window.LM_PAYMENT_STATUS(id);
        if (cancelled) return;
        setStatus(s);
        if (['paid', 'failed', 'canceled', 'expired'].includes(s.paymentStatus) || tries >= 12) {
          setPolling(false);
          return;
        }
      } catch (err) {
        if (cancelled) return;
        setError('Status kon niet opgehaald worden.');
        setPolling(false);
        return;
      }
      timer = setTimeout(tick, 2500);
    };
    tick();
    return () => { cancelled = true; if (timer) clearTimeout(timer); };
  }, [id]);

  const ps = status?.paymentStatus;
  const isPaid = ps === 'paid';
  const isFailed = ['failed', 'canceled', 'expired'].includes(ps);
  const isPending = !ps || ['open', 'pending'].includes(ps);

  return (
    <section className="section" style={{ minHeight: '60vh' }}>
      <div className="container" style={{ maxWidth: 640 }}>
        <Reveal>
          <div className="card" style={{ padding: '48px 40px', textAlign: 'center' }}>

            {error && (
              <>
                <h2 className="display" style={{ fontSize: 28, margin: '0 0 12px', textTransform: 'none', letterSpacing: '-0.01em' }}>Iets liep mis</h2>
                <p style={{ color: 'var(--ink-500)' }}>{error}</p>
              </>
            )}

            {!error && polling && (
              <>
                <div style={{
                  width: 56, height: 56, borderRadius: '50%',
                  border: '4px solid var(--ink-100)', borderTopColor: 'var(--blue-500)',
                  margin: '0 auto 20px', animation: 'spin 1s linear infinite',
                }} />
                <h2 className="display" style={{ fontSize: 28, margin: '0 0 12px', textTransform: 'none', letterSpacing: '-0.01em' }}>
                  We bevestigen je betaling…
                </h2>
                <p style={{ color: 'var(--ink-500)' }}>
                  Dit duurt enkele seconden. Sluit deze pagina niet.
                </p>
                <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
              </>
            )}

            {!error && !polling && isPaid && (
              <>
                <div style={{
                  width: 72, height: 72, borderRadius: '50%',
                  background: 'var(--gradient)', color: 'white',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  margin: '0 auto 24px',
                }}>
                  <Icon.Check size={32} />
                </div>
                <h2 className="display" style={{ fontSize: 32, margin: '0 0 16px', textTransform: 'none', letterSpacing: '-0.01em' }}>
                  Inschrijving bevestigd!
                </h2>
                <p style={{ fontSize: 16, color: 'var(--ink-500)', margin: '0 0 16px' }}>
                  Je betaling van <strong>€{status.amount}</strong> via {status.method || 'Mollie'} is goed aangekomen.
                  We sturen je binnen 24u een bevestigingsmail.
                </p>
                <p className="mono" style={{ fontSize: 11, color: 'var(--ink-500)', letterSpacing: '0.08em' }}>
                  Referentie: {status.id}
                </p>
                <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <button className="btn btn-ghost" onClick={() => navigate('home')}>Terug naar home</button>
                  <button className="btn btn-primary" onClick={() => navigate('lessen')}>Bekijk lessen <Icon.ArrowRight /></button>
                </div>
              </>
            )}

            {!error && !polling && isFailed && (
              <>
                <div style={{
                  width: 72, height: 72, borderRadius: '50%',
                  background: 'var(--ink-100)', color: 'var(--ink-700)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  margin: '0 auto 24px', fontSize: 32, fontWeight: 700,
                }}>×</div>
                <h2 className="display" style={{ fontSize: 28, margin: '0 0 12px', textTransform: 'none', letterSpacing: '-0.01em' }}>
                  Betaling niet voltooid
                </h2>
                <p style={{ color: 'var(--ink-500)', margin: '0 0 24px' }}>
                  Je inschrijving is nog niet definitief. Je kan opnieuw proberen of contact opnemen met de dansschool.
                </p>
                {status?.checkoutUrl && ps === 'open' && (
                  <a className="btn btn-primary" href={status.checkoutUrl} style={{ marginRight: 8 }}>
                    Opnieuw proberen <Icon.ArrowRight />
                  </a>
                )}
                <button className="btn btn-ghost" onClick={() => navigate('contact')}>Contacteer ons</button>
              </>
            )}

            {!error && !polling && isPending && !isPaid && !isFailed && (
              <>
                <div style={{
                  width: 72, height: 72, borderRadius: '50%',
                  background: 'var(--blue-50)', color: 'var(--blue-600)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  margin: '0 auto 24px', fontSize: 32,
                }}>⏳</div>
                <h2 className="display" style={{ fontSize: 28, margin: '0 0 12px', textTransform: 'none', letterSpacing: '-0.01em' }}>
                  Betaling in behandeling
                </h2>
                <p style={{ color: 'var(--ink-500)', margin: '0 0 24px' }}>
                  Sommige betaalmethodes (zoals overschrijving) hebben tijd nodig. Zodra de betaling binnen is, krijg je een bevestigingsmail.
                </p>
                <button className="btn btn-ghost" onClick={() => navigate('home')}>Terug naar home</button>
              </>
            )}

          </div>
        </Reveal>
      </div>
    </section>
  );
}

window.LM_PAGES = window.LM_PAGES || {};
window.LM_PAGES.PaymentReturn = PaymentReturnPage;
