// paywall.jsx — betalingsmur. Vises når en bruger er logget ind men ikke har betalt.
// Engangsbeløb på 100 kr giver permanent adgang. Betaling sker via Stripe Checkout
// (Cloud Function), og adgang gives først når webhooken har sat paid=true i Firestore.
const { useState: useStatePW, useEffect: useEffectPW, useRef: useRefPW } = React;

function Paywall({ user, onPaid, onLogout }) {
  // Tre tilstande: 'idle' (vis tilbud), 'redirecting' (på vej til Stripe),
  // 'verifying' (retur fra Stripe — venter på webhook).
  const params = new URLSearchParams(window.location.search);
  const returnedFromStripe = params.get('betaling') === 'ok';
  const urlCode = params.get('kode') || '';
  const [phase, setPhase] = useStatePW(returnedFromStripe ? 'verifying' : 'idle');
  const [error, setError] = useStatePW('');
  const pollRef = useRefPW(null);

  // Adgangskode-felt.
  const [showCode, setShowCode] = useStatePW(!!urlCode);
  const [code, setCode] = useStatePW(urlCode);
  const [codeBusy, setCodeBusy] = useStatePW(false);
  const [codeMsg, setCodeMsg] = useStatePW('');
  const autoTried = useRefPW(false);

  async function redeem() {
    const c = code.trim();
    if (!c) return;
    setCodeMsg(''); setCodeBusy(true);
    try {
      await window.PlaniqFirebase.redeemCode(c);
      cleanUrl();
      onPaid();
    } catch (e) {
      setCodeMsg(e.message || 'Koden kunne ikke indløses.');
      setCodeBusy(false);
    }
  }

  // Auto-indløs hvis koden kom via ?kode=… i linket.
  useEffectPW(() => {
    if (urlCode && !autoTried.current && phase === 'idle') {
      autoTried.current = true;
      redeem();
    }
  }, []);

  // Efter retur fra Stripe: poll Firestore indtil webhooken har sat paid=true.
  useEffectPW(() => {
    if (phase !== 'verifying') return;
    const fb = window.PlaniqFirebase;
    const uid = fb && fb.auth.currentUser && fb.auth.currentUser.uid;
    if (!uid) { setPhase('idle'); return; }

    let tries = 0;
    const tick = async () => {
      tries++;
      try {
        if (await fb.isPaid(uid)) {
          cleanUrl();
          onPaid();
          return;
        }
      } catch (e) { /* prøv igen */ }
      if (tries >= 15) { // ~30 sek
        setError('Vi kunne ikke bekræfte din betaling endnu. Det kan tage et øjeblik — prøv at genindlæse siden om lidt.');
        setPhase('idle');
        return;
      }
      pollRef.current = setTimeout(tick, 2000);
    };
    tick();
    return () => clearTimeout(pollRef.current);
  }, [phase]);

  function cleanUrl() {
    // Fjern ?betaling=… / ?kode=… fra adresselinjen.
    window.history.replaceState({}, '', window.location.pathname);
  }

  async function start() {
    setError('');
    setPhase('redirecting');
    try {
      const res = await window.PlaniqFirebase.startCheckout();
      if (res && res.alreadyPaid) { onPaid(); return; }
      // ellers redirecter startCheckout selv til Stripe.
    } catch (e) {
      setError(e.message || 'Noget gik galt. Prøv igen.');
      setPhase('idle');
    }
  }

  const busy = phase === 'redirecting' || phase === 'verifying';

  return (
    <div className="scroll" style={{ height: '100%', background:
      'radial-gradient(1200px 600px at 80% -10%, var(--accent-tint), transparent 60%), radial-gradient(900px 500px at 0% 110%, var(--sage-tint), transparent 55%), var(--bg)' }}>
      <header className="row lp-header" style={{ padding: '22px 40px', maxWidth: 1180, margin: '0 auto', justifyContent: 'space-between' }}>
        <Logo size={32} />
        <button className="btn btn-ghost" onClick={onLogout}>Log ud</button>
      </header>

      <div className="center" style={{ padding: '40px 20px 60px' }}>
        <div className="card anim-up" style={{ width: 460, maxWidth: '100%', padding: 36, textAlign: 'center' }}>
          <div className="center" style={{ marginBottom: 20 }}><LogoMark size={56} /></div>

          {phase === 'verifying' ? (
            <>
              <h2 style={{ fontSize: 24, marginBottom: 10 }}>Bekræfter din betaling…</h2>
              <p className="muted" style={{ fontSize: 16, lineHeight: 1.5 }}>Et øjeblik — vi giver dig adgang lige om lidt.</p>
              <div className="center" style={{ marginTop: 22 }}><span className="pw-spinner" /></div>
            </>
          ) : (
            <>
              <h2 style={{ fontSize: 26, marginBottom: 8 }}>Få fuld adgang til Planiq</h2>
              <p className="muted" style={{ fontSize: 17, lineHeight: 1.5, marginBottom: 22 }}>
                Lav alle de bordplaner du vil — til barnedåb, konfirmation, bryllup og fødselsdag.
              </p>

              <div style={{ background: 'var(--surface-2)', borderRadius: 'var(--radius)', padding: '22px 20px', marginBottom: 22 }}>
                <div className="row center" style={{ gap: 8, alignItems: 'baseline' }}>
                  <span style={{ fontFamily: 'var(--font-disp)', fontSize: 44, fontWeight: 600, color: 'var(--ink)' }}>100 kr</span>
                  <span className="muted" style={{ fontSize: 16, fontWeight: 700 }}>engang</span>
                </div>
                <p className="faint" style={{ fontSize: 14, fontWeight: 700, marginTop: 4 }}>Permanent adgang — ingen abonnement.</p>
              </div>

              <div className="col gap-2" style={{ textAlign: 'left', marginBottom: 24 }}>
                {['Ubegrænset antal projekter', 'Gæsteliste, grupper og diæter', 'Træk-og-slip bordplan + auto-placering', 'Print og del oversigt'].map(f => (
                  <div key={f} className="row gap-2" style={{ fontSize: 15.5, fontWeight: 700, color: 'var(--ink-soft)' }}>
                    <Icon name="check" size={18} color="var(--sage-deep)" /> {f}
                  </div>
                ))}
              </div>

              {error && <p style={{ color: 'var(--warn)', fontSize: 14.5, marginBottom: 14 }}>{error}</p>}

              <button className="btn btn-primary btn-lg" style={{ width: '100%' }} onClick={start} disabled={busy || codeBusy}>
                {phase === 'redirecting' ? 'Åbner betaling…' : <>Kom i gang <Icon name="chevR" size={20} /></>}
              </button>
              <p className="faint" style={{ fontSize: 13, marginTop: 14 }}>Sikker betaling via Stripe.</p>

              {/* Adgangskode (gratis adgang via særligt link/kode) */}
              <div style={{ marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                {!showCode ? (
                  <button className="link" style={{ background: 'none', border: 'none', color: 'var(--accent-deep)', fontWeight: 800, fontSize: 14.5, cursor: 'pointer' }}
                    onClick={() => setShowCode(true)}>Har du en adgangskode?</button>
                ) : (
                  <div className="col gap-2">
                    <div className="row gap-2">
                      <input className="input" placeholder="Indtast kode" value={code}
                        onChange={e => setCode(e.target.value)}
                        onKeyDown={e => { if (e.key === 'Enter') redeem(); }}
                        style={{ flex: 1, textTransform: 'uppercase' }} disabled={codeBusy} />
                      <button className="btn btn-sage" onClick={redeem} disabled={codeBusy || !code.trim()}>
                        {codeBusy ? 'Tjekker…' : 'Indløs'}
                      </button>
                    </div>
                    {codeMsg && <p style={{ color: 'var(--warn)', fontSize: 13.5, textAlign: 'left' }}>{codeMsg}</p>}
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Paywall });
