/* Capitán Fantasy — Squad (Mi Equipo): pitch, formation, budget, captain, coach, bench, selector */

function TopHeader({ title, sub, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '52px 18px 12px', flexShrink: 0 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <h1 style={{ fontSize: 24, fontWeight: 900, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</h1>
        {sub && <div style={{ fontSize: 13, color: C.mut, marginTop: 1, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>}
      </div>
      {right && <div style={{ flexShrink: 0 }}>{right}</div>}
    </div>
  );
}

function BudgetBar({ used, total }) {
  const pct = Math.min(100, (used / total) * 100);
  const remaining = total - used;
  const over = remaining < 0;
  return (
    <div style={{ padding: '0 18px', marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 9 }}>
        <span style={{ fontSize: 11, color: C.mut, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>Presupuesto</span>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
          <span className="num" style={{ fontWeight: 800, fontSize: 16, color: over ? C.destructive : C.fg }}>{remaining.toFixed(1)}</span>
          <span style={{ fontSize: 12, color: C.mut }}>/ {total}</span>
        </div>
      </div>
      <div style={{ height: 4, borderRadius: 999, background: 'hsl(0 0% 100% / 0.07)', overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: over ? C.destructive : C.gold, borderRadius: 999, transition: 'width .4s' }} />
      </div>
    </div>
  );
}

function FormationPicker({ value, onChange }) {
  const forms = Object.keys(window.CF.FORMATIONS);
  return (
    <div className="noscroll" style={{ display: 'flex', gap: 6, overflowX: 'auto', padding: '0 18px', marginBottom: 18 }}>
      {forms.map((f) => {
        const on = value === f;
        return (
          <button key={f} onClick={() => onChange(f)} className="num" style={{
            flexShrink: 0, padding: '7px 14px', borderRadius: 9, cursor: 'pointer', fontFamily: 'inherit',
            fontWeight: 700, fontSize: 13, letterSpacing: 0.3, transition: 'all .15s', whiteSpace: 'nowrap',
            border: `1px solid ${on ? C.primary : 'hsl(0 0% 100% / 0.10)'}`,
            background: on ? C.primary : 'transparent',
            color: on ? '#fff' : C.mut,
          }}>{f}</button>
        );
      })}
    </div>
  );
}

// The pitch — minimal: near-black field, hairline lines, no stripes/glow
function Pitch({ lineup, livePoints, onSlot, captain }) {
  const CF = window.CF;
  const form = CF.FORMATIONS[lineup.formation];
  const rows = [
    { pos: 'FWD', n: form.FWD }, { pos: 'MID', n: form.MID }, { pos: 'DEF', n: form.DEF }, { pos: 'GK', n: form.GK },
  ];
  // build slot → player from starters grouped by pos
  const byPos = { GK: [], DEF: [], MID: [], FWD: [] };
  lineup.starters.forEach((id) => { const p = CF.pById(id); if (p) byPos[p.pos].push(p); });

  const L = 'hsl(0 0% 100% / 0.09)';
  const box = { position: 'absolute', left: '50%', transform: 'translateX(-50%)', width: 104, height: 30, border: `1px solid ${L}` };

  return (
    <div style={{ padding: '0 18px', marginBottom: 18 }}>
      <div style={{
        borderRadius: 20, position: 'relative', overflow: 'hidden', padding: '24px 10px 20px',
        background: 'hsl(155 18% 8%)', border: '1px solid hsl(0 0% 100% / 0.07)',
      }}>
        {/* minimal field markings */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
          <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', height: 1, background: L }} />
          <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)', width: 72, height: 72, borderRadius: 999, border: `1px solid ${L}` }} />
          <div style={{ ...box, top: 0, borderTop: 'none', borderBottomLeftRadius: 8, borderBottomRightRadius: 8 }} />
          <div style={{ ...box, bottom: 0, borderBottom: 'none', borderTopLeftRadius: 8, borderTopRightRadius: 8 }} />
        </div>

        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 18 }}>
          {rows.map((row) => (
            <div key={row.pos} style={{ display: 'flex', justifyContent: 'center', gap: 'min(7vw, 26px)' }}>
              {Array.from({ length: row.n }).map((_, i) => {
                const p = byPos[row.pos][i];
                return p
                  ? <PitchPlayer key={p.id} p={p} isCaptain={captain === p.id} points={livePoints ? p.form[4] : null} onClick={() => onSlot(row.pos, p)} />
                  : <EmptySlot key={row.pos + i} pos={row.pos} onClick={() => onSlot(row.pos, null)} />;
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CoachRow({ coachId, onClick }) {
  const c = window.CF.cById(coachId);
  return (
    <div style={{ padding: '0 18px', marginBottom: 18 }}>
      <div onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 2px', cursor: onClick ? 'pointer' : 'default', borderTop: `1px solid ${C.cardBorder}`, borderBottom: `1px solid ${C.cardBorder}` }}>
        <Icon name="whistle" size={19} color={C.mut} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10.5, color: C.mut, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>Director Técnico</div>
          {c ? <div style={{ fontWeight: 600, fontSize: 15, marginTop: 1 }}>{c.name} <span style={{ color: C.mut, fontWeight: 400 }}>· {window.CF.teams[c.team].name}</span></div>
             : <div style={{ fontWeight: 600, fontSize: 15, color: C.mut }}>Elegir DT</div>}
        </div>
        {c && <span className="num" style={{ fontWeight: 700, color: C.fg, fontSize: 15 }}>{c.cost}</span>}
        <Icon name="chevR" size={17} color={C.mut} />
      </div>
    </div>
  );
}

function Bench({ lineup, onSlot }) {
  const CF = window.CF;
  return (
    <div style={{ padding: '0 18px', marginBottom: 22 }}>
      <div style={{ fontSize: 11, color: C.mut, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 12, paddingLeft: 2 }}>Banca</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        {lineup.bench.map((id) => {
          const p = CF.pById(id);
          return (
            <button key={id} onClick={() => onSlot('bench', p)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, padding: '4px 0', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
              <PlayerAvatar player={p} size={38} />
              <span style={{ fontSize: 11.5, fontWeight: 600, color: C.fg, textAlign: 'center', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%' }}>{p.name.split(' ').slice(-1)[0]}</span>
              <span style={{ fontSize: 9.5, fontWeight: 700, color: C.mut, letterSpacing: 0.4 }}>{posLabel[p.pos]}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// Player selector sheet
function PlayerSelector({ pos, current, onPick, onClose, budgetLeft, ownedIds }) {
  const CF = window.CF;
  const [sortBy, setSortBy] = React.useState('pts');
  let pool = CF.players.filter((p) => p.pos === pos);
  pool = pool.sort((a, b) => sortBy === 'pts' ? b.pts - a.pts : sortBy === 'cost' ? b.cost - a.cost : a.cost - b.cost);
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 70, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)', animation: 'fadeIn .2s' }} />
      <div style={{ position: 'relative', background: 'hsl(var(--popover))', borderTopLeftRadius: 22, borderTopRightRadius: 22, borderTop: `1px solid ${C.border}`, maxHeight: '82%', display: 'flex', flexDirection: 'column', animation: 'sheetUp .3s cubic-bezier(.2,.8,.2,1)' }}>
        <div style={{ padding: '14px 18px 10px', borderBottom: `1px solid ${C.border}` }}>
          <div style={{ width: 38, height: 4, borderRadius: 9, background: C.border, margin: '0 auto 14px' }} />
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <PosPill pos={pos} size="lg" />
              <h3 style={{ fontSize: 17, fontWeight: 800, whiteSpace: 'nowrap' }}>Elegir jugador</h3>
            </div>
            <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 999, background: C.secondary, border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><Icon name="x" size={17} color={C.mut} /></button>
          </div>
          <div style={{ display: 'flex', gap: 7, marginTop: 12 }}>
            {[['pts', 'Puntos'], ['cost', 'Caro'], ['costlow', 'Barato']].map(([k, l]) => (
              <button key={k} onClick={() => setSortBy(k)} style={{ padding: '5px 12px', borderRadius: 999, fontFamily: 'inherit', fontWeight: 600, fontSize: 12, cursor: 'pointer', border: `1px solid ${sortBy === k ? C.primary : C.border}`, background: sortBy === k ? C.primary.replace('hsl', 'hsla').replace(')', ' / 0.12)') : 'transparent', color: sortBy === k ? C.primary : C.mut }}>{l}</button>
            ))}
          </div>
        </div>
        <div className="noscroll" style={{ flex: 1, overflowY: 'auto', padding: '12px 18px 28px' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {pool.map((p) => {
              const owned = ownedIds.includes(p.id);
              const affordable = p.cost <= budgetLeft + (current ? current.cost : 0);
              return (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 12, background: C.card, border: `1px solid ${current && current.id === p.id ? C.primary : C.cardBorder}`, opacity: owned && !(current && current.id === p.id) ? 0.4 : 1 }}>
                  <PlayerAvatar player={p} size={36} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14.5 }}>{p.name}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 3 }}>
                      <TierBadge tier={p.tier} small />
                      <span style={{ fontSize: 11.5, color: C.mut }}>{window.CF.teams[p.team].name}</span>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="num" style={{ fontWeight: 800, fontSize: 14, color: C.gold }}>{p.cost}</div>
                    <div className="num" style={{ fontSize: 11, color: C.mut }}>{p.pts} pts</div>
                  </div>
                  <button disabled={owned && !(current && current.id === p.id)} onClick={() => onPick(p)} style={{ width: 34, height: 34, borderRadius: 10, flexShrink: 0, border: 'none', cursor: owned ? 'default' : 'pointer', background: current && current.id === p.id ? C.success : affordable && !owned ? C.primary : C.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name={current && current.id === p.id ? 'check' : owned ? 'check' : 'plus'} size={17} color={current && current.id === p.id ? '#fff' : owned ? C.mut : '#fff'} />
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function SquadScreen() {
  const CF = window.CF;
  const [lineup, setLineup] = React.useState(CF.myLineup);
  const [livePoints, setLivePoints] = React.useState(true);
  const [selector, setSelector] = React.useState(null); // {pos, current}
  const [saved, setSaved] = React.useState(true);

  const allIds = [...lineup.starters, ...lineup.bench];
  const used = allIds.reduce((s, id) => s + (CF.pById(id)?.cost || 0), 0) + (CF.cById(lineup.coach)?.cost || 0);

  const openSelector = (pos, current) => { if (pos === 'bench') return; setSelector({ pos, current }); };
  const pickPlayer = (p) => {
    setLineup((L) => {
      const starters = L.starters.filter((id) => CF.pById(id).pos !== p.pos || id !== (selector.current?.id));
      // replace one of same pos: simplest — remove current then add
      let next = L.starters.slice();
      if (selector.current) next = next.map((id) => id === selector.current.id ? p.id : id);
      else next = [...next, p.id];
      return { ...L, starters: next };
    });
    setSaved(false);
    setSelector(null);
  };

  return (
    <div className="animate-slide-up">
      <TopHeader title="Mi Equipo" sub="Jornada 14 · cierra en 2h 14m" right={
        <button onClick={() => setLivePoints((v) => !v)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 999, border: `1px solid ${livePoints ? C.destructive : C.border}`, background: livePoints ? C.destructive.replace('hsl', 'hsla').replace(')', ' / 0.14)') : C.secondary, color: livePoints ? C.destructive : C.mut, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 12, whiteSpace: 'nowrap' }}>
          {livePoints && <LiveDot size={6} />}{livePoints ? 'Puntos live' : 'Ver puntos'}
        </button>
      } />

      <BudgetBar used={used} total={CF.TOTAL_BUDGET} />
      <FormationPicker value={lineup.formation} onChange={(f) => { setLineup((L) => ({ ...L, formation: f })); setSaved(false); }} />
      <Pitch lineup={lineup} livePoints={livePoints} captain={lineup.captain} onSlot={openSelector} />
      <CoachRow coachId={lineup.coach} onClick={() => {}} />
      <Bench lineup={lineup} onSlot={openSelector} />

      <div style={{ padding: '0 18px 24px', display: 'flex', gap: 10 }}>
        <Btn variant="secondary" icon="sparkle" style={{ flex: 1 }}>Auto 11</Btn>
        <Btn variant={saved ? 'pitch' : 'gold'} icon={saved ? 'check' : 'save'} style={{ flex: 1 }} onClick={() => setSaved(true)}>{saved ? 'Guardado' : 'Guardar equipo'}</Btn>
      </div>

      {selector && <PlayerSelector pos={selector.pos} current={selector.current} budgetLeft={CF.TOTAL_BUDGET - used} ownedIds={allIds} onPick={pickPlayer} onClose={() => setSelector(null)} />}
    </div>
  );
}

Object.assign(window, { TopHeader, BudgetBar, FormationPicker, Pitch, CoachRow, Bench, PlayerSelector, SquadScreen });
