// ============================================================
// App.jsx — main shell + routing between screens + Tweaks
// ============================================================
const { useState: useState_A, useEffect: useEffect_A } = React;

function App() {
  const [screen, setScreen] = useState_A(() => localStorage.getItem('pitch.screen') || 'squad');
  const [squadSize, setSquadSize] = useState_A(() => Number(localStorage.getItem('pitch.squadSize')) || 5);
  const [simStyle, setSimStyle] = useState_A(() => localStorage.getItem('pitch.simStyle') || 'live');
  const [layout, setLayout] = useState_A(() => localStorage.getItem('pitch.layout') || 'classic');
  const [theme, setTheme] = useState_A(() => localStorage.getItem('pitch.theme') || 'midnight');
  const [editModeOn, setEditModeOn] = useState_A(false);

  const [collection] = useState_A(() => window.STARTER_COLLECTION);

  // Coins wallet + per-card training levels (persisted).
  const [coins, setCoins] = useState_A(() => {
    const stored = localStorage.getItem('pitch.coins');
    return stored === null ? 200 : Number(stored);
  });
  const [upgrades, setUpgrades] = useState_A(() => {
    const stored = JSON.parse(localStorage.getItem('pitch.upgrades') || '{}');
    window.applyCardUpgrades(stored);
    return stored;
  });
  const [selectedCardId, setSelectedCardId] = useState_A(null);

  useEffect_A(() => { localStorage.setItem('pitch.coins', String(coins)); }, [coins]);
  useEffect_A(() => {
    localStorage.setItem('pitch.upgrades', JSON.stringify(upgrades));
    window.applyCardUpgrades(upgrades);
  }, [upgrades]);

  const awardCoins = (result) => {
    const amount = result === 'W' ? 50 : result === 'D' ? 25 : 10;
    setCoins(c => c + amount);
  };

  const upgradeCard = (cardId) => {
    const lvl = upgrades[cardId] || 0;
    if (lvl >= window.MAX_UPGRADE_LEVEL) return;
    const cost = window.upgradeCost(lvl);
    if (coins < cost) return;
    setCoins(coins - cost);
    setUpgrades({ ...upgrades, [cardId]: lvl + 1 });
  };

  const autoFillSquad = (size) => {
    const formation = window.FORMATIONS[size];
    const used = new Set();
    return formation.slots.map(slot => {
      const best = window.STARTER_COLLECTION
        .map(id => window.CARDS.find(c => c.id === id))
        .filter(c => c && c.pos === slot.pos && !used.has(c.id))
        .sort((a,b) => b.ovr - a.ovr)[0];
      if (best) used.add(best.id);
      return best?.id || null;
    });
  };

  const [squad, setSquad] = useState_A(() => {
    const s = localStorage.getItem('pitch.squad.' + squadSize);
    if (s) {
      const parsed = JSON.parse(s);
      if (parsed.some(Boolean)) return parsed;
    }
    return autoFillSquad(squadSize);
  });
  const [opponent, setOpponent] = useState_A(null);

  useEffect_A(() => { localStorage.setItem('pitch.screen', screen); }, [screen]);
  useEffect_A(() => { localStorage.setItem('pitch.simStyle', simStyle); }, [simStyle]);
  useEffect_A(() => { localStorage.setItem('pitch.layout', layout); window.__layout = layout; }, [layout]);
  useEffect_A(() => { localStorage.setItem('pitch.theme', theme); }, [theme]);
  useEffect_A(() => {
    localStorage.setItem('pitch.squad.' + squadSize, JSON.stringify(squad));
  }, [squad, squadSize]);

  // On squad size change, try to preserve existing placements
  useEffect_A(() => {
    const stored = localStorage.getItem('pitch.squad.' + squadSize);
    if (stored) {
      const parsed = JSON.parse(stored);
      if (parsed.some(Boolean) && parsed.length === window.FORMATIONS[squadSize].slots.length) {
        setSquad(parsed);
        return;
      }
    }
    setSquad(autoFillSquad(squadSize));
  }, [squadSize]);

  // Tweaks protocol
  useEffect_A(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEditModeOn(true);
      if (e.data?.type === '__deactivate_edit_mode') setEditModeOn(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const squadRating = squad.filter(Boolean).length
    ? Math.round(squad.filter(Boolean).map(id => window.CARDS.find(c=>c.id===id)?.ovr||0).reduce((a,b)=>a+b,0) / squad.filter(Boolean).length)
    : 0;

  return (
    <div style={{ minHeight: '100vh', background: theme === 'blueprint' ? '#0a1220' : '#05070a', color: '#e6e8eb' }}>
      <TopNav screen={screen} setScreen={setScreen} squadRating={squadRating} squadSize={squadSize} setSquadSize={setSquadSize} coins={coins} />
      <div>
        {screen === 'collection' && (
          <window.CollectionScreen
            collection={collection}
            onPickCard={id => setSelectedCardId(id)}
            selectedCardId={selectedCardId}
          />
        )}
        {screen === 'squad' && (
          <window.SquadBuilder
            collection={collection}
            squad={squad}
            setSquad={setSquad}
            squadSize={squadSize}
            onStartMatch={() => setScreen('matchmaking')}
          />
        )}
        {screen === 'matchmaking' && (
          <window.MatchmakingScreen
            onPick={(opp) => { setOpponent(opp); setScreen('match'); }}
            playerSquadRating={squadRating}
            squadSize={squadSize}
          />
        )}
        {screen === 'match' && opponent && (
          simStyle === 'live' ? (
            <window.LiveMatchScreen
              playerSquad={squad}
              opponent={opponent}
              onFinish={(result) => { if (result) awardCoins(result); setScreen('squad'); }}
            />
          ) : (
            <window.MatchScreen
              playerSquad={squad}
              opponent={opponent}
              simStyle={simStyle}
              onFinish={(result) => { if (result) awardCoins(result); setScreen('squad'); }}
            />
          )
        )}
      </div>

      {selectedCardId && (
        <UpgradeModal
          cardId={selectedCardId}
          coins={coins}
          upgrades={upgrades}
          onUpgrade={upgradeCard}
          onClose={() => setSelectedCardId(null)}
        />
      )}

      {editModeOn && (
        <TweaksPanel
          squadSize={squadSize} setSquadSize={setSquadSize}
          simStyle={simStyle} setSimStyle={setSimStyle}
          layout={layout} setLayout={setLayout}
          theme={theme} setTheme={setTheme}
        />
      )}
    </div>
  );
}

function TopNav({ screen, setScreen, squadRating, squadSize, setSquadSize, coins }) {
  const inMatch = screen === 'match';
  const tabs = [
    { id: 'squad', label: 'Squad' },
    { id: 'collection', label: 'Collection' },
    { id: 'matchmaking', label: 'Play' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      padding: '14px 32px', borderBottom: '1px solid #1a1f26',
      background: 'linear-gradient(180deg, #0a0d0e, #05070a)',
      position: 'sticky', top: 0, zIndex: 20,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginRight: 24 }}>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 22, color: '#ffc43d',
          letterSpacing: '0.04em', fontWeight: 700,
          textShadow: '0 0 20px rgba(255,196,61,0.4)',
        }}>⚽ PITCH</div>
        <div style={{ fontSize: 9, color: '#5a6169', letterSpacing: '0.2em', textTransform: 'uppercase', fontWeight: 600 }}>Card Battler</div>
      </div>
      {tabs.map(t => (
        <button key={t.id} onClick={() => setScreen(t.id)} style={{
          background: screen === t.id || (t.id === 'matchmaking' && screen === 'match') ? '#1e2329' : 'transparent',
          color: screen === t.id || (t.id === 'matchmaking' && screen === 'match') ? '#fff' : '#8a9099',
          border: 'none', padding: '8px 16px', fontSize: 13,
          borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
          fontWeight: 600, letterSpacing: '0.04em',
        }}>{t.label}</button>
      ))}
      <div style={{ flex: 1 }} />
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '6px 12px', background: '#0e1114', border: '1px solid #1a1f26', borderRadius: 8,
        marginRight: 8,
      }}>
        <div style={{ fontSize: 9, color: '#5a6169', letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>Coins</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: '#ffc43d', lineHeight: 1, fontWeight: 700, textShadow: '0 0 12px rgba(255,196,61,0.35)' }}>⦾ {coins ?? 0}</div>
      </div>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 14,
        padding: '6px 14px', background: '#0e1114', border: '1px solid #1a1f26', borderRadius: 8,
      }}>
        <div>
          <div style={{ fontSize: 9, color: '#5a6169', letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>Squad</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: '#fff', lineHeight: 1, fontWeight: 700 }}>{squadRating || '—'}</div>
        </div>
        <div style={{ width: 1, height: 22, background: '#1a1f26' }} />
        <div>
          <div style={{ fontSize: 9, color: '#5a6169', letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 3 }}>Size</div>
          <div style={{ display: 'flex', gap: 3 }}>
            {[5, 7, 11].map(n => {
              const active = squadSize === n;
              return (
                <button
                  key={n}
                  onClick={() => !inMatch && setSquadSize(n)}
                  disabled={inMatch}
                  title={inMatch ? 'Finish the match first' : `Switch to ${n}v${n}`}
                  style={{
                    background: active ? '#ffc43d' : 'transparent',
                    color: active ? '#0a0d0e' : (inMatch ? '#3a4048' : '#c4ccd4'),
                    border: `1px solid ${active ? '#ffc43d' : '#2a3139'}`,
                    padding: '3px 8px', fontSize: 11, borderRadius: 3,
                    cursor: inMatch ? 'not-allowed' : 'pointer',
                    fontFamily: 'var(--font-display)', fontWeight: 700,
                    letterSpacing: '0.04em', lineHeight: 1,
                  }}
                >{n}v{n}</button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function TweaksPanel({ squadSize, setSquadSize, simStyle, setSimStyle, layout, setLayout, theme, setTheme }) {
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, width: 280,
      background: 'linear-gradient(180deg, #0e1114, #05070a)',
      border: '1px solid #2a3139', borderRadius: 12,
      padding: 18, zIndex: 100,
      boxShadow: '0 20px 60px rgba(0,0,0,0.6), 0 0 40px rgba(255,196,61,0.1)',
      fontFamily: 'var(--font-sans)',
    }}>
      <div style={{
        fontSize: 10, color: '#ffc43d', letterSpacing: '0.18em',
        textTransform: 'uppercase', fontWeight: 700, marginBottom: 14,
      }}>◆ Tweaks</div>

      <TweakRow label="Squad Size">
        {[5, 7, 11].map(n => (
          <Pill key={n} active={squadSize === n} onClick={()=>setSquadSize(n)}>{n}v{n}</Pill>
        ))}
      </TweakRow>

      <TweakRow label="Match Mode">
        <Pill active={simStyle === 'live'} onClick={()=>setSimStyle('live')}>⚡ Live (play)</Pill>
        <Pill active={simStyle === 'hybrid'} onClick={()=>setSimStyle('hybrid')}>Replay: Pitch + Feed</Pill>
        <Pill active={simStyle === 'feed'} onClick={()=>setSimStyle('feed')}>Replay: Feed</Pill>
        <Pill active={simStyle === 'pitch_only'} onClick={()=>setSimStyle('pitch_only')}>Replay: Pitch</Pill>
      </TweakRow>

      <TweakRow label="Card Layout">
        <Pill active={layout === 'classic'} onClick={()=>setLayout('classic')}>Classic (Chrome)</Pill>
        <Pill active={layout === 'minimal'} onClick={()=>setLayout('minimal')}>Minimal</Pill>
      </TweakRow>

      <TweakRow label="Theme">
        <Pill active={theme === 'midnight'} onClick={()=>setTheme('midnight')}>Midnight</Pill>
        <Pill active={theme === 'blueprint'} onClick={()=>setTheme('blueprint')}>Blueprint</Pill>
      </TweakRow>
    </div>
  );
}

function TweakRow({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 9, color: '#5a6169', letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>{label}</div>
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>{children}</div>
    </div>
  );
}
function Pill({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      background: active ? '#ffc43d' : 'transparent',
      color: active ? '#0a0d0e' : '#8a9099',
      border: `1px solid ${active ? '#ffc43d' : '#1e2329'}`,
      padding: '5px 10px', fontSize: 10, borderRadius: 4,
      cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, letterSpacing: '0.04em',
    }}>{children}</button>
  );
}

function UpgradeModal({ cardId, coins, upgrades, onUpgrade, onClose }) {
  const card = window.CARDS.find(c => c.id === cardId);
  if (!card) return null;
  const lvl = upgrades[cardId] || 0;
  const atMax = lvl >= window.MAX_UPGRADE_LEVEL;
  const cost = atMax ? 0 : window.upgradeCost(lvl);
  const canAfford = coins >= cost && !atMax;
  const layout = window.__layout || 'classic';

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(0,0,0,0.8)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'linear-gradient(180deg, #0e1114, #0a0d0e)',
        border: '1px solid #2a3139', borderRadius: 14,
        padding: 24, width: 560, maxWidth: '100%',
        display: 'flex', gap: 24, boxShadow: '0 20px 80px rgba(0,0,0,0.7)',
      }}>
        <div style={{ flexShrink: 0 }}>
          <window.PlayerCard cardId={cardId} size="md" interactive={false} layout={layout} />
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ fontSize: 10, color: '#ffc43d', letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700 }}>◆ Train Card</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, color: '#fff', fontWeight: 600, marginTop: 4, lineHeight: 1.1 }}>{card.name}</div>
          <div style={{ fontSize: 11, color: '#8a9099', letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginTop: 6 }}>
            Level {lvl} / {window.MAX_UPGRADE_LEVEL}
          </div>
          <div style={{
            marginTop: 14, padding: '10px 12px',
            background: '#05070a', border: '1px solid #1a1f26', borderRadius: 8,
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10,
            fontFamily: 'var(--font-mono)', fontSize: 12,
          }}>
            {[['PAC', card.pac], ['SHO', card.sho], ['PAS', card.pas], ['DEF', card.def]].map(([k, v]) => (
              <div key={k} style={{ textAlign: 'center' }}>
                <div style={{ color: '#5a6169', fontSize: 9, letterSpacing: '0.12em', fontWeight: 700 }}>{k}</div>
                <div style={{ color: '#e6e8eb', fontSize: 16, fontWeight: 700 }}>
                  {v}{!atMax && <span style={{ color: '#58d07a', fontSize: 11 }}> +2</span>}
                </div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12, color: '#8a9099', marginTop: 14, lineHeight: 1.5 }}>
            {atMax
              ? 'This card is maxed out.'
              : 'Each training session adds +2 to every stat (capped at 99) and raises the overall rating.'}
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button onClick={onClose} style={{
              flex: 1, background: 'transparent', border: '1px solid #2a3139',
              color: '#c4ccd4', padding: '10px', borderRadius: 6,
              cursor: 'pointer', fontSize: 12, fontWeight: 600, letterSpacing: '0.04em',
              fontFamily: 'var(--font-sans)',
            }}>Close</button>
            <button
              onClick={() => canAfford && onUpgrade(cardId)}
              disabled={!canAfford}
              style={{
                flex: 2,
                background: canAfford ? 'linear-gradient(135deg, #ffc43d, #ff9500)' : '#1a1f26',
                color: canAfford ? '#0a0d0e' : '#5a6169',
                border: 'none', padding: '10px', borderRadius: 6,
                cursor: canAfford ? 'pointer' : 'not-allowed',
                fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 700,
                letterSpacing: '0.04em',
              }}
            >
              {atMax ? 'Maxed Out' : `Train · ⦾ ${cost}`}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.App = App;
