// screens-credits.jsx — Credits/Packages + Payment flows + Manage subscription
const { useState: _cr_useState, useEffect: _cr_useEffect } = React;

function CreditsScreen({ ctx }){
  const { t: T, balance, premium, navigate } = ctx;
  const packages = window.RAVANA_DATA.packages;
  const availableMethods = (ctx.paymentMethods || ['telegram'])
    .map(m => m === 'telegram' ? 'stars' : m)
    .filter(m => m === 'stars' || m === 'paypal');
  const [method, setMethod] = _cr_useState(availableMethods[0] || 'stars');
  const [pickerOpen, setPickerOpen] = _cr_useState(false);
  const [pkg, setPkg] = _cr_useState(null);

  _cr_useEffect(() => {
    if (!availableMethods.includes(method)) {
      setMethod(availableMethods[0] || 'stars');
    }
  }, [availableMethods.join(','), method]);

  return (
    <div className="screen">
      <ScreenHeader title={T('credits_title')} subtitle={T('credits_sub')}
        right={
          <div className="row" style={{gap: 6}}>
            <HelpButton topic="credits" lang={ctx.lang}/>
            <button className="icon-btn" onClick={()=>navigate('manage_subscription')}><Icon.settings size={16}/></button>
          </div>
        }/>

      {/* Current balance summary */}
      <div className="card" style={{padding: 14, background: 'linear-gradient(135deg, rgba(34,17,77,0.6), rgba(12,15,33,0.6))'}}>
        <div className="row-between" style={{marginBottom: 10}}>
          <div className="dim" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'0.12em'}}>Current balance</div>
          <PremiumChip kind={premium} lang={ctx.lang}/>
        </div>
        <div className="row" style={{gap: 18}}>
          <div className="row" style={{gap: 8}}>
            <Icon.image size={18} style={{color: 'var(--purple-3)'}}/>
            <div>
              <div style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600}}>{balance.photo}</div>
              <div className="dim" style={{fontSize: 10}}>photo cr</div>
            </div>
          </div>
          <div style={{width: 1, height: 28, background: 'rgba(167,176,200,0.18)'}}/>
          <div className="row" style={{gap: 8}}>
            <Icon.video size={18} style={{color: 'var(--cyan)'}}/>
            <div>
              <div style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600}}>{balance.video}</div>
              <div className="dim" style={{fontSize: 10}}>video min</div>
            </div>
          </div>
        </div>
      </div>

      {/* Payment method */}
      <PaymentMethodSelector value={method} onChange={setMethod} onPickerOpen={()=>setPickerOpen(true)}
        onPickerSet={(v)=>{setMethod(v); setPickerOpen(false);}} pickerOpen={pickerOpen}
        ctx={ctx}/>

      {/* Hot combo */}
      <div className="section-title"><h3>Recommended</h3></div>
      <PackageCard pkg={packages.find(p=>p.id==='hot_combo')} method={method}
        onBuy={()=>{setPkg(packages.find(p=>p.id==='hot_combo'));}}/>

      <div className="section-title" style={{marginTop:8}}><h3>Video packages</h3></div>
      <div className="col">
        {packages.filter(p => p.video > 0 && p.id !== 'hot_combo').map(p =>
          <PackageCard key={p.id} pkg={p} method={method} onBuy={()=>setPkg(p)}/>
        )}
      </div>

      <div className="section-title" style={{marginTop:8}}><h3>Photo packages</h3></div>
      <div className="col">
        {packages.filter(p => p.video === 0 && p.id !== 'hot_combo').map(p =>
          <PackageCard key={p.id} pkg={p} method={method} onBuy={()=>setPkg(p)}/>
        )}
      </div>

      {/* Confirmation/Invoice sheet */}
      <PackageConfirmSheet pkg={pkg} method={method} onClose={()=>setPkg(null)}
        ctx={ctx}/>
    </div>
  );
}

function PaymentMethodSelector({ value, onChange, ctx }){
  const { t: T } = ctx;
  const methods = (ctx.paymentMethods || ['telegram'])
    .map(m => m === 'telegram' ? 'stars' : m)
    .filter(m => m === 'stars' || m === 'paypal');
  return (
    <div className="row" style={{gap: 8}}>
      {methods.includes('stars') && <button onClick={()=>onChange('stars')} className={"pkg-card " + (value === 'stars' ? 'selected' : '')}
        style={{flex: 1, padding: '10px 12px', display:'flex', alignItems:'center', gap: 8}}>
        <div style={{width: 24, height: 24, borderRadius: 8, background: 'rgba(246,200,95,0.16)',
          color:'var(--gold)', display:'flex',alignItems:'center',justifyContent:'center'}}>
          <Icon.telegramStar size={14}/>
        </div>
        <div>
          <div style={{fontSize: 12, fontWeight: 600}}>Telegram Stars</div>
        </div>
      </button>}
      {methods.includes('paypal') && <button onClick={()=>onChange('paypal')} className={"pkg-card " + (value === 'paypal' ? 'selected' : '')}
        style={{flex: 1, padding: '10px 12px', display:'flex', alignItems:'center', gap: 8}}>
        <div style={{width: 24, height: 24, borderRadius: 8, background: 'rgba(34,211,238,0.14)',
          color:'var(--cyan)', display:'flex',alignItems:'center',justifyContent:'center'}}>
          <Icon.paypal size={14}/>
        </div>
        <div>
          <div style={{fontSize: 12, fontWeight: 600}}>PayPal</div>
        </div>
      </button>}
    </div>
  );
}

function PackageCard({ pkg, method, onBuy }){
  return (
    <button className={"pkg-card " + (pkg.tag === 'hot' ? 'hot' : '')} onClick={onBuy}>
      {pkg.tag === 'hot' && <div className="pkg-tag">HOT</div>}
      {pkg.tag === 'best' && <div className="pkg-tag purple">BEST</div>}
      {pkg.tag === 'starter' && <div className="pkg-tag" style={{background:'linear-gradient(135deg, var(--cyan), var(--eblue))', color:'white'}}>START</div>}
      <div className="row-between">
        <div style={{flex: 1, minWidth: 0}}>
          <div className="h-card">{pkg.name}</div>
          <div className="dim" style={{marginTop: 4}}>{pkg.subline}</div>
          <div style={{display:'flex', gap: 10, marginTop: 8}}>
            {pkg.video > 0 && <span className="chip chip-cyan"><Icon.video size={11}/> {pkg.video} min</span>}
            {pkg.photo > 0 && <span className="chip chip-purple"><Icon.photo size={11}/> {pkg.photo}</span>}
          </div>
        </div>
        <div style={{textAlign:'right'}}>
          {method === 'stars' ? (
            <div className="row" style={{gap: 4, justifyContent:'flex-end'}}>
              <Icon.telegramStar size={14} style={{color:'var(--gold)'}}/>
              <span style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600, color:'var(--gold)'}}>
                {pkg.stars.toLocaleString()}
              </span>
            </div>
          ) : (
            <div style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600, color:'var(--cyan)'}}>
              ${pkg.usd}
            </div>
          )}
          <div className="dim" style={{fontSize: 10, marginTop: 2}}>{method === 'stars' ? 'Stars' : 'USD'}</div>
        </div>
      </div>
    </button>
  );
}

function PackageConfirmSheet({ pkg, method, onClose, ctx }){
  const { t: T, setBalance, setFortune, fortune } = ctx;
  const [state, setState] = _cr_useState('confirm'); // confirm, waiting, paid, failed, expired
  const [paymentError, setPaymentError] = _cr_useState(null);

  _cr_useEffect(() => {
    if (!pkg) {
      setState('confirm');
      setPaymentError(null);
    }
  }, [pkg]);

  if (!pkg) return null;

  const markPaid = () => {
    setState('paid');
    setBalance(b => ({photo: b.photo + (pkg.photo || 0), video: b.video + (pkg.video || 0)}));
    setFortune(f => ({...f, spins: f.spins + 3}));
  };

  const startPayment = async () => {
    setState('waiting');
    setPaymentError(null);
    const mini = window.RavanaMiniApp || {};
    const tg = mini.telegram;
    const apiMethod = method === 'stars' ? 'telegram' : 'paypal';

    if (mini.debug || !mini.createInvoice) {
      setTimeout(markPaid, 650);
      return;
    }

    try {
      const invoice = await mini.createInvoice(pkg.productId, apiMethod, mini.context);
      if (apiMethod === 'telegram' && tg && tg.openInvoice) {
        tg.openInvoice(invoice.invoice_url, (status) => {
          if (status === 'paid') {
            markPaid();
          } else {
            setPaymentError(status === 'cancelled' ? 'Payment was cancelled.' : 'Payment was not completed.');
            setState('failed');
          }
        });
        return;
      }

      if (tg && tg.openLink) {
        tg.openLink(invoice.invoice_url);
      } else {
        window.location.href = invoice.invoice_url;
      }
    } catch (error) {
      setPaymentError(error.message || 'Payment failed.');
      setState('failed');
    }
  };

  return (
    <Sheet open onClose={onClose}>
      {state === 'confirm' && (
        <div className="col">
          <div className="h-card">{pkg.name}</div>
          <div className="dim">{pkg.subline}</div>
          <CostPanel items={[
            ...(pkg.video > 0 ? [{ k: 'Video credits', v: pkg.video + ' min', tone: 'cyan' }] : []),
            ...(pkg.photo > 0 ? [{ k: 'Photo credits', v: pkg.photo + ' cr', tone: 'gold' }] : []),
            { k: 'Method', v: method === 'stars' ? 'Telegram Stars' : 'PayPal' },
            { k: 'Total',
              v: method === 'stars' ? pkg.stars.toLocaleString() + ' ★' : '$' + pkg.usd,
              tone: 'gold' },
          ]}/>
          <div className="dim" style={{textAlign:'center', fontSize: 11, padding: '0 20px'}}>
            By proceeding you agree to the Terms. Recurring payments off.
          </div>
          <button className="btn btn-primary btn-block btn-lg" onClick={startPayment}>
            {T('pay_now')} {method === 'stars' ? <Icon.telegramStar size={16}/> : <Icon.paypal size={16}/>}
          </button>
          <button className="btn btn-ghost btn-block" onClick={onClose}>{T('cancel')}</button>
        </div>
      )}

      {state === 'waiting' && (
        <div className="col" style={{textAlign:'center', alignItems: 'center'}}>
          <div className="pulse-cyan" style={{
            width: 64, height: 64, borderRadius: 18,
            background: 'rgba(155,92,255,0.18)', color:'var(--purple-3)',
            display:'flex',alignItems:'center',justifyContent:'center'
          }}>
            <Icon.clock size={28}/>
          </div>
          <div className="h-card">{T('invoice_waiting')}</div>
          <div className="dim">Complete the payment in Telegram. Credits will be added automatically.</div>
          <div className="progress-bar" style={{width: '100%'}}><div style={{width: '65%'}}/></div>
          <button className="btn btn-ghost btn-block" onClick={()=>setState('confirm')}>{T('cancel_invoice')}</button>
        </div>
      )}

      {state === 'paid' && (
        <div className="col" style={{textAlign:'center', alignItems: 'center'}}>
          <div style={{
            width: 64, height: 64, borderRadius: 18,
            background: 'rgba(46,230,166,0.18)', color:'var(--success)',
            display:'flex',alignItems:'center',justifyContent:'center'
          }}>
            <Icon.check size={32}/>
          </div>
          <div className="h-card">{T('invoice_paid')}</div>
          <div className="dim">Credits added · +3 extra spins as bonus</div>
          <button className="btn btn-primary btn-block btn-lg" onClick={onClose}>{T('ok')}</button>
        </div>
      )}

      {state === 'failed' && (
        <div className="col" style={{textAlign:'center', alignItems: 'center'}}>
          <div style={{
            width: 64, height: 64, borderRadius: 18,
            background: 'rgba(255,92,122,0.16)', color:'var(--error)',
            display:'flex',alignItems:'center',justifyContent:'center'
          }}>
            <Icon.warning size={30}/>
          </div>
          <div className="h-card">Payment was not completed</div>
          <div className="dim">{paymentError || 'Please try again.'}</div>
          <button className="btn btn-primary btn-block btn-lg" onClick={()=>setState('confirm')}>Try again</button>
          <button className="btn btn-ghost btn-block" onClick={onClose}>{T('cancel')}</button>
        </div>
      )}
    </Sheet>
  );
}

// Invoice resume screen (from invoice_reminder context)
function InvoiceScreen({ ctx }){
  const { t: T, navigate } = ctx;
  const pkg = window.RAVANA_DATA.packages.find(p => p.id === 'hot_combo');
  return (
    <div className="screen">
      <ScreenHeader title={T('invoice_resume')} onBack={()=>navigate('credits')}/>
      <AIBanner kind="campaign-invoice">
        <div className="h-card">{T('campaign_invoice_title')}</div>
        <div className="dim" style={{color:'var(--text-2)'}}>{T('campaign_invoice_sub')}</div>
      </AIBanner>
      <div className="card">
        <div className="h-card">{pkg.name}</div>
        <div className="dim" style={{marginTop: 4}}>{pkg.subline}</div>
        <div style={{display:'flex', gap: 10, marginTop: 8}}>
          <span className="chip chip-cyan"><Icon.video size={11}/> {pkg.video} min</span>
          <span className="chip chip-purple"><Icon.photo size={11}/> {pkg.photo}</span>
        </div>
      </div>
      <CostPanel items={[
        { k: 'Total', v: pkg.stars.toLocaleString() + ' ★', tone: 'gold' },
        { k: 'Status', v: 'Awaiting payment', tone: 'cyan' },
      ]}/>
      <div style={{flex:1}}/>
      <button className="btn btn-gold btn-block btn-lg" onClick={()=>navigate('credits')}>
        <Icon.telegramStar size={16}/> {T('resume_payment')}
      </button>
      <button className="btn btn-ghost btn-block" onClick={()=>navigate('credits')}>Choose another package</button>
    </div>
  );
}

// Manage subscription
function ManageSubscriptionScreen({ ctx }){
  const { t: T, navigate } = ctx;
  const [subs, setSubs] = _cr_useState(window.RAVANA_DATA.subscriptions);
  const [cancelling, setCancelling] = _cr_useState(null);

  return (
    <div className="screen">
      <ScreenHeader title={T('manage_subscription')} onBack={()=>navigate('credits')}/>

      <div className="banner-info">
        <Icon.info size={14} style={{color:'var(--cyan)', flex:'none'}}/>
        <div>{T('stripe_disabled')}. You can still cancel existing auto-renewals.</div>
      </div>

      {subs.length === 0 ? (
        <div className="empty">
          <div className="empty-art"><Icon.shield size={26}/></div>
          <div className="h-card">{T('no_active_subscriptions')}</div>
        </div>
      ) : subs.map(s => (
        <div key={s.id} className="card">
          <div className="row-between" style={{marginBottom: 8}}>
            <div className="h-card">{s.name}</div>
            {s.active ?
              <span className="chip chip-success">{T('auto_renew')}</span>
              : <span className="chip">Cancelled</span>}
          </div>
          <CostPanel items={[
            { k: 'Price', v: s.price },
            { k: T('next_payment'), v: s.active ? s.next : '—' },
          ]}/>
          {s.active && (
            <button className="btn btn-ghost btn-block" style={{marginTop: 10}} onClick={()=>setCancelling(s.id)}>
              <Icon.x size={14}/> {T('cancel_subscription')}
            </button>
          )}
        </div>
      ))}

      <Sheet open={cancelling != null} onClose={()=>setCancelling(null)} dialog>
        <div className="col" style={{textAlign:'center', alignItems:'center'}}>
          <div className="empty-art" style={{margin:0}}><Icon.warning size={26}/></div>
          <div className="h-card">{T('cancel_subscription')}?</div>
          <div className="mute" style={{fontSize: 12}}>You'll keep access until next payment date.</div>
          <div style={{display:'flex', gap: 8, width:'100%'}}>
            <button className="btn btn-ghost" style={{flex: 1}} onClick={()=>setCancelling(null)}>{T('back')}</button>
            <button className="btn btn-primary" style={{flex: 1}} onClick={()=>{
              setSubs(s => s.map(x => x.id === cancelling ? {...x, active: false} : x));
              setCancelling(null);
            }}>{T('confirm')}</button>
          </div>
        </div>
      </Sheet>
    </div>
  );
}

window.CreditsScreen = CreditsScreen;
window.InvoiceScreen = InvoiceScreen;
window.ManageSubscriptionScreen = ManageSubscriptionScreen;
