// v-rewards.jsx — Rewards / Growth Progress + Campaigns list

function MissionCard({ m, app }) {
  const e = ESTATES.find(x=>x.name===m.area);
  const pct = Math.round(m.progress/m.goal*100);
  const done = m.progress>=m.goal;
  return (
    <div style={{ background:'var(--bg-surface)', border:'1px solid var(--soft-line)', borderRadius:14, padding:'15px 16px', display:'flex', flexDirection:'column', gap:12, boxShadow:'var(--shadow-sm)' }}>
      <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:10 }}>
        <div style={{ display:'flex', gap:11 }}>
          <div style={{ width:36, height:36, borderRadius:10, background: done?'rgba(46,139,78,0.14)':'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
            {done ? <I.check c="#247a41" s={18}/> : <I.target c="var(--brand-orange)" s={18}/>}
          </div>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:14, color:'var(--fg-primary)', lineHeight:1.25 }}>{m.text}</div>
            <div style={{ display:'flex', alignItems:'center', gap:7, marginTop:5 }}>
              {m.live && <Pill tone="purple" dot>Live now</Pill>}
              <span style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}><I.pin c="var(--warm-stone)" s={11}/> {m.area}</span>
            </div>
          </div>
        </div>
        <Pill tone="orange" icon={<I.zap c="#c0500f" s={11} f/>}>+{m.xp} XP</Pill>
      </div>
      <div>
        <div style={{ display:'flex', justifyContent:'space-between', marginBottom:6 }}>
          <span style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)' }}>{done?'Complete':'Progress'}</span>
          <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:12, color:'var(--fg-primary)' }}>{m.progress}{m.unit||''} / {m.goal}{m.unit||''}</span>
        </div>
        <Bar pct={pct} color={done?'#2E8B4E':'var(--brand-orange)'} h={7}/>
      </div>
      {!done && <Btn kind="white" size="sm" full onClick={()=> e ? app.openBuilder(e.id) : app.nav('map')} icon={<I.rocket c="var(--fg-primary)" s={14}/>}>Work on this</Btn>}
    </div>
  );
}

function RewardsScreen({ app }) {
  const xpPct = Math.round(VENDOR.xp/VENDOR.xpToNext*100);
  return (
    <div>
      <PageHead eyebrow="Rewards · Growth Progress" title="Grow your territory"
        sub="Complete missions, expand influence across Milton Keynes and climb the local leaderboard."
        right={<Pill tone="orange" icon={<I.flame c="#c0500f" s={14} f/>} style={{ fontSize:13, padding:'7px 13px' }}>{`${VENDOR.streak}-week streak`}</Pill>}/>

      {/* level hero */}
      <Card pad={0} style={{ overflow:'hidden', marginBottom:16 }}>
        <div style={{ display:'flex', alignItems:'stretch' }}>
          <div style={{ flex:1, padding:'22px 26px', background:'linear-gradient(120deg,#1B120D 0%,#3A2418 100%)', color:'var(--dust-cream)', display:'flex', alignItems:'center', gap:24 }}>
            <div style={{ position:'relative', flexShrink:0 }}>
              <Ring pct={xpPct} size={108} stroke={10} color="var(--sun-orange)" track="rgba(255,255,255,0.12)">
                <div style={{ textAlign:'center' }}>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:32, color:'#fff', lineHeight:1 }}>{VENDOR.level}</div>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:9, letterSpacing:'0.14em', color:'#E9B97A' }}>LEVEL</div>
                </div>
              </Ring>
            </div>
            <div style={{ flex:1 }}>
              <Eyebrow color="#E9B97A" style={{ marginBottom:7 }}>Growth Level 7 · Trailblazer</Eyebrow>
              <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:24, color:'#fff', marginBottom:5 }}>{VENDOR.name}</div>
              <div style={{ fontFamily:'var(--font-body)', fontSize:13, color:'#C9B6A6', marginBottom:13 }}>{(VENDOR.xpToNext-VENDOR.xp).toLocaleString()} XP to Level 8 · {VENDOR.cuisine}</div>
              <div style={{ maxWidth:420 }}>
                <Bar pct={xpPct} color="linear-gradient(90deg,#F28C1B,#D85A14)" h={9} track="rgba(255,255,255,0.13)"/>
                <div style={{ display:'flex', justifyContent:'space-between', marginTop:6 }}>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'#9F8979' }}>{VENDOR.xp.toLocaleString()} XP</span>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'#9F8979' }}>{VENDOR.xpToNext.toLocaleString()} XP</span>
                </div>
              </div>
            </div>
          </div>
          <div style={{ width:280, flexShrink:0, padding:'20px 22px', display:'flex', flexDirection:'column', justifyContent:'center', gap:14 }}>
            {[['Territory influence', VENDOR.influence+'%', I.target],['Estates active', '13 / 17', I.map],['Campaigns won', '34', I.trophy]].map(([l,v,Ic])=>(
              <div key={l} style={{ display:'flex', alignItems:'center', gap:12 }}>
                <div style={{ width:38, height:38, borderRadius:11, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Ic c="var(--brand-orange)" s={18}/></div>
                <div>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:19, color:'var(--fg-primary)', lineHeight:1 }}>{v}</div>
                  <div style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)', marginTop:2 }}>{l}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </Card>

      <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:16, marginBottom:16 }}>
        {/* missions */}
        <div>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12 }}>
            <Eyebrow><I.target c="var(--brand-orange)" s={13}/> &nbsp;Weekly growth missions</Eyebrow>
            <span style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)' }}>Resets in 3 days</span>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:11 }}>
            {MISSIONS.map(m=> <MissionCard key={m.id} m={m} app={app}/>)}
          </div>
        </div>

        {/* territory tiers */}
        <div>
          <Eyebrow style={{ marginBottom:12 }}><I.map c="var(--brand-orange)" s={13}/> &nbsp;Territory influence</Eyebrow>
          <Card>
            {TERRITORY_TIERS.map((t,i)=>(
              <div key={t.id} style={{ marginBottom: i<TERRITORY_TIERS.length-1?14:0 }}>
                <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
                  <span style={{ width:11, height:11, borderRadius:4, background:t.color }}/>
                  <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13.5, color:'var(--fg-primary)', flex:1 }}>{t.name}</span>
                  <span style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:14, color:'var(--fg-primary)' }}>{t.count}</span>
                  <span style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>estates</span>
                </div>
                <Bar pct={t.count/17*100} color={t.color} h={7}/>
              </div>
            ))}
            <div style={{ marginTop:15, paddingTop:14, borderTop:'1px solid var(--soft-line)' }}>
              <div style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)', lineHeight:1.5 }}>Push a <strong style={{ color:'var(--fg-primary)', fontFamily:'var(--font-display)' }}>Warming</strong> estate to <strong style={{ color:'var(--fg-primary)', fontFamily:'var(--font-display)' }}>Active</strong> to level up faster.</div>
              <Btn kind="white" full size="sm" style={{ marginTop:11 }} onClick={()=>app.nav('map')} icon={<I.map c="var(--fg-primary)" s={14}/>}>Open territory map</Btn>
            </div>
          </Card>
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:16 }}>
        {/* badges */}
        <div>
          <Eyebrow style={{ marginBottom:12 }}><I.shield c="var(--brand-orange)" s={13}/> &nbsp;Badges · {BADGES.filter(b=>b.earned).length} of {BADGES.length} earned</Eyebrow>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:11 }}>
            {BADGES.map(b=>{
              const Icon = I[b.icon]||I.star;
              return (
                <Card key={b.id} pad={15} style={{ textAlign:'center', opacity: b.earned?1:0.5, borderStyle: b.earned?'solid':'dashed' }}>
                  <div style={{ width:46, height:46, margin:'0 auto 10px', borderRadius:14, background: b.earned?'var(--brand-orange)':'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow: b.earned?'var(--shadow-orange)':'none' }}>
                    <Icon c={b.earned?'#fff':'var(--warm-stone)'} s={22}/>
                  </div>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13, color:'var(--fg-primary)' }}>{b.name}</div>
                  <div style={{ fontFamily:'var(--font-body)', fontSize:10.5, color:'var(--warm-stone)', marginTop:3, lineHeight:1.35 }}>{b.desc}</div>
                  {!b.earned && <div style={{ marginTop:8 }}><Pill tone="grey" icon={<I.lock c="#7C675B" s={10}/>}>Locked</Pill></div>}
                </Card>
              );
            })}
          </div>
        </div>

        {/* leaderboard */}
        <div>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12, gap:10 }}>
            <Eyebrow><I.trophy c="var(--brand-orange)" s={13}/> &nbsp;MK pizza leaderboard</Eyebrow>
            <span title="Ranks are computed from the latest saved snapshot, not a live feed" style={{ cursor:'help', fontFamily:'var(--font-mono)', fontSize:10, color:'var(--warm-stone)' }}>Snapshot · today 06:00</span>
          </div>
          <Card pad={0} style={{ overflow:'hidden' }}>
            {LEADERBOARD.map((v,i)=>(
              <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 16px', borderBottom: i<LEADERBOARD.length-1?'1px solid var(--soft-line)':'none', background: v.you?'rgba(216,90,20,0.06)':'transparent' }}>
                <span style={{ width:22, fontFamily:'var(--font-display)', fontWeight:900, fontSize:15, color: v.rank<=3?'var(--brand-orange)':'var(--warm-stone)' }}>{v.rank}</span>
                <div style={{ width:34, height:34, borderRadius:'50%', background: v.you?'linear-gradient(135deg,#F28C1B,#D85A14)':'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontFamily:'var(--font-display)', fontWeight:900, fontSize:12, color: v.you?'#fff':'var(--horse-brown)' }}>{v.you?VENDOR.initials:'•'}</div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13, color:'var(--fg-primary)' }}>{v.name}{v.you && <span style={{ color:'var(--brand-orange)' }}> · You</span>}</div>
                  <div style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{v.cuisine}</div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:15, color:'var(--fg-primary)' }}>{v.score}%</div>
                  <div style={{ fontFamily:'var(--font-body)', fontSize:9.5, color:'var(--warm-stone)' }}>influence</div>
                </div>
              </div>
            ))}
            <div style={{ padding:'10px 16px', display:'flex', alignItems:'center', gap:8, background:'var(--bg-app)' }}>
              <I.lock c="var(--warm-stone)" s={13}/>
              <span style={{ fontFamily:'var(--font-body)', fontSize:10.5, color:'var(--warm-stone)' }}>Competitor names are anonymised</span>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ─── Campaigns list screen ───────────────────────────────────────────
function CampaignsScreen({ app }) {
  const [sel, setSel] = React.useState(null);
  const [, force] = React.useState(0);
  React.useEffect(()=>{
    if (app.campaignFocus){
      const c = ACTIVE_CAMPAIGNS.find(x=>x.id===app.campaignFocus);
      if (c){ setSel(c); force(v=>v+1); }
      app.clearCampaignFocus();
    }
  }, [app.campaignFocus]);
  const live = ACTIVE_CAMPAIGNS.filter(c=>c.status==='live').length;
  const totalRev = ACTIVE_CAMPAIGNS.reduce((s,c)=>s+c.revenue,0);
  const totalSpend = ACTIVE_CAMPAIGNS.reduce((s,c)=>s+c.spend,0);
  return (
    <div>
      <PageHead eyebrow="Campaigns" title="Marketing campaigns"
        sub={`${live} live · ${ACTIVE_CAMPAIGNS.length} total this month`}
        right={<Btn kind="accent" icon={<I.plus c="#fff" s={16}/>} onClick={()=>app.openBuilder(null)}>New campaign</Btn>}/>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:16 }}>
        {[['Live campaigns', live, I.megaphone],['Total reach', '802', I.users],['Revenue driven', '£'+totalRev.toLocaleString(), I.pound],['Blended ROI', ((totalRev/totalSpend)).toFixed(1)+'×', I.trendUp]].map(([l,v,Ic])=>(
          <Card key={l} pad={16}>
            <Ic c="var(--brand-orange)" s={18}/>
            <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:24, color:'var(--fg-primary)', marginTop:9, lineHeight:1 }}>{v}</div>
            <div style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)', marginTop:4 }}>{l}</div>
          </Card>
        ))}
      </div>

      <Card pad={0} style={{ overflow:'hidden' }}>
        <div style={{ display:'grid', gridTemplateColumns:'2fr 1.2fr 1fr 1fr 1fr 0.9fr 1fr 0.4fr', gap:10, padding:'12px 20px', borderBottom:'1px solid var(--soft-line)', background:'var(--bg-app)' }}>
          {['Campaign','Area','Spend','Reach','Orders','Revenue','Status',''].map((h,i)=> <span key={i} style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:10.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--warm-stone)' }}>{h}</span>)}
        </div>
        {ACTIVE_CAMPAIGNS.map((c,i)=>{
          const ct = CAMPAIGN_TYPES.find(t=>t.id===c.type);
          const CIcon = (ct && I[ct.icon]) || I.megaphone;
          return (
            <div key={c.id} onClick={()=>setSel(c)} style={{ display:'grid', gridTemplateColumns:'2fr 1.2fr 1fr 1fr 1fr 0.9fr 1fr 0.4fr', gap:10, alignItems:'center', padding:'14px 20px', borderBottom: i<ACTIVE_CAMPAIGNS.length-1?'1px solid var(--soft-line)':'none', cursor:'pointer', transition:'background 150ms' }}
              onMouseEnter={(e)=>e.currentTarget.style.background='var(--bg-elevated)'} onMouseLeave={(e)=>e.currentTarget.style.background='transparent'}>
              <div style={{ display:'flex', alignItems:'center', gap:11 }}>
                <div style={{ width:36, height:36, borderRadius:10, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><CIcon c="var(--horse-brown)" s={17}/></div>
                <div>
                  <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13.5, color:'var(--fg-primary)' }}>{c.name}</div>
                  <div style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{ct?ct.name:''}</div>
                </div>
              </div>
              <span style={{ fontFamily:'var(--font-body)', fontSize:12.5, color:'var(--fg-primary)' }}><I.pin c="var(--warm-stone)" s={12}/> {c.area}</span>
              <div>
                <div style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5, color:'var(--fg-primary)' }}>£{c.spend} / £{c.budget}</div>
                <div style={{ width:60, marginTop:4 }}><Bar pct={c.spend/c.budget*100} color="var(--brand-orange)" h={5}/></div>
              </div>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:13, color:'var(--fg-primary)' }}>{c.reach}</span>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:13, color:'var(--fg-primary)' }}>{c.orders}</span>
              <div>
                <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:13.5, color:'var(--fg-primary)' }}>£{c.revenue.toLocaleString()}</div>
                <Pill tone={c.roi>=5?'green':c.roi>=3.5?'amber':'red'} style={{ marginTop:3, fontSize:9.5, padding:'2px 6px' }}>{c.roi}×</Pill>
              </div>
              <Pill tone={(CAMP_STATUS[c.status]||CAMP_STATUS.live).tone} dot>{(CAMP_STATUS[c.status]||CAMP_STATUS.live).label}</Pill>
              <I.chevR c="var(--warm-stone)" s={16}/>
            </div>
          );
        })}
      </Card>

      {/* saved templates */}
      {CAMPAIGN_TEMPLATES.length>0 && (
        <div style={{ marginTop:16 }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:11 }}>
            <Eyebrow><I.bookmark c="var(--brand-orange)" s={13}/> &nbsp;Saved templates</Eyebrow>
            <span style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)' }}>Reusable settings · not running</span>
          </div>
          <Card pad={0} style={{ overflow:'hidden' }}>
            {CAMPAIGN_TEMPLATES.map((tpl,i)=>{
              const tt = CAMPAIGN_TYPES.find(t=>t.id===tpl.typeId);
              const TIcon = (tt && I[tt.icon]) || I.gift;
              const est = ESTATES.find(e=>e.id===tpl.estateId);
              return (
                <div key={tpl.id} style={{ display:'flex', alignItems:'center', gap:13, padding:'13px 20px', borderBottom: i<CAMPAIGN_TEMPLATES.length-1?'1px solid var(--soft-line)':'none' }}>
                  <div style={{ width:36, height:36, borderRadius:10, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><TIcon c="var(--horse-brown)" s={17}/></div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13.5, color:'var(--fg-primary)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{tpl.name}</div>
                    <div style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{tt?tt.name:''} · £{tpl.budget} · {tpl.duration} days{est?` · ${est.name}`:''}</div>
                  </div>
                  <Pill tone="grey">{tpl.lastUsed||'Template'}</Pill>
                  <Btn kind="primary" size="sm" icon={<I.rocket c="var(--dust-cream)" s={14}/>} onClick={()=>app.openBuilder(tpl.estateId, null, tpl)}>Use</Btn>
                  <button onClick={()=>{ const idx=CAMPAIGN_TEMPLATES.indexOf(tpl); if(idx>-1) CAMPAIGN_TEMPLATES.splice(idx,1); force(v=>v+1); app.toast('Template removed'); }} title="Delete template" style={{ width:30, height:30, borderRadius:9, border:'1px solid var(--soft-line)', background:'var(--bg-surface)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}><I.x c="var(--warm-stone)" s={15}/></button>
                </div>
              );
            })}
          </Card>
        </div>
      )}

      {sel && <CampaignDetail app={app} c={sel} onClose={()=>setSel(null)}/>}
    </div>
  );
}

Object.assign(window, { RewardsScreen, CampaignsScreen });
