// app.jsx — wallet state, trade→XP loop, canvas layout, tweaks
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "art": "clay",
  "homeLayout": "hero",
  "mktLayout": "roster",
  "petLevel": 12,
  "dark": false
}/*EDITMODE-END*/;

const AGENT = { name: 'Stable Yield Loom', apy: 11.2, runs: 47 };

function nearestTheme(hue) {
  return THEMES.reduce((best, th) => Math.abs(((th.hue - hue + 540) % 360) - 180) < Math.abs(((best.hue - hue + 540) % 360) - 180) ? th : best, THEMES[0]);
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [tab, setTab] = React.useState('home');
  const [onboarded, setOnboarded] = React.useState(true);
  const [theme, setTheme] = React.useState(THEMES[0]);
  const [accessory, setAccessory] = React.useState(null);
  const [bonusXp, setBonusXp] = React.useState(180);
  const [trades, setTrades] = React.useState(1284);
  const [volume, setVolume] = React.useState(2.4); // $M
  const [streak, setStreak] = React.useState(23);
  const [flash, setFlash] = React.useState(null);

  const level = t.petLevel;
  const stage = level >= LEVELS.evolveAt[1] ? 3 : level >= LEVELS.evolveAt[0] ? 2 : 1;
  const pet = { name: 'Mochi', hue: theme.hue, level, xp: bonusXp, stage, accessory, trades: fmtNum(trades), volume: '$' + volume.toFixed(1) + 'M', streak };

  const total = ASSETS.reduce((s, a) => s + a.amt * a.price, 0);
  const change = 3.2;

  const doTrade = React.useCallback(() => {
    const gain = 50 + Math.round(Math.random() * 60);
    const need = xpForLevel(level + 1);
    let nb = bonusXp + gain, leveled = false;
    if (nb >= need) { nb -= need; leveled = true; setTweak('petLevel', Math.min(99, level + 1)); }
    setBonusXp(nb);
    setTrades((n) => n + 1);
    setVolume((v) => +(v + 0.01).toFixed(2));
    setFlash({ amt: gain, leveled, key: Date.now() });
    setTimeout(() => setFlash(null), 1300);
  }, [bonusXp, level, setTweak]);

  const listPet = () => { setFlash({ listing: true, key: Date.now() }); setTimeout(() => setFlash(null), 1800); };

  const ctx = {
    t, pet, theme, total, change, agent: AGENT,
    go: setTab, doTrade, listPet,
    rehatch: () => setOnboarded(false),
    setTheme: (th) => setTheme(th),
    setArt: (v) => setTweak('art', v),
    setAccessory,
  };

  const Screen = { home: HomeScreen, pet: PetScreen, market: MarketScreen, style: CustomizeScreen }[tab];

  return (
    <div className={'stage' + (t.dark ? ' theme-dark' : '')} style={{ background: t.dark ? 'radial-gradient(1200px 700px at 18% -8%, #221b33 0%, transparent 55%), radial-gradient(1000px 600px at 95% 110%, #102530 0%, transparent 55%), #100E18' : 'transparent' }}>
      {/* header */}
      <div className="stage-head">
        <div className="brand-row">
          <div className="brand-mark"><Icon name="paw" size={30} color="#fff" stroke={2.2} fill="#fff" /></div>
          <div>
            <div className="brand-name" style={{ color: t.dark ? '#F3F0FA' : undefined }}>Poke</div>
            <div className="brand-tag" style={{ color: t.dark ? '#AAA3BC' : undefined }}>A crypto wallet that grows with how you trade</div>
          </div>
        </div>
        <div className="legend" style={{ color: t.dark ? '#AAA3BC' : undefined }}>
          Mobile app + browser extension, same wallet.<br />
          Tap <b style={{ color: t.dark ? '#fff' : '#2A2833' }}>Trade</b> to earn XP · open <b style={{ color: t.dark ? '#fff' : '#2A2833' }}>Tweaks</b> for art styles & layouts.
        </div>
      </div>

      {/* devices */}
      <div className="devices">
        <div className="device-col">
          <div style={{ position: 'relative' }}>
            <IOSDevice dark={t.dark}>
              {onboarded
                ? <Screen ctx={ctx} />
                : <Onboarding onDone={(hue) => { setTheme(nearestTheme(hue)); setOnboarded(true); setTab('home'); }} />}
            </IOSDevice>
            {/* floating feedback */}
            {flash && !flash.listing && (
              <div key={flash.key} style={{ position: 'absolute', top: 120, left: '50%', transform: 'translateX(-50%)', zIndex: 80, pointerEvents: 'none', animation: 'poke-xp 1.3s ease-out forwards', textAlign: 'center' }}>
                <div style={{ fontFamily: 'var(--disp)', fontWeight: 700, fontSize: 30, color: '#fff', background: flash.leveled ? 'var(--violet)' : 'var(--mint)', padding: '8px 18px', borderRadius: 999, boxShadow: '0 10px 24px rgba(0,0,0,.25)' }}>+{flash.amt} XP</div>
                {flash.leveled && <div style={{ marginTop: 8, fontFamily: 'var(--disp)', fontWeight: 700, fontSize: 18, color: 'var(--violet)' }}>LEVEL UP! ⭐</div>}
              </div>
            )}
            {flash && flash.listing && (
              <div key={flash.key} style={{ position: 'absolute', top: 140, left: '50%', transform: 'translateX(-50%)', zIndex: 80, pointerEvents: 'none', animation: 'poke-pop .5s both', width: 250 }}>
                <div style={{ background: 'var(--surface)', borderRadius: 18, padding: 16, boxShadow: '0 16px 40px rgba(0,0,0,.25)', textAlign: 'center', border: '1px solid var(--line)' }}>
                  <div style={{ fontFamily: 'var(--disp)', fontWeight: 600, fontSize: 17 }}>Listed Mochi 🎉</div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)', fontWeight: 600, marginTop: 4 }}>Lv {level} · est. {(level * 0.06).toFixed(1)} ETH</div>
                </div>
              </div>
            )}
          </div>
          <div className="device-cap" style={{ color: t.dark ? '#B7B1C4' : undefined }}><span className="dot" /> iOS app — full wallet, pet & marketplace</div>
        </div>

        <div className="device-col">
          <ExtensionDemo ctx={ctx} />
          <div className="device-cap" style={{ color: t.dark ? '#B7B1C4' : undefined }}><span className="dot" /> Browser extension — quick popup</div>
        </div>
      </div>

      {/* tweaks */}
      <TweaksPanel>
        <TweakSection label="Creature" />
        <TweakRadio label="Art style" value={t.art} options={[{ value: 'clay', label: 'Clay' }, { value: 'flat', label: 'Flat' }, { value: 'gem', label: 'Gem' }, { value: 'pixel', label: 'Pixel' }]} onChange={(v) => setTweak('art', v)} />
        <TweakSlider label="Pet level" value={t.petLevel} min={1} max={40} onChange={(v) => setTweak('petLevel', v)} />
        <TweakSection label="UX variations" />
        <TweakRadio label="Wallet home" value={t.homeLayout} options={[{ value: 'hero', label: 'Pet hero' }, { value: 'compact', label: 'Balance-first' }]} onChange={(v) => setTweak('homeLayout', v)} />
        <TweakSelect label="Strategy market" value={t.mktLayout} options={[{ value: 'roster', label: 'Agent roster' }, { value: 'cards', label: 'Cards grid' }, { value: 'leaderboard', label: 'Leaderboard' }]} onChange={(v) => setTweak('mktLayout', v)} />
        <TweakSection label="Theme" />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
        <TweakButton label="▶ Replay hatch onboarding" onClick={() => { setOnboarded(false); }} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
