// screens-misc.jsx — Referrals + History + Profile/Settings
const { useState: _ms_useState, useEffect: _ms_useEffect } = React;

// ============================================================
// Referrals
// ============================================================
function ReferralsScreen({ ctx }){
  const { t: T, premium, navigate, campaign, miniContext } = ctx;
  const ref = window.RAVANA_DATA.referral_user;
  const [copied, setCopied] = _ms_useState(false);
  const [view, setView] = _ms_useState(
    campaign === 'referral_challenge' || miniContext === 'referral_challenge' ? 'challenge' : 'overview'
  );

  const copy = () => {
    setCopied(true);
    if (navigator.clipboard) navigator.clipboard.writeText(ref.invite_link).catch(()=>{});
    setTimeout(()=>setCopied(false), 1600);
  };

  return (
    <div className="screen">
      <ScreenHeader title={T('referrals_title')} subtitle={T('referrals_sub')}
        right={<HelpButton topic="referrals" lang={ctx.lang}/>}/>

      {/* Tab switcher */}
      <div className="row" style={{gap: 6, background: 'var(--bg-panel)', padding: 4, borderRadius: 12,
          border: '1px solid rgba(155,92,255,0.1)'}}>
        <button onClick={()=>setView('overview')} style={{
          flex: 1, padding: '8px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
          border: 0, cursor: 'pointer', fontFamily:'inherit',
          background: view === 'overview' ? 'rgba(155,92,255,0.2)' : 'transparent',
          color: view === 'overview' ? 'var(--text-1)' : 'var(--text-3)',
        }}>Overview</button>
        <button onClick={()=>setView('challenge')} style={{
          flex: 1, padding: '8px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
          border: 0, cursor: 'pointer', fontFamily:'inherit',
          background: view === 'challenge' ? 'rgba(155,92,255,0.2)' : 'transparent',
          color: view === 'challenge' ? 'var(--text-1)' : 'var(--text-3)',
        }}>{T('challenge')} <span className="chip chip-error" style={{marginLeft:4, padding:'1px 5px',fontSize:9}}>LIVE</span></button>
      </div>

      {view === 'overview' && <ReferralOverview referral={ref} copy={copy} copied={copied} ctx={ctx} premium={premium}/>}
      {view === 'challenge' && <ReferralChallenge ctx={ctx}/>}
    </div>
  );
}

function ReferralOverview({ referral, copy, copied, ctx, premium }){
  const { t: T } = ctx;
  return (
    <>
      {/* Referral Premium status */}
      {premium === 'ref_premium' && (
        <div className="card card-premium">
          <div className="row" style={{gap: 12}}>
            <div style={{width: 40, height: 40, borderRadius: 12,
                background: 'rgba(155,92,255,0.24)', color: 'var(--purple-3)',
                display:'flex',alignItems:'center',justifyContent:'center'}}>
              <Icon.crown size={20}/>
            </div>
            <div>
              <div className="h-card">{T('referral_premium_active')}</div>
              <div className="dim" style={{marginTop: 2}}>{T('referral_premium_sub')}</div>
            </div>
          </div>
        </div>
      )}

      {/* Invite link */}
      <div className="card">
        <div className="dim" style={{fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 8}}>{T('your_link')}</div>
        <div className="row" style={{gap: 8}}>
          <div className="input" style={{flex: 1, fontFamily: 'var(--font-mono)', fontSize: 11, padding: '10px 12px', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{referral.invite_link}</div>
          <button className="btn btn-secondary btn-sm" onClick={copy}>
            {copied ? <><Icon.check size={14}/> {T('copied')}</> : <><Icon.copy size={14}/> {T('copy')}</>}
          </button>
        </div>
        <button className="btn btn-primary btn-block" style={{marginTop: 10}}>
          <Icon.share size={16}/> {T('share')}
        </button>
      </div>

      {/* Rewards explanation */}
      <div className="col">
        <div className="card" style={{padding: 12}}>
          <div className="row" style={{gap: 12}}>
            <div style={{width: 32, height: 32, borderRadius: 10,
                background: 'rgba(34,211,238,0.14)', color: 'var(--cyan)',
                display:'flex',alignItems:'center',justifyContent:'center'}}>
              <Icon.user size={16}/>
            </div>
            <div style={{flex: 1, fontSize: 12}}>{T('reward_per_friend')}</div>
          </div>
        </div>
        <div className="card" style={{padding: 12}}>
          <div className="row" style={{gap: 12}}>
            <div style={{width: 32, height: 32, borderRadius: 10,
                background: 'rgba(246,200,95,0.14)', color: 'var(--gold)',
                display:'flex',alignItems:'center',justifyContent:'center'}}>
              <Icon.crown size={16}/>
            </div>
            <div style={{flex: 1, fontSize: 12}}>{T('reward_per_paid')}</div>
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="section-title"><h3>Your stats</h3></div>
      <div className="grid-2">
        <StatCard label={T('invited')} value={referral.invited} icon={<Icon.user size={14}/>} color="cyan"/>
        <StatCard label={T('active_friends')} value={referral.active} icon={<Icon.users size={14}/>} color="success"/>
        <StatCard label={T('earned')} value={`${referral.earned_video}v · ${referral.earned_photo}p`} icon={<Icon.gift size={14}/>} color="gold"/>
        <StatCard label={T('pending')} value={referral.pending} icon={<Icon.clock size={14}/>} color="purple"/>
      </div>
    </>
  );
}

function StatCard({ label, value, icon, color }){
  const colors = {
    cyan: { bg: 'rgba(34,211,238,0.12)', col: 'var(--cyan)' },
    purple: { bg: 'rgba(155,92,255,0.14)', col: 'var(--purple-3)' },
    gold: { bg: 'rgba(246,200,95,0.14)', col: 'var(--gold)' },
    success: { bg: 'rgba(46,230,166,0.12)', col: 'var(--success)' },
  };
  const c = colors[color] || colors.purple;
  return (
    <div className="card" style={{padding: 12}}>
      <div className="row" style={{gap: 8, marginBottom: 6}}>
        <div style={{width: 26, height: 26, borderRadius: 8, background: c.bg, color: c.col,
            display:'flex', alignItems:'center', justifyContent:'center'}}>{icon}</div>
        <div className="dim" style={{fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em'}}>{label}</div>
      </div>
      <div style={{fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, color: 'var(--text-1)'}}>{value}</div>
    </div>
  );
}

function ReferralChallenge({ ctx }){
  const { t: T } = ctx;
  const lb = window.RAVANA_DATA.leaderboard;
  const tiers = window.RAVANA_DATA.prize_tiers;
  return (
    <>
      <div className="card card-gold">
        <div className="row-between" style={{marginBottom: 8}}>
          <div className="row" style={{gap: 8}}>
            <Icon.trophy size={16} style={{color:'var(--gold)'}}/>
            <span className="chip chip-error">{T('challenge_active')}</span>
          </div>
          <div className="dim" style={{fontSize: 11}}>{T('challenge_ends')}: <span style={{color:'var(--gold)'}}>3d 14h</span></div>
        </div>
        <div className="h-card">May invite race</div>
        <div className="dim" style={{marginTop: 4}}>Top 50 referrers split 1500+ video minutes</div>
      </div>

      {/* Your rank */}
      <div className="card">
        <div className="row-between">
          <div>
            <div className="dim" style={{fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em'}}>{T('challenge_rank')}</div>
            <div className="row" style={{gap: 8, marginTop: 4}}>
              <span style={{fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 600}}>#47</span>
              <span className="chip chip-success">+12</span>
            </div>
          </div>
          <div style={{textAlign: 'right'}}>
            <div className="dim" style={{fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em'}}>Next tier in</div>
            <div className="row" style={{gap: 4, marginTop: 4, justifyContent: 'flex-end'}}>
              <Icon.user size={14} style={{color:'var(--cyan)'}}/>
              <span style={{fontFamily: 'var(--font-display)', fontWeight: 600}}>3 more</span>
            </div>
          </div>
        </div>
        <div className="progress-bar" style={{marginTop: 12}}><div style={{width: '64%'}}/></div>
      </div>

      {/* Prize tiers */}
      <div className="section-title"><h3>{T('prize_tiers')}</h3></div>
      <div className="col">
        {tiers.map((tier, i) => (
          <div className="card" key={i} style={{padding: '10px 12px'}}>
            <div className="row-between">
              <div className="row" style={{gap: 10}}>
                <div style={{
                  width: 42, minWidth: 42, height: 30, borderRadius: 8,
                  background: i === 0 ? 'rgba(246,200,95,0.18)' :
                              i === 1 ? 'rgba(192,200,218,0.15)' :
                              i === 2 ? 'rgba(224,138,75,0.16)' :
                              'rgba(155,92,255,0.12)',
                  color: i === 0 ? 'var(--gold)' : i === 1 ? '#C0C8DA' : i === 2 ? '#E08A4B' : 'var(--purple-3)',
                  display:'flex',alignItems:'center',justifyContent:'center', whiteSpace: 'nowrap',
                  fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 700
                }}>#{tier.rank}</div>
                <div style={{fontSize: 12}}>{tier.reward}</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Leaderboard */}
      <div className="section-title"><h3>{T('leaderboard')}</h3></div>
      <div className="col">
        {lb.map((row, i) => (
          <div key={i} className={"lb-row " + (row.isMe ? 'me' : '')}>
            <div className={"lb-rank " + (row.rank === 1 ? 'gold' : row.rank === 2 ? 'silver' : row.rank === 3 ? 'bronze' : '')}>
              {row.isMe ? '#' + row.displayRank : '#' + row.rank}
            </div>
            <div>
              <div className="lb-name">{row.isMe ? 'You' : row.name}</div>
              <div className="lb-meta">{row.invited} invited · {row.paid} paid</div>
            </div>
            <div className="lb-score">{row.paid * 50 + row.invited}</div>
          </div>
        ))}
      </div>

      <button className="btn btn-primary btn-block btn-lg">
        <Icon.share size={16}/> {T('share')}
      </button>
    </>
  );
}

// ============================================================
// History
// ============================================================
function HistoryScreen({ ctx }){
  const { t: T, navigate } = ctx;
  const items = window.RAVANA_DATA.history;
  const [filter, setFilter] = _ms_useState('all');

  const filtered = items.filter(item => {
    if (filter === 'all') return true;
    if (filter === 'face_swap') return item.type === 'face_swap';
    if (filter === 'multiface') return item.type === 'multiface';
    if (filter === 'image_gen') return item.type === 'image_gen';
    if (filter === 'photo') return item.media === 'photo';
    if (filter === 'video') return item.media === 'video';
    return true;
  });

  return (
    <div className="screen">
      <ScreenHeader title={T('history_title')} subtitle={T('history_sub')}
        right={<HelpButton topic="history" lang={ctx.lang}/>}/>

      <div className="filter-row">
        {[
          ['all', T('filter_all')],
          ['face_swap', T('face_swap')],
          ['multiface', T('multiface')],
          ['image_gen', T('image_gen')],
          ['photo', T('photo')],
          ['video', T('video')],
        ].map(([k, label]) => (
          <button key={k} className={"filter-chip " + (filter === k ? 'active' : '')} onClick={()=>setFilter(k)}>
            {label}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="empty">
          <div className="empty-art"><Icon.history size={26}/></div>
          <div className="h-card">{T('empty_history')}</div>
          <div className="dim" style={{marginTop:4}}>{T('empty_history_sub')}</div>
          <button className="btn btn-primary btn-sm" style={{marginTop: 14}} onClick={()=>navigate('create')}>{T('create_another')}</button>
        </div>
      ) : (
        <div className="col">
          {filtered.map(item => <HistoryRow key={item.id} item={item} ctx={ctx}/>)}
        </div>
      )}
    </div>
  );
}

function HistoryRow({ item, ctx }){
  const { t: T, navigate } = ctx;
  const statusChip = item.status === 'ready' ?
    <span className="chip chip-success">● {T('status_ready')}</span> :
    item.status === 'processing' ?
      <span className="chip chip-cyan">● {T('status_processing')}</span> :
    item.status === 'failed' ?
      <span className="chip chip-error">{T('status_failed')}</span> :
      <span className="chip">{item.status}</span>;

  const TypeIcon = item.type === 'multiface' ? Icon.multiface : item.type === 'image_gen' ? Icon.wand : Icon.face;

  return (
    <div className="history-card">
      <div className="history-thumb">
        <div className="placeholder-art" style={{position:'static', height:'100%', borderRadius: 12}}>
          <TypeIcon size={20}/>
        </div>
        {item.media === 'video' && (
          <div className="badge-ix"><Icon.video size={10}/></div>
        )}
      </div>
      <div className="history-body">
        <div className="row" style={{gap: 6}}>
          <div className="history-title">{item.name}</div>
        </div>
        <div className="row" style={{gap: 8, alignItems:'center'}}>
          {statusChip}
          {item.duration && <span className="history-meta">{item.duration}</span>}
          {item.enhanced && <span className="chip chip-purple" style={{padding:'1px 6px', fontSize: 9}}>HQ</span>}
        </div>
        <div className="history-meta">{item.time} · {item.cost > 0 ? item.cost + (item.media === 'video' ? ' min' : ' cr') : 'no charge'}</div>
      </div>
      {item.status === 'ready' ?
        <button className="history-action" title={T('download')}><Icon.download size={14}/></button>
        : item.status === 'failed' ?
        <button className="history-action" style={{color:'var(--error)', background:'rgba(255,92,122,0.1)'}}><Icon.refresh size={14}/></button>
        :
        <button className="history-action pulse-cyan" style={{color:'var(--cyan)', background: 'rgba(34,211,238,0.1)'}}>
          <Icon.eye size={14}/>
        </button>
      }
    </div>
  );
}

// ============================================================
// Profile / Settings
// ============================================================
function ProfileScreen({ ctx }){
  const { t: T, navigate, lang, premium, setLang, user } = ctx;
  const displayName = (user && (user.name || user.username)) || 'Mira';
  const username = user && user.username ? `@${user.username}` : '@miraq';
  const tgId = user && user.id ? user.id : 4218;
  return (
    <div className="screen">
      <ScreenHeader title={T('profile')} onBack={()=>navigate('home')}/>

      <div className="card" style={{padding: 14}}>
        <div className="row" style={{gap: 14}}>
          <div style={{
            width: 56, height: 56, borderRadius: 16,
            background: 'radial-gradient(70% 70% at 40% 30%, rgba(155,92,255,0.4), transparent), var(--surf-dark)',
            border: '1px solid rgba(155,92,255,0.32)',
            display:'flex', alignItems:'center', justifyContent:'center', color: 'var(--purple-3)'
          }}>
            <Icon.user size={26}/>
          </div>
          <div style={{flex: 1, minWidth: 0}}>
            <div className="h-card">{displayName}</div>
            <div className="dim">{username} · TG ID {tgId}</div>
            <div style={{marginTop: 6}}><PremiumChip kind={premium} lang={lang}/></div>
          </div>
        </div>
      </div>

      <div className="section-title"><h3>{T('settings')}</h3></div>
      <div className="col">
        <SettingsRow icon={<Icon.language size={16}/>} label={T('language')}
          value={lang === 'ru' ? 'Русский' : 'English'}
          onClick={()=>setLang(lang === 'ru' ? 'en' : 'ru')}/>
        <SettingsRow icon={<Icon.crown size={16}/>} label={T('manage_subscription')} onClick={()=>navigate('manage_subscription')}/>
        <SettingsRow icon={<Icon.helpCircle size={16}/>} label={T('support')} onClick={()=>navigate('support')}/>
        <SettingsRow icon={<Icon.book size={16}/>} label={T('manual')} onClick={()=>navigate('manual')}/>
        <SettingsRow icon={<Icon.shield size={16}/>} label={T('terms')} onClick={()=>navigate('terms')}/>
        <SettingsRow icon={<Icon.externalLink size={16}/>} label="Open in Telegram" badge="Web"/>
      </div>

      <div className="dim" style={{textAlign:'center', fontSize: 11, marginTop: 16}}>
        {T('version')} 1.0.0 · Build 2026.05.27
      </div>
    </div>
  );
}

function SettingsRow({ icon, label, value, badge, onClick }){
  return (
    <button onClick={onClick} className="card" style={{
      textAlign:'left', color:'inherit', cursor: onClick ? 'pointer' : 'default',
      padding: '12px 14px',
      display:'flex', alignItems:'center', gap: 12,
    }}>
      <div style={{width: 28, height: 28, borderRadius: 8,
          background: 'rgba(155,92,255,0.1)', color: 'var(--text-2)',
          display:'flex',alignItems:'center',justifyContent:'center'}}>{icon}</div>
      <div style={{flex: 1, fontSize: 13}}>{label}</div>
      {value && <span className="dim" style={{fontSize: 12}}>{value}</span>}
      {badge && <span className="chip" style={{fontSize: 10}}>{badge}</span>}
      {onClick && <Icon.chevronRight size={16}/>}
    </button>
  );
}

// Simple support / manual / terms screens
function SupportScreen({ ctx }){
  const { t: T, navigate } = ctx;
  return (
    <div className="screen">
      <ScreenHeader title={T('support')} onBack={()=>navigate('profile')}/>
      <div className="empty">
        <div className="empty-art"><Icon.mail size={26}/></div>
        <div className="h-card">Need help?</div>
        <div className="dim" style={{maxWidth: 240, margin: '8px auto'}}>
          Our team usually replies within a few hours.
        </div>
        <button className="btn btn-primary btn-sm" style={{marginTop: 14}}>
          <Icon.externalLink size={14}/> Open support chat
        </button>
      </div>
    </div>
  );
}

function ManualScreen({ ctx }){
  const { t: T, navigate } = ctx;
  return (
    <div className="screen">
      <ScreenHeader title={T('manual')} onBack={()=>navigate('profile')}/>
      <div className="col">
        {[
          { t: 'Face Swap', d: 'Upload a clear source face, then your target photo or video. Best with front-facing shots.', i: <Icon.face size={16}/> },
          { t: 'MultiFace', d: 'Premium feature. Detects every face in your media and lets you replace each one individually.', i: <Icon.multiface size={16}/> },
          { t: 'Image Gen', d: 'Describe what you want and pick an aspect ratio. Costs 1 photo credit per generation.', i: <Icon.wand size={16}/> },
          { t: 'Fortune', d: 'Spin daily for rewards. Earn extra spins via referrals, purchases, and streaks.', i: <Icon.sparkles size={16}/> },
          { t: 'Limits', d: 'Free users: videos under 60 seconds, Telegram-size files. Premium removes both.', i: <Icon.info size={16}/> },
        ].map((it, i) => (
          <div key={i} className="card">
            <div className="row" style={{gap: 10, marginBottom: 4}}>
              <div style={{width: 28, height: 28, borderRadius: 8, background: 'rgba(155,92,255,0.16)',
                  color: 'var(--purple-3)', display:'flex',alignItems:'center',justifyContent:'center'}}>{it.i}</div>
              <div className="h-card">{it.t}</div>
            </div>
            <div className="dim" style={{fontSize: 12, lineHeight: 1.5, marginLeft: 38}}>{it.d}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function TermsScreen({ ctx }){
  const { t: T, navigate } = ctx;
  return (
    <div className="screen">
      <ScreenHeader title={T('terms')} onBack={()=>navigate('profile')}/>
      <div className="card" style={{lineHeight: 1.55, fontSize: 12, color: 'var(--text-2)'}}>
        <p style={{margin: '0 0 10px'}}><strong style={{color: 'var(--text-1)'}}>18+ acknowledgement.</strong> By using Ravana Swap you confirm you are at least 18 years old and consent to the processing of biometric data for face-swap operations.</p>
        <p style={{margin: '0 0 10px'}}>You retain ownership of any source/target media you upload. We process it temporarily for your selected action.</p>
        <p style={{margin: '0 0 10px'}}>Purchases are non-refundable unless required by Telegram or local law. New Stripe subscriptions are disabled; existing auto-renewals can be cancelled in Manage subscription.</p>
        <p style={{margin: 0}}>Do not use Ravana Swap to deceive, harass, or harm others. Violation results in immediate access revocation.</p>
      </div>
    </div>
  );
}

window.ReferralsScreen = ReferralsScreen;
window.HistoryScreen = HistoryScreen;
window.ProfileScreen = ProfileScreen;
window.SupportScreen = SupportScreen;
window.ManualScreen = ManualScreen;
window.TermsScreen = TermsScreen;
