/* ============================================================
   Bizia — Payment page  (/app/payment?projectId=...)
   One-time build fee. Handles Stripe (live) and demo mode.
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, Button, Icon, Badge } = window;

  function getToken() {
    return sessionStorage.getItem('bz_token') || '';
  }

  function formatInr(minorUnits) {
    return '₹' + (minorUnits / 100).toLocaleString('en-IN', { maximumFractionDigits: 0 });
  }

  function PaymentPage() {
    const params = new URLSearchParams(window.location.hash.split('?')[1] || '');
    const projectId = params.get('projectId');
    const paymentResult = params.get('payment'); // 'success' | 'cancelled'
    const isDemo = params.get('demo') === '1';

    const [loading, setLoading] = useState(false);
    const [quoting, setQuoting] = useState(true);
    const [quote, setQuote] = useState(null);
    const [error, setError] = useState('');
    const [paid, setPaid] = useState(false);

    useEffect(() => {
      if (paymentResult === 'success') {
        setPaid(true);
        // Auto-redirect to builder after 2.5s
        setTimeout(() => {
          window.navigate(`/app/builder?project=${projectId}`);
        }, 2500);
      }
    }, [paymentResult, projectId]);

    useEffect(() => {
      // Skip only when already paid (redirecting away) — a cancelled
      // payment still needs a quote so "Try again" works.
      if (paymentResult === 'success') return;
      if (!projectId) { setQuoting(false); return; }
      (async () => {
        try {
          const project = await window.API.projects.get(projectId);
          if (!project) throw new Error('Project not found.');
          const q = await window.API.pricing.quote({
            projectId,
            organizationId: project.organizationId,
            planId: 'starter',
          });
          setQuote(q);
        } catch (e) {
          setError(e.message || 'Could not build a price quote for this project.');
        } finally {
          setQuoting(false);
        }
      })();
    }, [projectId, paymentResult]);

    async function handlePay() {
      if (!projectId) { setError('No project selected. Go back and create a website first.'); return; }
      if (!getToken()) {
        window.navigate(`/login?next=/app/payment?projectId=${projectId}`);
        return;
      }
      if (!quote) { setError('No quote available yet.'); return; }
      setLoading(true); setError('');
      try {
        // Server derives the amount from the quote just built above —
        // this page never sends a price to the server.
        const result = await window.API.payment.checkout({ projectId, quoteId: quote.quoteId });
        window.location.href = result.checkoutUrl;
      } catch (e) {
        setError(e.message || 'Payment initiation failed');
        setLoading(false);
      }
    }

    const containerStyle = { minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'var(--bg)' };
    const boxStyle = { width: '100%', maxWidth: 480, display: 'flex', flexDirection: 'column', gap: 20 };

    // Success state
    if (paid) {
      return React.createElement('div', { style: containerStyle },
        React.createElement('div', { style: { ...boxStyle, alignItems: 'center', textAlign: 'center' } },
          React.createElement('div', { style: { width: 64, height: 64, borderRadius: '50%', background: 'var(--success)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 8 } },
            React.createElement(Icon, { name: 'check', size: 30 })),
          React.createElement('div', { style: { fontWeight: 800, fontSize: 26 } }, isDemo ? 'Demo payment accepted!' : 'Payment confirmed!'),
          React.createElement('div', { style: { fontSize: 15, color: 'var(--text-2)', lineHeight: 1.6 } }, 'Your website build is starting. Redirecting to the builder…'),
          React.createElement(Button, { variant: 'primary', icon: 'arrowRight', onClick: () => window.navigate(`/app/builder?project=${projectId}`) }, 'Open builder now'),
        ),
      );
    }

    // Cancelled state
    if (paymentResult === 'cancelled') {
      return React.createElement('div', { style: containerStyle },
        React.createElement('div', { style: { ...boxStyle, alignItems: 'center', textAlign: 'center' } },
          React.createElement('div', { style: { fontWeight: 700, fontSize: 22, marginBottom: 8 } }, 'Payment cancelled'),
          React.createElement('div', { style: { fontSize: 14, color: 'var(--text-2)', marginBottom: 16 } }, 'No charge was made. You can try again when ready.'),
          React.createElement(Button, { variant: 'primary', onClick: handlePay, loading }, 'Try again'),
          React.createElement(Button, { variant: 'ghost', onClick: () => window.navigate('/app') }, 'Back to dashboard'),
          error && React.createElement('div', { style: { color: 'var(--danger)', fontSize: 13 } }, error),
        ),
      );
    }

    // Default: show pricing + pay button
    return React.createElement('div', { style: containerStyle },
      React.createElement('div', { style: boxStyle },
        React.createElement('div', { style: { textAlign: 'center' } },
          React.createElement('div', { style: { fontWeight: 800, fontSize: 28, letterSpacing: '-0.02em', marginBottom: 6 } }, 'One last step'),
          React.createElement('div', { style: { fontSize: 15, color: 'var(--text-2)', lineHeight: 1.6 } }, 'Pay once. We\'ll build your full website and give you edit credits.'),
        ),
        React.createElement(Card, { pad: 28, style: { display: 'flex', flexDirection: 'column', gap: 20 } },
          // Price block — always the server-quoted amount, never hardcoded
          React.createElement('div', { style: { display: 'flex', alignItems: 'flex-end', gap: 8, justifyContent: 'center' } },
            quoting
              ? React.createElement('div', { style: { fontSize: 20, color: 'var(--text-2)' } }, 'Calculating price…')
              : quote
              ? [
                  React.createElement('div', { key: 'amt', style: { fontSize: 48, fontWeight: 800, letterSpacing: '-0.04em', lineHeight: 1 } }, formatInr(quote.oneTimeTotal)),
                  React.createElement('div', { key: 'unit', style: { fontSize: 14, color: 'var(--muted)', marginBottom: 6 } }, 'one-time'),
                ]
              : React.createElement('div', { style: { fontSize: 15, color: 'var(--danger)' } }, 'Could not load pricing'),
          ),
          // Feature list
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
            [
              ['sparkles', 'AI-generated full website (all pages)'],
              ['wand', '5 free AI edit credits included'],
              ['eye', 'Live preview before going public'],
              ['rocket', 'Publish-ready files & hosting guidance'],
            ].map(([icon, label]) =>
              React.createElement('div', { key: label, style: { display: 'flex', alignItems: 'center', gap: 10, fontSize: 14 } },
                React.createElement('div', { style: { width: 22, height: 22, borderRadius: 6, background: 'var(--primary-soft)', color: 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } },
                  React.createElement(Icon, { name: icon, size: 12 })),
                label,
              )
            )
          ),
          React.createElement('div', { style: { borderTop: '1px solid var(--border-soft)', paddingTop: 16 } },
            error && React.createElement('div', { style: { color: 'var(--danger)', fontSize: 13, marginBottom: 12 } }, error),
            React.createElement(Button, { variant: 'primary', full: true, icon: 'creditCard', loading, disabled: quoting || !quote, onClick: handlePay },
              loading ? 'Redirecting to payment…' : quote ? `Pay ${formatInr(quote.oneTimeTotal)} and start building` : 'Pay and start building'),
          ),
          React.createElement('div', { style: { textAlign: 'center', fontSize: 12, color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 } },
            React.createElement(Icon, { name: 'shield', size: 12 }), 'Secure payment via Stripe · No subscription · Cancel anytime',
          ),
        ),
        React.createElement('div', { style: { textAlign: 'center' } },
          React.createElement('button', {
            onClick: () => window.navigate('/app/new-website'),
            style: { background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', fontSize: 13 },
          }, '← Back to setup'),
        ),
      ),
    );
  }

  window.PaymentPage = PaymentPage;
})();
