// screens-more.jsx — Strategy/Pet Market, Customize, Onboarding
// Exports: MarketScreen, CustomizeScreen, Onboarding

function RiskPill({ risk }) {
  const map = { Low: ['var(--mint)', 'var(--mint-soft)'], Med: ['var(--peach)', '#FFEBDD'], High: ['var(--coral)', 'var(--coral-soft)'] };
  const [c, s] = map[risk] || map.Med;
  return <span style={{ fontSize: 11, fontWeight: 800, color: c, background: s, padding: '3px 9px', borderRadius: 999 }}>{risk} risk</span>;
}

function DeployBtn({ on, onClick, small }) {
  return (
    <button onClick={onClick} style={{
      border: 'none', cursor: 'pointer', borderRadius: 'var(--r-pill)',
      padding: small ? '8px 14px' : '11px 16px', fontFamily: 'var(--body)', fontWeight: 800, fontSize: small ? 12.5 : 14,
      background: on ? 'var(--mint-soft)' : 'var(--violet)', color: on ? 'var(--mint)' : '#fff',
      display: 'inline-flex', alignItems: 'center', gap: 6, transition: 'all .2s',
    }}>
      {on ? <><Icon name="check" size={15} stroke={3} /> Deployed</> : <>Deploy</>}
    </button>
  );
}

// ── MARKET ──────────────────────────────────────────────────────
function MarketScreen({ ctx }) {
  const { t, go } = ctx;
  const [tab, setTab] = React.useState('strategies');
  const [deployed, setDeployed] = React.useState({});
  const toggle = (id) => setDeployed((d) => ({ ...d, [id]: !d[id] }));

  const header = (
    <div style={{ padding: '0 18px 10px' }}>
      <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 26, marginBottom: 12 }}>Market</div>
      <Segmented options={[{ value: 'strategies', label: 'Strategies' }, { value: 'pets', label: 'Pets' }]} value={tab} onChange={setTab} />
    </div>
  );

  const layout = t.mktLayout || 'cards';
  const sorted = [...STRATEGIES].sort((a, b) => b.apy - a.apy);

  return (
    <Shell header={header} active="market" onTab={go}>
      {tab === 'strategies' && (
        <>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '4px 4px 14px', color: 'var(--ink-2)' }}>
            <Icon name="cpu" size={16} stroke={2.1} color="var(--violet)" />
            <span style={{ fontSize: 12.5, fontWeight: 700 }}>Acquire an agent harness · deploy on Poke infra · it trades for you</span>
          </div>

          {/* CARDS layout */}
          {layout === 'cards' && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {sorted.map((s) => (
                <SoftCard key={s.id} pad={14}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div style={{ width: 36, height: 36, borderRadius: 11, background: `oklch(0.92 0.08 ${s.hue})`, color: `oklch(0.45 0.15 ${s.hue})`, display: 'grid', placeItems: 'center' }}><Icon name="cpu" size={19} stroke={2.1} /></div>
                    <RiskPill risk={s.risk} />
                  </div>
                  <div style={{ fontWeight: 800, fontSize: 15, marginTop: 10, lineHeight: 1.2 }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 700, marginTop: 2 }}>{s.author}</div>
                  <div style={{ margin: '10px 0 8px' }}><Sparkline data={s.spark} w={150} h={34} color={`oklch(0.62 0.16 ${s.hue})`} /></div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <div><div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 20, color: 'var(--mint)' }}>{s.apy}%</div><div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-3)' }}>APY · {s.win}% win</div></div>
                  </div>
                  <button onClick={() => toggle(s.id)} style={{ width: '100%', marginTop: 10, border: 'none', cursor: 'pointer', borderRadius: 'var(--r-md)', padding: '10px', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 13, background: deployed[s.id] ? 'var(--mint-soft)' : 'var(--violet)', color: deployed[s.id] ? 'var(--mint)' : '#fff' }}>{deployed[s.id] ? '✓ Deployed' : `Deploy · ${s.price} ETH`}</button>
                </SoftCard>
              ))}
            </div>
          )}

          {/* LEADERBOARD layout */}
          {layout === 'leaderboard' && (
            <SoftCard pad={6}>
              {sorted.map((s, i) => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 10px', borderBottom: i < sorted.length - 1 ? '1px solid var(--line)' : 'none' }}>
                  <div style={{ fontFamily: 'var(--disp)', fontWeight: 700, fontSize: 17, color: i === 0 ? 'var(--butter)' : i === 1 ? '#B8B2C4' : i === 2 ? 'var(--peach)' : 'var(--ink-3)', width: 22, textAlign: 'center' }}>{i + 1}</div>
                  <div style={{ width: 34, height: 34, borderRadius: 10, background: `oklch(0.92 0.08 ${s.hue})`, color: `oklch(0.45 0.15 ${s.hue})`, display: 'grid', placeItems: 'center' }}><Icon name="cpu" size={17} stroke={2.1} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 800, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 700 }}>{s.win}% win · {s.sub} live</div>
                  </div>
                  <Sparkline data={s.spark} w={44} h={24} color={`oklch(0.62 0.16 ${s.hue})`} fill={false} />
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 17, color: 'var(--mint)' }}>{s.apy}%</div>
                    <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-3)' }}>APY</div>
                  </div>
                  <DeployBtn small on={deployed[s.id]} onClick={() => toggle(s.id)} />
                </div>
              ))}
            </SoftCard>
          )}

          {/* ROSTER layout — agent-forward */}
          {layout === 'roster' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {sorted.map((s) => (
                <SoftCard key={s.id} pad={16}>
                  <div style={{ display: 'flex', gap: 13 }}>
                    <div style={{ width: 58, height: 58, borderRadius: 16, background: `linear-gradient(150deg, oklch(0.85 0.13 ${s.hue}), oklch(0.7 0.16 ${s.hue}))`, color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0, boxShadow: `0 6px 16px oklch(0.7 0.16 ${s.hue} / .4)` }}><Icon name="cpu" size={28} stroke={2} /></div>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                        <div><div style={{ fontWeight: 800, fontSize: 15.5 }}>{s.name}</div><div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 700 }}>{s.author}</div></div>
                        <RiskPill risk={s.risk} />
                      </div>
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 7, background: 'var(--violet-soft)', color: 'var(--violet)', borderRadius: 999, padding: '3px 9px', fontSize: 11, fontWeight: 800 }}>
                        <Icon name="spark" size={12} stroke={2.4} /> {s.model}
                      </div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 8, marginTop: 13 }}>
                    {[['APY', `${s.apy}%`, 'var(--mint)'], ['Win rate', `${s.win}%`, 'var(--ink)'], ['Live runs', s.runs, 'var(--ink)']].map(([l, v, c]) => (
                      <div key={l} style={{ flex: 1, background: 'var(--surface-2)', borderRadius: 12, padding: '9px 10px', border: '1px solid var(--line)' }}>
                        <div style={{ fontSize: 10, fontWeight: 800, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.3px' }}>{l}</div>
                        <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 17, color: c }}>{v}</div>
                      </div>
                    ))}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 13 }}>
                    <button onClick={() => toggle(s.id)} style={{ flex: 1, border: 'none', cursor: 'pointer', borderRadius: 'var(--r-lg)', padding: '13px', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 14, background: deployed[s.id] ? 'var(--mint-soft)' : 'var(--violet)', color: deployed[s.id] ? 'var(--mint)' : '#fff' }}>{deployed[s.id] ? '✓ Running on your infra' : 'Recruit agent'}</button>
                    <div style={{ textAlign: 'right' }}><div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 16, whiteSpace: 'nowrap' }}>{s.price} ETH</div><div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-3)' }}>license</div></div>
                  </div>
                </SoftCard>
              ))}
            </div>
          )}
        </>
      )}

      {/* PET MARKET */}
      {tab === 'pets' && (
        <>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '4px 4px 14px', color: 'var(--ink-2)' }}>
            <Icon name="paw" size={16} stroke={2.1} color="var(--violet)" />
            <span style={{ fontSize: 12.5, fontWeight: 700 }}>Buy a creature & inherit its trading track record</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {MARKET_PETS.map((p) => (
              <SoftCard key={p.id} pad={14}>
                <div style={{ display: 'flex', justifyContent: 'center', background: `radial-gradient(90% 80% at 50% 12%, oklch(0.95 0.05 ${p.hue}), transparent 75%)`, borderRadius: 18, padding: '6px 0' }}>
                  <Creature hue={p.hue} size={92} stage={p.stage} art={t.art} bob={false} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
                  <span style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 17 }}>{p.name}</span>
                  <span style={{ fontSize: 10, fontWeight: 800, color: `oklch(0.5 0.16 ${p.hue})`, background: `oklch(0.93 0.07 ${p.hue})`, padding: '3px 8px', borderRadius: 999 }}>{p.rarity}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 700, marginTop: 3 }}>Lv {p.level} · {p.trades} trades</div>
                <button style={{ width: '100%', marginTop: 11, border: 'none', cursor: 'pointer', borderRadius: 'var(--r-md)', padding: '10px', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 13.5, background: 'var(--ink)', color: 'var(--surface)' }}>{p.price} ETH</button>
              </SoftCard>
            ))}
          </div>
        </>
      )}
      <div style={{ height: 6 }} />
    </Shell>
  );
}

// ── CUSTOMIZE ───────────────────────────────────────────────────
const ART_OPTS = [{ v: 'clay', l: 'Clay' }, { v: 'flat', l: 'Flat' }, { v: 'gem', l: 'Gem' }, { v: 'pixel', l: 'Pixel' }];
const BGS = [
  { id: 'dots', name: 'Confetti' }, { id: 'rings', name: 'Bubbles' }, { id: 'plain', name: 'Clean' },
];
function CustomizeScreen({ ctx }) {
  const { t, pet, theme, go, setTheme, setArt, setAccessory, rehatch } = ctx;

  const header = <div style={{ padding: '0 18px 6px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 26 }}>Customize</div>;

  return (
    <Shell header={header} active="style" onTab={go}>
      {/* live preview */}
      <div style={{ borderRadius: 'var(--r-card)', padding: '24px 0 26px', background: `linear-gradient(150deg, ${theme.c1}, ${theme.c2})`, position: 'relative', overflow: 'hidden', boxShadow: `0 14px 30px ${theme.c1}55`, display: 'grid', placeItems: 'center' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(120% 80% at 80% -10%, rgba(255,255,255,.4), transparent 60%)' }} />
        <div style={{ position: 'relative', animation: 'poke-float 3.6s ease-in-out infinite' }}>
          <Creature hue={pet.hue} size={150} stage={pet.stage} art={t.art} mood="happy" accessory={pet.accessory} />
        </div>
        <div style={{ position: 'relative', marginTop: 6, color: '#fff', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18, textShadow: '0 2px 6px rgba(0,0,0,.15)' }}>Live preview</div>
      </div>

      {/* theme */}
      <div style={{ margin: '22px 4px 12px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Wallet theme</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        {THEMES.map((th) => {
          const on = th.id === theme.id;
          return (
            <button key={th.id} onClick={() => setTheme(th)} style={{ border: on ? '2.5px solid var(--violet)' : '1px solid var(--line)', cursor: 'pointer', borderRadius: 18, padding: 8, background: 'var(--surface)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7 }}>
              <div style={{ width: '100%', height: 42, borderRadius: 12, background: `linear-gradient(150deg, ${th.c1}, ${th.c2})` }} />
              <span style={{ fontSize: 11.5, fontWeight: 800, color: on ? 'var(--violet)' : 'var(--ink-2)' }}>{th.name}</span>
            </button>
          );
        })}
      </div>

      {/* art style */}
      <div style={{ margin: '22px 4px 12px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Creature style</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 10 }}>
        {ART_OPTS.map((o) => {
          const on = t.art === o.v;
          return (
            <button key={o.v} onClick={() => setArt(o.v)} style={{ border: on ? '2.5px solid var(--violet)' : '1px solid var(--line)', cursor: 'pointer', borderRadius: 16, padding: '10px 4px 8px', background: 'var(--surface)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              <Creature hue={pet.hue} size={46} stage={2} art={o.v} bob={false} />
              <span style={{ fontSize: 11, fontWeight: 800, color: on ? 'var(--violet)' : 'var(--ink-2)' }}>{o.l}</span>
            </button>
          );
        })}
      </div>

      {/* accessory */}
      <div style={{ margin: '22px 4px 12px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Accessory</div>
      <div style={{ display: 'flex', gap: 10 }}>
        {[{ v: null, l: 'None' }, { v: 'crown', l: 'Crown 👑' }].map((o) => {
          const on = pet.accessory === o.v;
          return <button key={o.l} onClick={() => setAccessory(o.v)} style={{ flex: 1, border: on ? '2.5px solid var(--violet)' : '1px solid var(--line)', cursor: 'pointer', borderRadius: 'var(--r-md)', padding: '13px', background: 'var(--surface)', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 13.5, color: on ? 'var(--violet)' : 'var(--ink-2)' }}>{o.l}</button>;
        })}
      </div>

      {/* re-hatch */}
      <div style={{ margin: '22px 4px 12px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Companion</div>
      <SoftCard onClick={rehatch} style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
        <div style={{ width: 46, height: 46, borderRadius: 14, background: 'var(--violet-soft)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          <CreatureEgg hue={pet.hue} size={26} wobble={false} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 800, fontSize: 14.5 }}>Re-hatch a new companion</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>Replay onboarding & start fresh</div>
        </div>
        <Icon name="chevron" size={20} color="var(--ink-3)" stroke={2.2} />
      </SoftCard>
      <div style={{ height: 6 }} />
    </Shell>
  );
}

// ── ONBOARDING / HATCH ──────────────────────────────────────────
function Onboarding({ onDone }) {
  const [step, setStep] = React.useState(0); // 0 intro, 1 egg, 2 hatched
  const [taps, setTaps] = React.useState(0);
  const [hue, setHue] = React.useState(285);
  const cracked = Math.min(1, taps / 3);
  const hatched = taps >= 3;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: `radial-gradient(120% 70% at 50% 0%, oklch(0.95 0.05 ${hue}), var(--bg) 70%)`, paddingTop: 64 }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '20px 32px', textAlign: 'center', overflowY: 'auto' }}>
        {step === 0 && (
          <>
            <div style={{ display: 'flex', gap: -10, marginBottom: 10 }}>
              <Creature hue={165} size={64} stage={2} art="clay" />
              <Creature hue={285} size={84} stage={2} art="clay" style={{ margin: '0 -8px' }} />
              <Creature hue={40} size={64} stage={2} art="clay" />
            </div>
            <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 34, lineHeight: 1.1, marginTop: 8 }}>Your wallet is alive</div>
            <p style={{ fontSize: 15.5, color: 'var(--ink-2)', fontWeight: 600, lineHeight: 1.5, maxWidth: 300, marginTop: 12 }}>Every trade feeds your companion. It levels up, evolves, and becomes your on-chain reputation.</p>
            <button onClick={() => setStep(1)} style={{ marginTop: 28, border: 'none', cursor: 'pointer', padding: '16px 40px', borderRadius: 999, background: 'var(--violet)', color: '#fff', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 16, boxShadow: 'var(--shadow-pop)' }}>Hatch my egg</button>
          </>
        )}
        {step === 1 && (
          <>
            {!hatched ? (
              <>
                <div onClick={() => setTaps((n) => n + 1)} style={{ cursor: 'pointer', transform: `scale(${1 + taps * 0.02})`, transition: 'transform .15s' }}>
                  <CreatureEgg hue={hue} size={168} cracked={cracked} />
                </div>
                <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 24, marginTop: 22 }}>{taps === 0 ? 'Tap to hatch!' : taps < 3 ? 'Keep tapping…' : ''}</div>
                <p style={{ fontSize: 14, color: 'var(--ink-3)', fontWeight: 700, marginTop: 6 }}>{3 - taps} taps to go</p>
                {/* egg color choice */}
                <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
                  {[285, 165, 40, 230, 350].map((h) => (
                    <button key={h} onClick={() => setHue(h)} style={{ width: 34, height: 34, borderRadius: '50%', border: hue === h ? '3px solid var(--ink)' : '2px solid var(--line)', cursor: 'pointer', background: `oklch(0.78 0.16 ${h})` }} />
                  ))}
                </div>
              </>
            ) : (
              <>
                <div style={{ animation: 'poke-pop .6s cubic-bezier(.3,1.5,.5,1) both' }}>
                  <Creature hue={hue} size={156} stage={1} art="clay" mood="excited" />
                </div>
                <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 30, marginTop: 14 }}>Meet Mochi!</div>
                <p style={{ fontSize: 15, color: 'var(--ink-2)', fontWeight: 600, marginTop: 8, maxWidth: 290 }}>A Sprout-form companion. Trade to help it grow into its Radiant form.</p>
                <button onClick={() => onDone(hue)} style={{ marginTop: 26, border: 'none', cursor: 'pointer', padding: '16px 44px', borderRadius: 999, background: 'var(--violet)', color: '#fff', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 16, boxShadow: 'var(--shadow-pop)' }}>Enter wallet</button>
              </>
            )}
          </>
        )}
      </div>
      {/* progress dots */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 7, paddingBottom: 40 }}>
        {[0, 1].map((i) => <div key={i} style={{ width: i === step ? 22 : 7, height: 7, borderRadius: 999, background: i === step ? 'var(--violet)' : 'var(--line)', transition: 'width .3s' }} />)}
      </div>
    </div>
  );
}

Object.assign(window, { MarketScreen, CustomizeScreen, Onboarding });
