// Shared design tokens
window.T = {
  navy950:  '#080C14',
  navy900:  '#0D1420',
  navy800:  '#111B2E',
  navy700:  '#172340',
  navy600:  '#1E2E52',
  gold400:  '#F5C842',
  gold500:  '#E8B820',
  gold600:  '#C99A10',
  green:    '#2D8C4E',
  greenLt:  '#37A85F',
  card:     '#1A2236',
  cardEmpty:'#1E2840',
  border:   '#232E45',
  grayMuted:'#4A5568',
  text:     '#F0F4FF',
  textSec:  '#8896B0',
  textMute: '#4A5568',
  red:      '#E87A7A',
};
const T = window.T;

// ─── Team colors (primary = fill, secondary = stroke/border) ─────────
// Used for crest placeholders on the reveal screen AND player dots in-game.
// Covers teams currently in the matches database. Add new entries as matches are added.
window.TEAM_COLORS = {
  // ── Premier League ──
  'Arsenal':                   { primary: '#EF0107', secondary: '#FFFFFF' },
  'Chelsea':                   { primary: '#034694', secondary: '#FFFFFF' },
  'Liverpool':                 { primary: '#C8102E', secondary: '#FFFFFF' },
  'Manchester City':           { primary: '#6CABDD', secondary: '#FFFFFF' },
  'Manchester United':         { primary: '#DA020E', secondary: '#FBE122' },
  'Tottenham Hotspur':         { primary: '#FFFFFF', secondary: '#132257' },
  'Leicester':                 { primary: '#003090', secondary: '#FDBE11' },
  'Wolverhampton Wanderers':   { primary: '#FDB913', secondary: '#231F20' },

  // ── La Liga ──
  'Real Madrid':               { primary: '#FFFFFF', secondary: '#FEBE10' },
  'Barcelona':                 { primary: '#A50044', secondary: '#004D98' },
  'Atlético Madrid':           { primary: '#CB3524', secondary: '#FFFFFF' },

  // ── Serie A ──
  'Inter':                     { primary: '#0068A8', secondary: '#000000' },
  'Milan':                     { primary: '#FB090B', secondary: '#000000' },
  'Juventus':                  { primary: '#FFFFFF', secondary: '#000000' },

  // ── Bundesliga ──
  'Bayern Munich':             { primary: '#DC052D', secondary: '#FFFFFF' },
  'Borussia Dortmund':         { primary: '#FDE100', secondary: '#000000' },
  'Bayer Leverkusen':          { primary: '#E32221', secondary: '#000000' },
  'RB Leipzig':                { primary: '#DD0741', secondary: '#FFFFFF' },

  // ── Ligue 1 ──
  'Paris Saint-Germain':       { primary: '#004170', secondary: '#DA291C' },
  'PSG':                       { primary: '#004170', secondary: '#DA291C' },

  // ── Other European ──
  'Ajax':                      { primary: '#FFFFFF', secondary: '#D2122E' },
  'Benfica':                   { primary: '#E30613', secondary: '#FFFFFF' },

  // ── National teams ──
  'Argentina':                 { primary: '#75AADB', secondary: '#FFFFFF' },
  'Belgium':                   { primary: '#ED2939', secondary: '#FAE042' },
  'Brazil':                    { primary: '#FEDF00', secondary: '#009B3A' },
  'Croatia':                   { primary: '#FF0000', secondary: '#FFFFFF' },
  'England':                   { primary: '#FFFFFF', secondary: '#CE1124' },
  'France':                    { primary: '#002395', secondary: '#FFFFFF' },
  'Germany':                   { primary: '#000000', secondary: '#DD0000' },
  'Ghana':                     { primary: '#FCD116', secondary: '#CE1126' },
  'Italy':                     { primary: '#0066CC', secondary: '#FFFFFF' },
  'Netherlands':               { primary: '#FF6C00', secondary: '#FFFFFF' },
  'Portugal':                  { primary: '#C41E3A', secondary: '#006600' },
  'Spain':                     { primary: '#AA151B', secondary: '#F1BF00' },
  'Sweden':                    { primary: '#006AA7', secondary: '#FECC00' },
  'Uruguay':                   { primary: '#5CBCEC', secondary: '#000000' },
};

// Returns { primary, secondary } for a team name, or fallback colors if unknown.
// Side fallback: home = red, away = navy (the old default).
window.getTeamColors = function(teamName, isHome = true) {
  if (teamName && window.TEAM_COLORS[teamName]) {
    return window.TEAM_COLORS[teamName];
  }
  return isHome
    ? { primary: '#C41E3A', secondary: '#F5C842' }
    : { primary: '#08306B', secondary: '#F5C842' };
};

// If home and away teams share the same primary color, the away team uses
// its secondary as the primary so users can tell the dots apart on the pitch.
window.getMatchColors = function(homeTeam, awayTeam) {
  const home = window.getTeamColors(homeTeam, true);
  let away = window.getTeamColors(awayTeam, false);
  if (home.primary.toUpperCase() === away.primary.toUpperCase()) {
    // Swap primary/secondary for the away team so there's visual contrast
    away = { primary: away.secondary, secondary: away.primary };
  }
  return { home, away };
};

// Hex token icon
function HexIcon({ size = 14, fill = T.gold500 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M12 2.5l8.5 4.9v9.2L12 21.5 3.5 16.6V7.4L12 2.5z"
        fill={fill} stroke="rgba(245,200,66,0.5)" strokeWidth="0.8"/>
    </svg>
  );
}

// Wordmark
function Wordmark({ size = 28 }) {
  return (
    <div style={{
      fontFamily: 'Bakbak One, sans-serif',
      fontSize: size, lineHeight: 1, letterSpacing: '0.06em', color: T.text,
    }}>
      FUT<span style={{ color: T.gold500 }}>B</span>ALL
    </div>
  );
}

// Plain title (used on inner screens — STATS, PLAY, etc.)
function PageWordmark({ text }) {
  return (
    <div style={{
      fontFamily: 'Bakbak One, sans-serif',
      fontSize: 22, letterSpacing: '0.06em', color: T.text,
    }}>{text}</div>
  );
}

// Token pill — "240 Tokens"
function TokenPill({ amount }) {
  // If no amount provided, self-fetch and listen for global updates
  const [autoTokens, setAutoTokens] = React.useState(null);
  const isAuto = amount === undefined;

  React.useEffect(() => {
    if (!isAuto) return;
    let mounted = true;
    const load = () => {
      if (!window.fetchTokens) return;
      window.fetchTokens()
        .then(t => { if (mounted) setAutoTokens(t?.balance ?? 0); })
        .catch(() => {});
    };
    load();
    const onUpdate = () => load();
    window.addEventListener('tokens:updated', onUpdate);
    return () => {
      mounted = false;
      window.removeEventListener('tokens:updated', onUpdate);
    };
  }, [isAuto]);

  const display = isAuto ? (autoTokens ?? '—') : (amount ?? '—');

  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      height: 30, padding: '0 12px',
      borderRadius: 999,
      background: 'rgba(232,184,32,0.10)',
      border: `1px solid ${T.gold600}`,
      color: T.gold400, fontFamily: 'DM Sans',
      fontSize: 12.5, fontWeight: 600,
    }}>
      <HexIcon size={12} />
      {display} Tokens
    </div>
  );
}

// Top app header — shows token balance when signed in, nothing when anonymous
function AppHeader({ left }) {
  const [tokens, setTokens] = React.useState(null);
  const [signedIn, setSignedIn] = React.useState(false);

  React.useEffect(() => {
    let mounted = true;
    const load = () => {
      window.isSignedIn().then(yes => {
        if (!mounted) return;
        setSignedIn(yes);
        if (yes && window.fetchTokens) {
          window.fetchTokens()
            .then(t => { if (mounted) setTokens(t?.balance ?? 0); })
            .catch(() => {});
        }
      });
    };
    load();
    const onUpdate = () => load();
    window.addEventListener('tokens:updated', onUpdate);
    return () => {
      mounted = false;
      window.removeEventListener('tokens:updated', onUpdate);
    };
  }, []);

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '12px 0 18px',
    }}>
      {left}
      {signedIn && <TokenPill amount={tokens ?? '—'} />}
    </div>
  );
}

// Section heading (Bakbak)
function SectionLabel({ children, size = 20, top = 18, bottom = 12 }) {
  return (
    <h2 style={{
      margin: 0, marginTop: top, marginBottom: bottom,
      fontFamily: 'Bakbak One, sans-serif',
      fontSize: size, color: T.text, letterSpacing: '0.03em', fontWeight: 400,
    }}>{children}</h2>
  );
}

// Page title + sub
function PageTitleBlock({ title, sub }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <h1 style={{
        margin: 0, marginBottom: 4,
        fontFamily: 'Bakbak One, sans-serif',
        fontSize: 28, color: T.text, letterSpacing: '0.02em', fontWeight: 400,
      }}>{title}</h1>
      <div style={{ fontSize: 13, color: T.textSec }}>{sub}</div>
    </div>
  );
}

// Bottom nav icons
const Bar = {
  home: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 10.5L12 3l9 7.5V20a1 1 0 01-1 1h-5v-6h-6v6H4a1 1 0 01-1-1v-9.5z"/>
    </svg>
  ),
  stats: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 19V10M10 19V5M16 19v-7M22 19H2"/>
    </svg>
  ),
  play: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9"/>
      <path d="M12 3v18M3 12h18M7 5l10 14M17 5L7 19"/>
    </svg>
  ),
  rank: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9V3h12v6a6 6 0 01-12 0zM9 21h6M12 15v6M4 3h2M18 3h2"/>
    </svg>
  ),
  achievements: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="8" r="6"/>
      <path d="M8.21 13.89L7 23l5-3 5 3-1.21-9.12"/>
    </svg>
  ),
  profile: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="8" r="4"/>
      <path d="M4 21a8 8 0 0116 0"/>
    </svg>
  ),
};

function BottomNav({ active, onChange }) {
  const items = [
    { id: 'home',         label: 'Home',    icon: Bar.home },
    { id: 'stats',        label: 'Stats',   icon: Bar.stats },
    { id: 'play',         label: 'Play',    icon: Bar.play },
    { id: 'achievements', label: 'Trophies',  icon: Bar.achievements },
    { id: 'profile',      label: 'Profile', icon: Bar.profile },
  ];
  return (
    <nav style={{
      position: 'absolute',
      bottom: 'max(22px, calc(22px + env(safe-area-inset-bottom)))',
      left: 16, right: 16,
      backdropFilter: 'blur(24px) saturate(180%)',
      WebkitBackdropFilter: 'blur(24px) saturate(180%)',
      background: 'rgba(20,28,48,0.55)',
      border: '1px solid rgba(255,255,255,0.08)',
      borderRadius: 28,
      padding: '10px 8px',
      display: 'flex', justifyContent: 'space-around', alignItems: 'center',
      boxShadow: '0 10px 40px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.08)',
      zIndex: 20,
    }}>
      {items.map(it => {
        const isActive = active === it.id;
        return (
          <button key={it.id} onClick={() => onChange(it.id)} style={{
            flex: 1, border: 'none', background: 'transparent', cursor: 'pointer',
            padding: '8px 4px', borderRadius: 20,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            color: isActive ? T.gold400 : T.textMute,
            backgroundColor: isActive ? 'rgba(232,184,32,0.12)' : 'transparent',
            boxShadow: isActive ? 'inset 0 0 0 1px rgba(232,184,32,0.25)' : 'none',
            transition: 'all 250ms cubic-bezier(0.2,0.9,0.3,1)',
          }}>
            {it.icon}
            <span style={{
              fontFamily: 'DM Sans', fontSize: 9.5, fontWeight: 600, letterSpacing: '0.03em',
              color: isActive ? T.gold400 : T.textMute,
            }}>{it.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// Phone shell — simulated device on desktop, full viewport on mobile
function Phone({ children }) {
  const [isMobile, setIsMobile] = React.useState(false);

  React.useEffect(() => {
    const check = () => setIsMobile(window.innerWidth <= 500);
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  // Mobile: fill the real viewport, no fake phone chrome
  if (isMobile) {
    return (
      <div style={{
        width: '100vw',
        height: '100dvh',
        maxHeight: '100dvh',
        background: T.navy950,
        position: 'fixed', inset: 0,
        display: 'flex', flexDirection: 'column',
        fontFamily: 'DM Sans',
        overflow: 'hidden',
      }}>
        {children}
        <div style={{
          position:'absolute', bottom: 8, left:'50%', transform:'translateX(-50%)',
          width: 134, height: 5, background:'rgba(255,255,255,0.15)',
          borderRadius: 100, zIndex: 30, pointerEvents: 'none',
        }}/>
      </div>
    );
  }

  // Desktop: simulated iPhone frame (for dev preview)
  return (
    <div style={{
      width: 393, height: 852, background: T.navy950,
      borderRadius: 48, overflow: 'hidden', position: 'relative',
      border: '8px solid #1a1a1a',
      boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
      display: 'flex', flexDirection: 'column',
      fontFamily: 'DM Sans',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '14px 28px 6px', fontSize: 15, fontWeight: 600, color: T.text,
        flexShrink: 0,
      }}>
        <span>9:05</span>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <svg width="16" height="11" viewBox="0 0 16 11"><path d="M14 0v11M11 3v8M8 5v6M5 7v4M2 9v2" stroke="#fff" strokeWidth="1.5" strokeLinecap="round"/></svg>
          <svg width="16" height="11" viewBox="0 0 16 11" fill="#fff"><path d="M8 0a8 8 0 016 2.7l-1 1a6.5 6.5 0 00-10 0l-1-1A8 8 0 018 0zm0 3a5 5 0 014 1.7l-1 1a3.5 3.5 0 00-6 0l-1-1A5 5 0 018 3zm0 3.2a2 2 0 011.5.7l-1.5 1.5L6.5 6.9A2 2 0 018 6.2z"/></svg>
          <svg width="26" height="12" viewBox="0 0 26 12"><rect x="0.5" y="0.5" width="22" height="11" rx="3" stroke="#fff" strokeOpacity="0.4" fill="none"/><rect x="2" y="2" width="14" height="8" rx="1.5" fill="#fff"/><rect x="23" y="4" width="2" height="4" rx="1" fill="#fff" fillOpacity="0.4"/></svg>
        </div>
      </div>
      {children}
      <div style={{
        position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)',
        width: 134, height: 5, background: 'rgba(255,255,255,0.4)',
        borderRadius: 100, zIndex: 30,
      }} />
    </div>
  );
}

// Scrollable content region
function Content({ children }) {
  return (
    <div className="no-scrollbar" style={{
      flex: 1, overflowY: 'auto',
      padding: '8px 20px 130px',
      paddingTop: 'max(8px, env(safe-area-inset-top))',
      paddingBottom: 'max(130px, calc(130px + env(safe-area-inset-bottom)))',
      WebkitOverflowScrolling: 'touch',
    }}>
      {children}
    </div>
  );
}

Object.assign(window, {
  HexIcon, Wordmark, PageWordmark, TokenPill, AppHeader,
  SectionLabel, PageTitleBlock, BottomNav, Phone, Content, Bar,
});
