// Sticker book - premium binder layout with real two-page spreads
const { useState: useStateB, useMemo: useMemoB, useRef: useRefB, useEffect: useEffectB } = React;

const TEAM_QUOTES = {
  arg: {
    quote: 'We do not play for the shirt, we play for the soul behind it.',
    author: 'Lionel Messi',
  },
  bra: {
    quote: 'Football here is rhythm, joy, and courage in motion.',
    author: 'Selecao archive',
  },
  fra: {
    quote: 'Elegance matters, but the win must still be ruthless.',
    author: 'Les Bleus archive',
  },
  eng: {
    quote: 'History follows the teams that keep showing up for it.',
    author: 'Three Lions archive',
  },
};

const BINDER_PAGE_SIZE = 9;
const MOBILE_BREAKPOINT = 720;
const STACKED_BINDER_BREAKPOINT = 1100;

function chunkItems(items, size) {
  const chunks = [];
  for (let index = 0; index < items.length; index += size) {
    chunks.push(items.slice(index, index + size));
  }
  return chunks;
}

function getTeamFlag(team) {
  return team?.displayFlag || team?.flag || '';
}

function StickerBook({ collection, onStickerClick, initialTeam, onViewedNew }) {
  const data = window.WC_DATA;
  const [teamId, setTeamId] = useStateB(initialTeam || data.TEAMS[0].id);
  const [flipping, setFlipping] = useStateB(false);
  const [flipDirection, setFlipDirection] = useStateB('next');
  const [viewportWidth, setViewportWidth] = useStateB(() =>
    typeof window !== 'undefined' ? window.innerWidth : 1280
  );
  const [viewMode, setViewMode] = useStateB(() =>
    typeof window !== 'undefined' && window.innerWidth <= MOBILE_BREAKPOINT ? 'grid' : 'binder'
  );
  const [showMissing, setShowMissing] = useStateB(true);
  const [spreadStartIndex, setSpreadStartIndex] = useStateB(0);
  const teamsScrollerRef = useRefB(null);
  const isMobile = viewportWidth <= MOBILE_BREAKPOINT;
  const isStackedBinder = viewportWidth <= STACKED_BINDER_BREAKPOINT;

  useEffectB(() => {
    function handleResize() {
      setViewportWidth(window.innerWidth);
    }

    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffectB(() => {
    if (isMobile && viewMode !== 'grid') {
      setViewMode('grid');
    }
  }, [isMobile, viewMode]);

  const totalByTeam = useMemoB(() => {
    const map = {};
    data.TEAMS.forEach(item => {
      const stickers = data.STICKERS.filter(sticker => sticker.team === item.id);
      const total = stickers.length;
      const owned = stickers.filter(sticker => collection[sticker.id]?.count > 0).length;
      map[item.id] = { total, owned };
    });
    return map;
  }, [collection]);

  const selectedTeamStickers = useMemoB(
    () => data.STICKERS.filter(sticker => sticker.team === teamId).sort((a, b) => a.num - b.num),
    [data.STICKERS, teamId]
  );

  const visibleGridStickers = useMemoB(() => {
    if (showMissing) return selectedTeamStickers;
    return selectedTeamStickers.filter(sticker => collection[sticker.id]?.count > 0);
  }, [collection, selectedTeamStickers, showMissing]);

  const binderData = useMemoB(() => {
    const pages = [];
    const teamStartPage = {};

    data.TEAMS.forEach(item => {
      const teamStickers = data.STICKERS
        .filter(sticker => sticker.team === item.id)
        .sort((a, b) => a.num - b.num);

      const visibleStickers = showMissing
        ? teamStickers
        : teamStickers.filter(sticker => collection[sticker.id]?.count > 0);

      const stickerChunks = chunkItems(visibleStickers, BINDER_PAGE_SIZE);
      const pageChunks = stickerChunks.length ? stickerChunks : [[]];

      teamStartPage[item.id] = pages.length;

      pages.push({
        type: 'cover',
        team: item,
        stats: totalByTeam[item.id],
        quote: TEAM_QUOTES[item.id] || TEAM_QUOTES.arg,
      });

      pageChunks.forEach((stickers, pageIndex) => {
        pages.push({
          type: 'cards',
          team: item,
          stats: totalByTeam[item.id],
          stickers,
          pageIndex,
          pageCount: pageChunks.length,
        });
      });
    });

    return { pages, teamStartPage };
  }, [collection, data.STICKERS, data.TEAMS, showMissing, totalByTeam]);

  const totalOwned = Object.values(totalByTeam).reduce((sum, value) => sum + value.owned, 0);
  const totalTotal = Object.values(totalByTeam).reduce((sum, value) => sum + value.total, 0);
  const progressPct = totalTotal ? Math.round((totalOwned / totalTotal) * 100) : 0;
  const selectedTeam = useMemoB(
    () => data.TEAMS.find(item => item.id === teamId) || data.TEAMS[0],
    [data.TEAMS, teamId]
  );
  const teamStats = totalByTeam[selectedTeam.id] || { owned: 0, total: 0 };

  const maxSpreadStart = Math.max(0, binderData.pages.length - 1);
  const safeSpreadStart = Math.min(spreadStartIndex, maxSpreadStart);
  const leftPage = binderData.pages[safeSpreadStart] || null;
  const rightPage = binderData.pages[safeSpreadStart + 1] || null;
  const activeBinderTeamId = rightPage?.type === 'cover'
    ? rightPage.team.id
    : (leftPage?.team?.id || teamId);

  function runFlip(direction, action) {
    setFlipDirection(direction);
    setFlipping(true);
    setTimeout(() => {
      action();
      setFlipping(false);
    }, 320);
  }

  function jumpToTeam(nextTeamId) {
    const teamStart = binderData.teamStartPage[nextTeamId] ?? 0;
    const nextSpread = teamStart % 2 === 0 ? teamStart : Math.max(0, teamStart - 1);

    setTeamId(nextTeamId);
    if (viewMode === 'binder') {
      if (nextSpread === safeSpreadStart) {
        setSpreadStartIndex(nextSpread);
        return;
      }
      runFlip(nextSpread > safeSpreadStart ? 'next' : 'prev', () => setSpreadStartIndex(nextSpread));
      return;
    }
    setSpreadStartIndex(nextSpread);
  }

  function toggleShowMissing() {
    setShowMissing(current => !current);
    setSpreadStartIndex(0);
  }

  function changeSpread(direction) {
    if (direction === 'prev' && safeSpreadStart === 0) return;
    if (direction === 'next' && safeSpreadStart + 2 >= binderData.pages.length) return;

    runFlip(direction, () => {
      const nextSpreadStart = direction === 'prev'
        ? Math.max(0, safeSpreadStart - 2)
        : Math.min(safeSpreadStart + 2, Math.max(0, binderData.pages.length - 1));
      const nextLeftPage = binderData.pages[nextSpreadStart];
      const nextRightPage = binderData.pages[nextSpreadStart + 1];
      const nextActiveTeamId = nextRightPage?.type === 'cover'
        ? nextRightPage.team.id
        : (nextLeftPage?.team?.id || teamId);

      setSpreadStartIndex(nextSpreadStart);
      setTeamId(nextActiveTeamId);
    });
  }

  function scrollTeams(direction) {
    const element = teamsScrollerRef.current;
    if (!element) return;
    const delta = direction === 'next' ? 220 : -220;
    element.scrollBy({ left: delta, behavior: 'smooth' });
  }

  function handleTeamsWheel(event) {
    const element = teamsScrollerRef.current;
    if (!element) return;
    if (element.scrollWidth <= element.clientWidth) return;
    if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) return;

    event.preventDefault();
    element.scrollBy({ left: event.deltaY, behavior: 'auto' });
  }

  function renderPageChrome(side, pageNumber, action) {
    return (
      <>
        {!isStackedBinder && action ? (
          <button
            className={`binder__page-action binder__page-action--${side}`}
            type="button"
            onClick={action.onClick}
            disabled={action.disabled}
          >
            {action.label}
          </button>
        ) : null}

        {pageNumber ? (
          <div className={`binder__folio binder__folio--${side}`}>
            {pageNumber}
          </div>
        ) : null}
      </>
    );
  }

  function renderCoverPage(page, side, pageNumber, action) {
    return (
      <section className={`binder__page binder__page--${side} binder__page--cover`}>
        <div className={`binder__side-tab binder__side-tab--${side}`}>
          <span>{page.team.short}</span>
          <strong>{page.team.name}</strong>
        </div>

        <div className="binder__cover-badge">{page.team.short}</div>

        <div className="binder__cover-copy">
          <div className="binder__cover-kicker">{page.team.nickname}</div>
          <h3>{page.team.name}</h3>
          <p>{page.team.motto}</p>
          <div className="binder__cover-progress">
            <strong>{page.stats.owned}/{page.stats.total}</strong>
            <span>Collected</span>
          </div>
        </div>

        <div className="binder__crest">
          <div className="binder__crest-stars">***</div>
          <div className="binder__crest-shield">
            <span>{getTeamFlag(page.team)}</span>
            <strong>{page.team.short}</strong>
          </div>
        </div>

        <div className="binder__quote">
          <p>"{page.quote.quote}"</p>
          <span>- {page.quote.author}</span>
        </div>

        {renderPageChrome(side, pageNumber, action)}
      </section>
    );
  }

  function renderCardsPage(page, side, pageNumber, action) {
    return (
      <section className={`binder__page binder__page--${side} binder__page--cards`}>
        <div className="binder__pockets">
          {page.stickers.length ? page.stickers.map((sticker, index) => {
            const owned = collection[sticker.id];
            const isNew = owned?.isNew;

            return (
              <div
                key={sticker.id}
                className={`binder-pocket ${owned ? 'is-owned' : 'is-empty'} ${isNew ? 'glow-new' : ''}`}
                style={{ animationDelay: `${index * 0.04}s` }}
              >
                {owned ? (
                  <StickerCard
                    sticker={sticker}
                    rarity={owned.rarity}
                    isNew={isNew}
                    compact
                    tilt={false}
                    onClick={() => {
                      if (isNew) onViewedNew(sticker.id);
                      onStickerClick(sticker, owned.rarity);
                    }}
                  />
                ) : (
                  <div className="binder-pocket__empty">
                    <EmptySlot num={sticker.num} />
                    <span className="binder-pocket__lock">Locked</span>
                  </div>
                )}
              </div>
            );
          }) : (
            <div className="binder__empty-state">
              <strong>{page.team.name}</strong>
              <span>No owned cards are visible with missing cards hidden.</span>
            </div>
          )}
        </div>

        {renderPageChrome(side, pageNumber, action)}
      </section>
    );
  }

  function renderBinderPage(page, side, pageNumber, action) {
    if (!page) {
      return (
        <section className={`binder__page binder__page--${side} binder__page--blank`}>
          {renderPageChrome(side, pageNumber, action)}
        </section>
      );
    }
    return page.type === 'cover'
      ? renderCoverPage(page, side, pageNumber, action)
      : renderCardsPage(page, side, pageNumber, action);
  }

  const isPrevDisabled = safeSpreadStart === 0;
  const isNextDisabled = safeSpreadStart + 2 >= binderData.pages.length;
  const activeTeamForTabs = viewMode === 'binder' ? activeBinderTeamId : teamId;
  const leftPageAction = {
    label: 'Previous',
    onClick: () => changeSpread('prev'),
    disabled: isPrevDisabled,
  };
  const rightPageAction = {
    label: 'Next Page',
    onClick: () => changeSpread('next'),
    disabled: isNextDisabled,
  };

  return (
    <div className={`book book--binder ${isMobile ? 'book--mobile' : ''}`}>
      <div className="book__hero">
        <div className="book__hero-copy">
          <h2 className="book__title">Card Collection</h2>
          <div className="book__eyebrow">Your legends. Your history.</div>
        </div>

        <div className="book__hero-side">
          <div className="book__summary-card">
            <div className="book__summary-top">
              <strong>{totalOwned} / {totalTotal}</strong>
              <span>{progressPct}%</span>
            </div>
            <div className="book__progress-bar">
              <div style={{ width: `${progressPct}%` }} />
            </div>
            <div className="book__summary-label">Collection progress</div>
          </div>
        </div>
      </div>

      <div className="book__collection-bar">
        <div className="book__countries-shell">
          <button className="book__countries-nav" type="button" aria-label="Scroll teams left" onClick={() => scrollTeams('prev')}>
            {'<'}
          </button>
          <div className="book__countries-track" ref={teamsScrollerRef} onWheel={handleTeamsWheel}>
            <div className="book__countries">
              <div className="book__countries-row">
                {data.TEAMS.map(item => {
                  const stats = totalByTeam[item.id];
                  return (
                    <button
                      key={item.id}
                      className="country-tab"
                      title={item.name}
                      data-active={item.id === activeTeamForTabs}
                      style={{ '--team-color': item.primary, '--team-accent': item.accent }}
                      onClick={() => jumpToTeam(item.id)}
                    >
                      <span className="country-tab__flag">{getTeamFlag(item)}</span>
                      <span className="country-tab__count">{stats.owned}/{stats.total}</span>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
          <button className="book__countries-nav" type="button" aria-label="Scroll teams right" onClick={() => scrollTeams('next')}>
            {'>'}
          </button>
        </div>

        <div className="book__controls">
          <div className="book__toolbar">
            {!isMobile ? (
              <button
                className="book__toolbar-btn"
                data-active={viewMode === 'binder'}
                onClick={() => setViewMode('binder')}
              >
                Binder
              </button>
            ) : null}
            <button
              className="book__toolbar-btn"
              data-active={viewMode === 'grid'}
              onClick={() => setViewMode('grid')}
            >
              Grid
            </button>
          </div>

          <div className="book__toggle">
            <span>Show Missing</span>
            <button
              className="book__switch"
              type="button"
              aria-pressed={showMissing}
              data-active={showMissing}
              onClick={toggleShowMissing}
            >
              <span />
            </button>
          </div>
        </div>
      </div>

      <div className="book__pages">
        {flipping && viewMode === 'binder' && !isStackedBinder ? (
          <div className="book__flip" data-direction={flipDirection}>
            <div className="book__flip-sheet" />
          </div>
        ) : null}

        {viewMode === 'binder' ? (
          <div className="binder" key={`${activeTeamForTabs}-${showMissing ? 'all' : 'owned'}-${safeSpreadStart}`}>
            {renderBinderPage(leftPage, 'left', leftPage ? safeSpreadStart + 1 : null, leftPageAction)}

            <div className="binder__spine" aria-hidden="true">
              <div className="binder__spine-rail" />
              <div className="binder__rings">
                {[0, 1, 2, 3, 4].map(index => (
                  <span key={index} className="binder__ring" />
                ))}
              </div>
            </div>

            {renderBinderPage(
              rightPage,
              'right',
              rightPage ? safeSpreadStart + 2 : null,
              rightPageAction
            )}

            {isStackedBinder ? (
              <div className="binder__page-footer">
                <button className="binder__page-btn" type="button" onClick={() => changeSpread('prev')} disabled={isPrevDisabled}>
                  Previous
                </button>
                <div className="binder__page-number">Pages {safeSpreadStart + 1}-{Math.min(safeSpreadStart + 2, binderData.pages.length)}</div>
                <button className="binder__page-btn" type="button" onClick={() => changeSpread('next')} disabled={isNextDisabled}>
                  Next Page
                </button>
              </div>
            ) : null}
          </div>
        ) : (
          <div className="book__page book__page--grid" key={`${teamId}-${showMissing ? 'all' : 'owned'}`}>
            <div
              className="team-banner"
              style={{ '--team-gradient': `linear-gradient(135deg, ${selectedTeam.primary} 0%, ${selectedTeam.accent} 100%)` }}
            >
              <div className="team-banner__flag">{getTeamFlag(selectedTeam)}</div>
              <div className="team-banner__text">
                <h3>{selectedTeam.name}</h3>
                <p>{selectedTeam.nickname} - {selectedTeam.motto}</p>
              </div>
              <div className="team-banner__meta">
                <div className="mono">{teamStats.owned}/{teamStats.total}</div>
                <span>Collected</span>
              </div>
            </div>

            <div className="team-grid">
              {visibleGridStickers.map((sticker, index) => {
                const owned = collection[sticker.id];
                const isNew = owned?.isNew;

                return (
                  <div
                    key={sticker.id}
                    className={`team-grid__item ${isNew ? 'glow-new' : ''}`}
                    style={{ animationDelay: `${index * 0.03}s` }}
                  >
                    {owned ? (
                      <StickerCard
                        sticker={sticker}
                        rarity={owned.rarity}
                        isNew={isNew}
                        onClick={() => {
                          if (isNew) onViewedNew(sticker.id);
                          onStickerClick(sticker, owned.rarity);
                        }}
                      />
                    ) : (
                      <EmptySlot num={sticker.num} />
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      <div className="book__legend">
        <span className="rarity-chip" data-rarity="epic">Epic</span>
        <span className="rarity-chip" data-rarity="legendary">Legendary</span>
        <span className="rarity-chip" data-rarity="rare">Rare</span>
        <span className="rarity-chip" data-rarity="common">Common</span>
        <span className="book__legend-locked">Locked</span>
      </div>
    </div>
  );
}

function PlayerModal({ sticker, rarity, onClose }) {
  const data = window.WC_DATA;
  const team = data.TEAMS.find(item => item.id === sticker.team);
  const stats = sticker.stats || {};
  const statLabels = { pac: 'Pace', sho: 'Shooting', pas: 'Passing', dri: 'Dribbling', def: 'Defense', phy: 'Physical' };
  const r = window.normalizeRarity ? window.normalizeRarity(rarity) : rarity;
  const rarityInfo = data.RARITY[r] || { label: r };

  function statColor(value) {
    if (value >= 85) return { from: '#f59e0b', to: '#fbbf24' };
    if (value >= 75) return { from: '#10b981', to: '#34d399' };
    if (value >= 65) return { from: '#3b82f6', to: '#60a5fa' };
    return { from: '#64748b', to: '#94a3b8' };
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="player-modal" onClick={event => event.stopPropagation()}>
        <button className="player-modal__close" onClick={onClose} aria-label="Close">X</button>
        <div className="player-modal__left" style={{ background: `linear-gradient(180deg, ${team.primary}33, transparent)` }}>
          <div className="player-modal__card-wrap">
            <StickerCard sticker={sticker} rarity={r} interactive tilt />
          </div>
        </div>
        <div className="player-modal__right">
          <div className="row" style={{ gap: 10, marginBottom: 4 }}>
            <span className="rarity-chip" data-rarity={r}>{rarityInfo.label}</span>
            <span style={{ fontSize: 12, color: 'var(--ink-dim)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
              #{String(sticker.num).padStart(2, '0')} - {team.short}
            </span>
          </div>
          <h3>{sticker.name}</h3>
          <p className="player-modal__sub">{sticker.pos} - {team.nickname}</p>

          <div className="info-grid">
            <div className="info-grid__item"><span>Age</span><b>{sticker.age}</b></div>
            <div className="info-grid__item"><span>Height</span><b>{sticker.height}cm</b></div>
            <div className="info-grid__item"><span>Foot</span><b>{sticker.foot}</b></div>
            <div className="info-grid__item"><span>No.</span><b>{sticker.num}</b></div>
          </div>

          <div className="section-label">Stats</div>
          <div>
            {Object.entries(statLabels).map(([key, label]) => {
              const value = stats[key] ?? 60;
              const colors = statColor(value);
              return (
                <div className="stat-bar" key={key}>
                  <div className="stat-bar__head"><span>{label}</span><b>{value}</b></div>
                  <div className="stat-bar__track">
                    <div className="stat-bar__fill" style={{ width: `${value}%`, '--fill-from': colors.from, '--fill-to': colors.to }} />
                  </div>
                </div>
              );
            })}
          </div>

          <div className="section-label">Fun Facts</div>
          <ul className="facts-list">
            {sticker.facts.map((fact, index) => <li key={index}>{fact}</li>)}
          </ul>
        </div>
      </div>
    </div>
  );
}

window.StickerBook = StickerBook;
window.PlayerModal = PlayerModal;
