// ============================================================
// SocialPulse — Credits Page (API-connected)
// ============================================================

function CreditsPage() {
  const history = useApi(() => spStats.creditHistory(200), []);
  const pricing = useApi(() => spApi('/api/config/pricing'), []);
  const user = spGetUser() || {};

  // Build the pricing card rows from the live config so this card can never
  // drift from the backend formula again (it used to be hardcoded and stale).
  const pricingRows = (() => {
    const cfg = pricing.data;
    if (!cfg) return null;
    const rows = [];
    for (const t of (cfg.fb?.tiers || []).slice(0, 3)) {
      rows.push([`FB 更新 ≤${t.maxDays} 天`, `${t.min}~${t.max}`]);
    }
    const ig = cfg.ig;
    if (ig) {
      const igMin = Math.max(1, Math.ceil(ig.defaultCount * ig.costPerPostUsdMin * cfg.costMultiplier / cfg.costPerPoint));
      const igMax = Math.max(1, Math.ceil(ig.defaultCount * ig.costPerPostUsdMax * cfg.costMultiplier / cfg.costPerPoint));
      rows.push([`IG 更新 ${ig.defaultCount} 篇`, `${igMin}~${igMax}`]);
    }
    for (const ex of (cfg.report?.examples || []).filter(e => [20, 100].includes(e.postCount))) {
      rows.push([`AI 報告 ≤${ex.postCount} 篇`, `${ex.min}~${ex.max}`]);
    }
    return rows;
  })();

  const total = user.monthly_credits || 10;
  const used = user.credits_used || 0;
  const left = total - used;
  const pct = Math.round((used/total)*100);
  const isLow = left <= 5;

  // Aggregate transactions: split pending (reserved, not yet charged) from
  // settled usage/refunds. Credits are negative for spend, positive for refund.
  const txs = history.data || [];
  const pendingTxs = txs.filter(t => t.type === 'pending');
  const settledTxs = txs.filter(t => t.type !== 'pending');
  const allTimeUsed = settledTxs.reduce((s,t) => t.credits < 0 ? s + Math.abs(t.credits) : s, 0);
  const allTimeGained = settledTxs.reduce((s,t) => t.credits > 0 ? s + t.credits : s, 0);
  const pendingReserved = pendingTxs.reduce((s,t) => s + (Number(t.reserved_credits) || 0), 0);

  return (
    <div>
      <h2 style={{fontSize:22,fontWeight:800,letterSpacing:'-.02em',marginBottom:20}}>點數與使用</h2>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:16,marginBottom:24}}>
        <div style={{background:'var(--panel)',border:'1px solid var(--line)',borderRadius:'var(--r-xl)',padding:'24px 28px',gridRow:'1/3',display:'flex',flexDirection:'column'}}>
          <div style={{fontFamily:'var(--font-mono)',fontSize:11,color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.12em',marginBottom:16}}>本月額度</div>
          <div style={{display:'flex',alignItems:'center',justifyContent:'center',flex:1,padding:'8px 0'}}>
            <div style={{position:'relative',width:140,height:140}}>
              <svg width="140" height="140" viewBox="0 0 140 140" style={{transform:'rotate(-90deg)'}}>
                <circle cx="70" cy="70" r="58" fill="none" stroke="var(--line)" strokeWidth="8"/>
                <circle cx="70" cy="70" r="58" fill="none" stroke={isLow?'var(--amber)':'var(--indigo)'} strokeWidth="8" strokeLinecap="round"
                  strokeDasharray={`${pct*3.64} ${364-pct*3.64}`}/>
              </svg>
              <div style={{position:'absolute',inset:0,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center'}}>
                <div style={{fontSize:32,fontWeight:800,letterSpacing:'-.02em',color:isLow?'var(--amber)':'var(--text)'}}>{used}</div>
                <div style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text3)'}}>/ {total} 已使用</div>
              </div>
            </div>
          </div>
          <div style={{display:'flex',justifyContent:'space-between',fontSize:12,color:'var(--text2)',marginTop:12,padding:'12px 0 0',borderTop:'1px solid var(--line)'}}>
            <span>方案: {user.plan || 'free'}</span>
            <span style={{fontFamily:'var(--font-mono)',fontWeight:600,color:isLow?'var(--amber)':'var(--lime)'}}>{left} 剩餘</span>
          </div>
        </div>

        <div style={{background:'var(--panel)',border:'1px solid var(--line)',borderRadius:'var(--r-xl)',padding:'20px 24px'}}>
          <div style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.1em',marginBottom:10}}>本期已用</div>
          <div style={{fontSize:28,fontWeight:800,letterSpacing:'-.02em',marginBottom:4}}>{used}</div>
          <div style={{fontSize:12,color:'var(--text2)'}}>點已消耗{pendingReserved > 0 && <span style={{color:'var(--amber)',marginLeft:8}}>⌛ 預留 {pendingReserved} 點</span>}</div>
          <div style={{marginTop:12,height:4,background:'var(--line)',borderRadius:2,overflow:'hidden'}}>
            <div style={{height:'100%',background:'var(--indigo)',borderRadius:2,width:`${pct}%`,transition:'width .3s'}}/>
          </div>
          <div style={{marginTop:12,paddingTop:10,borderTop:'1px solid var(--line)',display:'flex',justifyContent:'space-between',gap:10,fontSize:11,fontFamily:'var(--font-mono)'}}>
            <div>
              <div style={{color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.08em'}}>累計消耗</div>
              <div style={{color:'var(--red)',fontWeight:700,fontSize:13}}>−{allTimeUsed}</div>
            </div>
            <div style={{textAlign:'right'}}>
              <div style={{color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.08em'}}>累計入帳</div>
              <div style={{color:'var(--lime)',fontWeight:700,fontSize:13}}>+{allTimeGained}</div>
            </div>
          </div>
        </div>

        <div style={{background:'var(--panel)',border:'1px solid var(--line)',borderRadius:'var(--r-xl)',padding:'20px 24px'}}>
          <div style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.1em',marginBottom:12}}>Credit pricing</div>
          {!pricingRows ? (
            <div style={{fontSize:12,color:'var(--text3)'}}>載入中…</div>
          ) : (
            <div style={{display:'flex',flexDirection:'column',gap:6,fontSize:12}}>
              {pricingRows.map(([l,c],i,arr) => (
                <div key={i} style={{display:'flex',justifyContent:'space-between',padding:'4px 0',borderBottom:i<arr.length-1?'1px dashed var(--line)':'none'}}>
                  <span style={{color:'var(--text2)'}}>{l}</span>
                  <span style={{fontFamily:'var(--font-mono)',fontWeight:600}}>{c} 點</span>
                </div>
              ))}
              <div style={{fontSize:10,color:'var(--text3)',marginTop:4}}>區間為預估，實際依用量計</div>
            </div>
          )}
        </div>

        <div style={{background:'var(--panel)',border:'1px solid var(--line)',borderRadius:'var(--r-xl)',padding:'20px 24px'}}>
          <div style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.1em',marginBottom:10}}>Current plan</div>
          <div style={{fontSize:22,fontWeight:800,marginBottom:4}}>{(user.plan||'free').toUpperCase()}</div>
          <div style={{fontSize:12,color:'var(--text2)',marginBottom:12}}>{user.max_brands||1} 品牌 · {total} 點 / 月</div>
          <div style={{fontSize:11,color:'var(--text3)',fontFamily:'var(--font-mono)',lineHeight:1.6,padding:'8px 10px',background:'var(--panel2)',borderRadius:'var(--r-md)'}}>
            🎁 點數可用於爬取與 AI 報告生成（報告約 2~5 點/份）
          </div>
        </div>
      </div>

      <div style={{background:'var(--panel)',border:'1px solid var(--line)',borderRadius:'var(--r-xl)',overflow:'hidden'}}>
        <div style={{padding:'16px 22px',borderBottom:'1px solid var(--line)',fontSize:15,fontWeight:700}}>交易紀錄</div>
        {history.loading ? <LoadingState/> :
         history.error ? <ErrorState error={history.error} onRetry={history.reload}/> :
         (history.data||[]).length === 0 ? <EmptyState title="尚無交易" desc="點數使用紀錄會顯示在這"/> :
        <table style={{width:'100%',borderCollapse:'collapse'}}>
          <thead>
            <tr>
              {['日期','類型','說明','點數'].map(h => (
                <th key={h} style={{textAlign:h==='點數'?'right':'left',padding:'10px 16px',fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text3)',textTransform:'uppercase',letterSpacing:'.1em',fontWeight:600,borderBottom:'1px solid var(--line)',background:'var(--bg2)'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {(history.data||[]).map((t,i,arr) => {
              const isPending = t.type === 'pending';
              const n = Number(t.credits ?? t.amount ?? 0);
              const reserved = Number(t.reserved_credits || 0);
              const displayN = isPending ? reserved : n;
              const isGain = !isPending && n > 0;
              const text = isPending
                ? `⌛ ~${reserved}`
                : ((n > 0 ? '+' : n < 0 ? '−' : '') + Math.abs(n));
              const typeBg = isPending ? 'var(--amber-soft)' : 'var(--indigo-soft)';
              const typeColor = isPending ? 'var(--amber)' : 'var(--indigo2)';
              const typeLabel = isPending ? '計算中' : (t.type || 'use');
              const amountColor = isPending ? 'var(--amber)' : isGain ? 'var(--lime)' : 'var(--red)';
              const rowBg = isPending ? 'rgba(245,179,36,.04)' : 'transparent';
              return (
              <tr key={t.id||i} style={{background:rowBg}}>
                <td style={{padding:'11px 16px',borderBottom:i===arr.length-1?'none':'1px solid var(--line)',fontFamily:'var(--font-mono)',fontSize:12,color:'var(--text3)'}}>{t.created_at?.slice(0,16).replace('T',' ')}</td>
                <td style={{padding:'11px 16px',borderBottom:i===arr.length-1?'none':'1px solid var(--line)'}}>
                  <span style={{fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,padding:'2px 7px',borderRadius:'var(--r-xs)',background:typeBg,color:typeColor,textTransform:'uppercase',letterSpacing:'.06em'}}>{typeLabel}</span>
                </td>
                <td style={{padding:'11px 16px',borderBottom:i===arr.length-1?'none':'1px solid var(--line)',fontSize:13,color:isPending?'var(--text2)':'var(--text)',fontStyle:isPending?'italic':'normal'}}>{t.description||t.reason||'—'}</td>
                <td style={{padding:'11px 16px',borderBottom:i===arr.length-1?'none':'1px solid var(--line)',textAlign:'right',fontFamily:'var(--font-mono)',fontWeight:600,color:amountColor}}>{text}</td>
              </tr>
            );})}
          </tbody>
        </table>}
      </div>
    </div>
  );
}

Object.assign(window, { CreditsPage });
