// ── Credits store — balance + PayPal Smart Buttons ──────────────

function Credits({ navigate, user, credits, onSignOut, onChange }) {
  const [data, setData] = useState({ balance: credits, packs: [] });
  const [loading, setLoading] = useState(true);
  const [paypalReady, setPaypalReady] = useState(Boolean(window.paypal));
  const [paypalClientId, setPaypalClientId] = useState(null);
  const [toast, setToast] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const [cfg, creditsData] = await Promise.all([Api.config(), Api.credits()]);
        setPaypalClientId(cfg.paypalClientId);
        setData(creditsData);
      } catch (err) {
        console.error('credits load failed', err);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  // Lazy-load PayPal Smart Buttons SDK with our client ID.
  useEffect(() => {
    if (!paypalClientId || window.paypal) {
      if (window.paypal) setPaypalReady(true);
      return;
    }
    const id = 'paypal-sdk';
    if (document.getElementById(id)) return;
    const script = document.createElement('script');
    script.id = id;
    script.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(paypalClientId)}&currency=USD&intent=capture`;
    script.async = true;
    script.onload = () => setPaypalReady(true);
    script.onerror = () => setToast('Could not load PayPal');
    document.head.appendChild(script);
  }, [paypalClientId]);

  const balance = typeof data.balance === 'number' ? data.balance : credits;

  return (
    <div className="pm-shell">
      <PMSidebar navigate={navigate} active="credits" user={user} credits={balance} onSignOut={onSignOut} />

      <div className="pm-content" data-screen-label="credits">
        <div style={{ padding: '34px 34px 48px', maxWidth: 1040 }}>

          {/* Top row: back link · eyebrow · balance pill */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 8, flexWrap: 'wrap' }}>
            <button onClick={() => navigate('studio')} className="btn btn-ghost btn-sm">← Studio</button>
            <span style={{
              fontFamily: 'var(--mono)', fontSize: 9.5, letterSpacing: '0.14em',
              textTransform: 'uppercase', color: 'var(--ink-3)',
            }}>Credits store</span>
            <div style={{ flex: 1 }} />
            <span style={{
              padding: '8px 15px', borderRadius: 100,
              border: '1px solid var(--line-2)', background: 'var(--surface)',
              fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.06em', color: 'var(--ink-2)',
            }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--brand)', display: 'inline-block', marginRight: 6 }} />
              <strong style={{ color: 'var(--ink)' }}>{typeof balance === 'number' ? balance : '—'}</strong>{' '}
              CREDIT{balance === 1 ? '' : 'S'}
            </span>
          </div>

          <h1 style={{
            fontFamily: 'var(--serif)', fontWeight: 500,
            fontSize: 'clamp(40px, 5vw, 52px)', lineHeight: 1, letterSpacing: '-0.02em',
            margin: '12px 0 10px',
          }}>
            Top up your <em style={{ color: 'var(--brand-deep)' }}>shelf</em>.
          </h1>
          <p style={{ fontSize: 14, color: 'var(--ink-2)', maxWidth: 520, margin: '0 0 30px', lineHeight: 1.55 }}>
            One credit renders one painted plate. Bigger packs work out cheaper per credit — pay once, no subscription.
          </p>

          {toast && (
            <div style={{
              padding: '12px 16px', borderRadius: 10, marginBottom: 24,
              background: toast.startsWith('✓') ? 'var(--brand-soft)' : 'rgba(200,50,74,0.10)',
              border: toast.startsWith('✓') ? '1px solid var(--brand-bright)' : '1px solid rgba(200,50,74,0.30)',
              color: toast.startsWith('✓') ? 'var(--ink)' : 'var(--brand-deep)',
              fontSize: 13.5,
            }}>{toast}</div>
          )}

          {loading ? (
            <div style={{ padding: 80, color: 'var(--ink-3)', textAlign: 'center' }}>Loading credits…</div>
          ) : (
            <>
              <div style={{
                display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, alignItems: 'start',
              }}>
                {data.packs.map((pack, i) => (
                  <PackCard
                    key={pack.id}
                    pack={pack}
                    featured={i === 1}
                    paypalReady={paypalReady}
                    onPaid={(creditsAdded, newBalance) => {
                      setData(d => ({ ...d, balance: newBalance }));
                      setToast(`✓ ${creditsAdded} credits added`);
                      onChange && onChange();
                      setTimeout(() => setToast(null), 5000);
                    }}
                    onError={(msg) => setToast(msg)}
                  />
                ))}
              </div>

              <p style={{
                marginTop: 22, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.08em',
                color: 'var(--ink-3)', textAlign: 'center',
              }}>
                SECURE CHECKOUT · PAY WITH PAYPAL OR CARD · NO SUBSCRIPTION
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function PackCard({ pack, featured, paypalReady, onPaid, onError }) {
  const btnRef = useRef(null);
  const [rendering, setRendering] = useState(false);

  useEffect(() => {
    if (!paypalReady || !btnRef.current || rendering) return;
    setRendering(true);
    btnRef.current.innerHTML = '';
    window.paypal.Buttons({
      style: {
        layout: 'vertical',
        color: featured ? 'gold' : 'silver',
        shape: 'pill',
        label: 'paypal',
        height: 44,
      },
      createOrder: async () => {
        try {
          const resp = await Api.paypalCreateOrder(pack.id);
          return resp.orderId;
        } catch (err) {
          onError && onError('Could not start payment: ' + err.message);
          throw err;
        }
      },
      onApprove: async (data) => {
        try {
          const resp = await Api.paypalCaptureOrder(data.orderID);
          onPaid && onPaid(resp.creditsAdded, resp.balance);
        } catch (err) {
          onError && onError('Payment capture failed: ' + err.message);
        }
      },
      onError: (err) => {
        onError && onError('PayPal error: ' + (err?.message || 'unknown'));
      },
    }).render(btnRef.current);
  }, [paypalReady, pack.id, featured]);

  const perCredit = (parseFloat(pack.price) / pack.credits).toFixed(2);
  const muted = featured ? 'rgba(246,244,239,0.55)' : 'var(--ink-3)';

  return (
    <div style={{
      background: featured ? 'var(--sidebar)' : 'var(--surface)',
      color: featured ? 'var(--sidebar-ink)' : 'var(--ink)',
      border: featured ? 'none' : '1px solid var(--line-2)',
      borderRadius: 12,
      padding: '26px 22px 22px',
      display: 'flex', flexDirection: 'column',
      transform: featured ? 'translateY(-8px)' : 'none',
      boxShadow: featured ? '0 24px 50px -20px rgba(0,0,0,0.5)' : 'none',
      position: 'relative',
    }}>
      {featured && (
        <span style={{
          position: 'absolute', top: -11, left: 22,
          background: 'var(--brand)', color: '#242424',
          padding: '4px 11px', borderRadius: 100,
          fontFamily: 'var(--mono)', fontSize: 9, fontWeight: 700, letterSpacing: '0.1em',
        }}>BEST VALUE</span>
      )}

      <div style={{ fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 600 }}>{pack.label}</div>
      <div style={{ fontSize: 12, color: muted, marginBottom: 16 }}>${perCredit} per credit</div>

      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 6 }}>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 40, fontWeight: 600, lineHeight: 1 }}>
          {pack.credits}
        </span>
        <span style={{ fontSize: 13, color: muted }}>credits</span>
      </div>

      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginBottom: 20 }}>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 24, fontWeight: 600 }}>${pack.price}</span>
        <span style={{ fontSize: 11, color: muted }}>one-time</span>
      </div>

      <div ref={btnRef} style={{ marginTop: 'auto' }} />
      {!paypalReady && (
        <div style={{ marginTop: 14, fontSize: 12, color: muted }}>
          Loading PayPal…
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Credits });
