// screens-core.jsx — shared chrome + Home + Pet detail
// Exports: TabBar, SoftCard, QuickAction, StatChip, HomeScreen, PetScreen

function SoftCard({ children, style = {}, pad = 18, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: 'var(--surface)', borderRadius: 'var(--r-card)', padding: pad,
      boxShadow: 'var(--shadow-soft)', border: '1px solid var(--line)',
      cursor: onClick ? 'pointer' : 'default', ...style,
    }}>{children}</div>
  );
}

function QuickAction({ icon, label, tone = 'var(--violet)', soft = 'var(--violet-soft)', onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, border: 'none', background: 'transparent', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: 0,
    }}>
      <span style={{
        width: 54, height: 54, borderRadius: 18, background: soft, color: tone,
        display: 'grid', placeItems: 'center', transition: 'transform .15s',
        boxShadow: 'inset 0 -2px 0 rgba(0,0,0,.04)',
      }} onMouseDown={(e) => e.currentTarget.style.transform = 'scale(.92)'}
         onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
         onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
        <Icon name={icon} size={24} stroke={2.2} />
      </span>
      <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-2)' }}>{label}</span>
    </button>
  );
}

function StatChip({ icon, label, value, tone = 'var(--ink)', soft }) {
  return (
    <div style={{ flex: 1, background: 'var(--surface-2)', borderRadius: 'var(--r-md)', padding: '12px 12px 13px', border: '1px solid var(--line)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', marginBottom: 5 }}>
        <Icon name={icon} size={15} stroke={2.2} color={soft || 'var(--ink-3)'} />
        <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.3px', textTransform: 'uppercase' }}>{label}</span>
      </div>
      <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 21, color: tone, lineHeight: 1 }}>{value}</div>
    </div>
  );
}

const TABS = [
  { id: 'home', icon: 'home', label: 'Wallet' },
  { id: 'pet', icon: 'paw', label: 'Pet' },
  { id: 'market', icon: 'market', label: 'Market' },
  { id: 'style', icon: 'palette', label: 'Style' },
];
function TabBar({ active, onTab }) {
  return (
    <div style={{
      display: 'flex', padding: '10px 12px 24px', gap: 4,
      background: 'color-mix(in srgb, var(--surface) 88%, transparent)',
      backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
      borderTop: '1px solid var(--line)', position: 'relative', zIndex: 5,
    }}>
      {TABS.map((tb) => {
        const on = tb.id === active;
        return (
          <button key={tb.id} onClick={() => onTab(tb.id)} style={{
            flex: 1, border: 'none', background: 'transparent', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, padding: '4px 0',
            color: on ? 'var(--violet)' : 'var(--ink-3)', transition: 'color .2s',
          }}>
            <Icon name={tb.icon} size={24} stroke={on ? 2.5 : 2} fill={on ? 'currentColor' : 'none'} />
            <span style={{ fontSize: 10.5, fontWeight: 700 }}>{tb.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// reusable scroll shell with sticky header + tab bar
function Shell({ header, children, active, onTab, pad = 18 }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ paddingTop: 52, position: 'relative', zIndex: 4 }}>{header}</div>
      <div style={{ flex: 1, overflowY: 'auto', padding: `4px ${pad}px 20px` }}>{children}</div>
      <TabBar active={active} onTab={onTab} />
    </div>
  );
}

function MiniCreature({ pet, art, size = 40 }) {
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', background: 'var(--surface-2)', display: 'grid', placeItems: 'center', border: '1px solid var(--line)', overflow: 'hidden' }}>
      <Creature hue={pet.hue} size={size * 0.92} stage={pet.stage} art={art} bob={false} />
    </div>
  );
}

// ── HOME ────────────────────────────────────────────────────────
function HomeScreen({ ctx }) {
  const { t, pet, theme, total, change, go, doTrade, agent } = ctx;
  const hero = t.homeLayout !== 'compact';
  const lvlPct = pet.xp / xpForLevel(pet.level + 1);

  const header = (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 18px 8px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
        <MiniCreature pet={pet} art={t.art} />
        <div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', fontWeight: 600 }}>Good morning</div>
          <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 17, color: 'var(--ink)' }}>vee.eth</div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        {['eye', 'qr'].map((ic) => (
          <span key={ic} style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--surface)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', color: 'var(--ink-2)' }}>
            <Icon name={ic} size={18} stroke={2} />
          </span>
        ))}
      </div>
    </div>
  );

  const balanceCard = (
    <div style={{
      borderRadius: 'var(--r-card)', padding: hero ? '20px 22px 24px' : '22px 22px',
      background: `linear-gradient(150deg, ${theme.c1}, ${theme.c2})`,
      position: 'relative', overflow: 'hidden', boxShadow: `0 14px 34px ${theme.c1}55`,
    }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(120% 80% at 85% -10%, rgba(255,255,255,.4), transparent 60%)' }} />
      {hero && (
        <div style={{ position: 'relative', display: 'flex', justifyContent: 'center', marginBottom: 6 }}>
          <div style={{ position: 'relative' }} onClick={() => go('pet')}>
            <Creature hue={pet.hue} size={132} stage={pet.stage} art={t.art} mood="happy" />
            <div style={{ position: 'absolute', bottom: 8, right: -6, whiteSpace: 'nowrap', background: 'rgba(255,255,255,.92)', borderRadius: 999, padding: '4px 10px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 13, color: 'var(--ink)', boxShadow: '0 4px 12px rgba(0,0,0,.18)' }}>Lv {pet.level}</div>
          </div>
        </div>
      )}
      <div style={{ position: 'relative', display: 'flex', alignItems: hero ? 'flex-start' : 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,.82)', letterSpacing: '.3px' }}>Total balance</div>
          <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 42, color: '#fff', lineHeight: 1.05, letterSpacing: '-.5px', textShadow: '0 2px 8px rgba(0,0,0,.12)' }}>{fmtUSD(total)}</div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 8, background: 'rgba(255,255,255,.22)', borderRadius: 999, padding: '4px 10px', color: '#fff', fontWeight: 700, fontSize: 13 }}>
            <Icon name="arrowUp" size={14} stroke={2.6} /> {change.toFixed(1)}% today
          </div>
        </div>
        {!hero && (
          <div style={{ position: 'relative' }} onClick={() => go('pet')}>
            <Creature hue={pet.hue} size={88} stage={pet.stage} art={t.art} />
            <div style={{ position: 'absolute', bottom: 2, right: -2, whiteSpace: 'nowrap', background: 'rgba(255,255,255,.92)', borderRadius: 999, padding: '2px 8px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 11, color: 'var(--ink)' }}>Lv {pet.level}</div>
          </div>
        )}
      </div>
      {/* xp bar */}
      <div style={{ position: 'relative', marginTop: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, fontWeight: 700, color: 'rgba(255,255,255,.85)', marginBottom: 5 }}>
          <span>XP to Lv {pet.level + 1}</span><span>{pet.xp} / {xpForLevel(pet.level + 1)}</span>
        </div>
        <div style={{ height: 8, borderRadius: 999, background: 'rgba(255,255,255,.28)', overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${Math.min(100, lvlPct * 100)}%`, borderRadius: 999, background: '#fff', transition: 'width .7s cubic-bezier(.4,1.3,.5,1)' }} />
        </div>
      </div>
    </div>
  );

  return (
    <Shell header={header} active="home" onTab={go}>
      {balanceCard}
      {/* quick actions */}
      <SoftCard style={{ marginTop: 16, padding: '18px 14px' }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <QuickAction icon="send" label="Send" />
          <QuickAction icon="receive" label="Receive" tone="var(--sky)" soft="#E3F2FD" />
          <QuickAction icon="swap" label="Swap" tone="var(--peach)" soft="#FFEBDD" />
          <QuickAction icon="trade" label="Trade" tone="var(--mint)" soft="var(--mint-soft)" onClick={doTrade} />
        </div>
      </SoftCard>

      {/* active agent strip */}
      <SoftCard style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 12 }} onClick={() => go('market')}>
        <div style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--violet-soft)', color: 'var(--violet)', display: 'grid', placeItems: 'center' }}>
          <Icon name="cpu" size={22} stroke={2} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <span style={{ fontWeight: 800, fontSize: 14.5 }}>{agent.name}</span>
            <span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--mint)', boxShadow: '0 0 0 3px var(--mint-soft)' }} />
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>Agent live · {agent.runs} runs today</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 17, color: 'var(--mint)' }}>+{agent.apy}%</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 700 }}>APY</div>
        </div>
      </SoftCard>

      {/* assets */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '22px 4px 12px' }}>
        <span style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Assets</span>
        <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--violet)' }}>See all</span>
      </div>
      <SoftCard pad={6}>
        {ASSETS.map((a, i) => (
          <div key={a.sym} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 12px', borderBottom: i < ASSETS.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <div style={{ width: 40, height: 40, borderRadius: 13, background: `oklch(0.92 0.09 ${a.hue})`, color: `oklch(0.45 0.15 ${a.hue})`, display: 'grid', placeItems: 'center', fontFamily: 'var(--disp)', fontWeight: 700, fontSize: 14 }}>{a.sym.slice(0, 2)}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 14.5 }}>{a.name}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', fontWeight: 600 }}>{a.amt} {a.sym}</div>
            </div>
            <Sparkline data={a.spark} w={56} h={28} color={a.chg >= 0 ? 'var(--mint)' : 'var(--coral)'} />
            <div style={{ textAlign: 'right', minWidth: 78 }}>
              <div style={{ fontWeight: 800, fontSize: 14 }}>{fmtUSD(a.amt * a.price)}</div>
              <div style={{ fontSize: 12, fontWeight: 700, color: a.chg > 0 ? 'var(--mint)' : a.chg < 0 ? 'var(--coral)' : 'var(--ink-3)' }}>{a.chg > 0 ? '+' : ''}{a.chg}%</div>
            </div>
          </div>
        ))}
      </SoftCard>
      <div style={{ height: 6 }} />
    </Shell>
  );
}

// ── PET DETAIL ──────────────────────────────────────────────────
function PetScreen({ ctx }) {
  const { t, pet, go, listPet } = ctx;
  const nextXp = xpForLevel(pet.level + 1);
  const pct = pet.xp / nextXp;
  const stages = [
    { n: 'Sprout', lvl: 1 }, { n: 'Bloom', lvl: LEVELS.evolveAt[0] }, { n: 'Radiant', lvl: LEVELS.evolveAt[1] },
  ];
  const perks = [
    { icon: 'bolt', t: 'Gas rebate', d: '12% off network fees', on: true },
    { icon: 'cpu', t: 'Agent slots', d: '2 of 3 unlocked', on: true },
    { icon: 'star', t: 'Pro signals', d: 'Unlocks at Lv 25', on: pet.level >= 25 },
  ];

  const header = (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 18px 4px' }}>
      <span style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 26 }}>{pet.name}</span>
      <span style={{ fontSize: 12.5, fontWeight: 800, whiteSpace: 'nowrap', color: 'var(--violet)', background: 'var(--violet-soft)', padding: '6px 12px', borderRadius: 999 }}>{['Sprout', 'Bloom', 'Radiant'][pet.stage - 1]} form</span>
    </div>
  );

  return (
    <Shell header={header} active="pet" onTab={go}>
      {/* hero creature */}
      <div style={{ position: 'relative', borderRadius: 'var(--r-card)', padding: '14px 0 22px', background: `radial-gradient(120% 90% at 50% 10%, oklch(0.95 0.05 ${pet.hue}), var(--surface) 70%)`, border: '1px solid var(--line)', overflow: 'hidden' }}>
        <div style={{ display: 'grid', placeItems: 'center' }}>
          <div style={{ animation: 'poke-float 3.6s ease-in-out infinite' }}>
            <Creature hue={pet.hue} size={188} stage={pet.stage} art={t.art} mood="excited" accessory={pet.accessory} />
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 8 }}>
          <Ring size={70} stroke={7} value={pct} color={`oklch(0.7 0.16 ${pet.hue})`}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--disp)', fontWeight: 700, fontSize: 22, lineHeight: 1 }}>{pet.level}</div>
              <div style={{ fontSize: 9, fontWeight: 800, color: 'var(--ink-3)', letterSpacing: '.5px' }}>LEVEL</div>
            </div>
          </Ring>
        </div>
        <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-2)', fontWeight: 700, marginTop: 8 }}>
          {nextXp - pet.xp} XP to Lv {pet.level + 1}
        </div>
      </div>

      {/* evolution timeline */}
      <div style={{ margin: '22px 4px 12px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Evolution</div>
      <SoftCard>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', position: 'relative' }}>
          <div style={{ position: 'absolute', left: '16%', right: '16%', top: 40, height: 3, background: 'var(--line)', borderRadius: 9 }} />
          <div style={{ position: 'absolute', left: '16%', width: `${(Math.min(pet.stage, 3) - 1) / 2 * 68}%`, top: 40, height: 3, background: `oklch(0.7 0.16 ${pet.hue})`, borderRadius: 9, transition: 'width .6s' }} />
          {stages.map((s, i) => {
            const reached = pet.stage >= i + 1;
            return (
              <div key={s.n} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, zIndex: 1, flex: 1 }}>
                <div style={{ opacity: reached ? 1 : 0.32, filter: reached ? 'none' : 'grayscale(.5)' }}>
                  <Creature hue={pet.hue} size={62} stage={i + 1} art={t.art} bob={false} />
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 800, color: reached ? 'var(--ink)' : 'var(--ink-3)' }}>{s.n}</div>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-3)' }}>Lv {s.lvl}</div>
              </div>
            );
          })}
        </div>
      </SoftCard>

      {/* stats */}
      <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
        <StatChip icon="trade" label="Trades" value={pet.trades} soft="var(--violet)" />
        <StatChip icon="chart" label="Volume" value={pet.volume} soft="var(--sky)" />
        <StatChip icon="fire" label="Streak" value={`${pet.streak}d`} tone="var(--peach)" soft="var(--peach)" />
      </div>

      {/* perks */}
      <div style={{ margin: '22px 4px 12px', fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 18 }}>Perks</div>
      <SoftCard pad={6}>
        {perks.map((p, i) => (
          <div key={p.t} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px', borderBottom: i < perks.length - 1 ? '1px solid var(--line)' : 'none', opacity: p.on ? 1 : 0.5 }}>
            <div style={{ width: 38, height: 38, borderRadius: 12, background: p.on ? 'var(--mint-soft)' : 'var(--bg-2)', color: p.on ? 'var(--mint)' : 'var(--ink-3)', display: 'grid', placeItems: 'center' }}>
              <Icon name={p.on ? p.icon : 'lock'} size={18} stroke={2.2} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 14 }}>{p.t}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>{p.d}</div>
            </div>
            {p.on && <Icon name="check" size={18} color="var(--mint)" stroke={2.6} />}
          </div>
        ))}
      </SoftCard>

      {/* sell / trade pet */}
      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        <button onClick={listPet} style={{ flex: 1, border: 'none', cursor: 'pointer', padding: '15px', borderRadius: 'var(--r-lg)', background: 'var(--violet)', color: '#fff', fontFamily: 'var(--body)', fontWeight: 800, fontSize: 15, boxShadow: 'var(--shadow-pop)' }}>List on Pet Market</button>
        <button style={{ width: 56, border: '1px solid var(--line)', cursor: 'pointer', borderRadius: 'var(--r-lg)', background: 'var(--surface)', color: 'var(--ink-2)', display: 'grid', placeItems: 'center' }}>
          <Icon name="gift" size={22} stroke={2} />
        </button>
      </div>
      <div style={{ height: 6 }} />
    </Shell>
  );
}

Object.assign(window, { TabBar, SoftCard, QuickAction, StatChip, Shell, MiniCreature, HomeScreen, PetScreen });
