// Compact mobile composition for the same single-screen profile.

function MobileLobby({
  heroCharacter,
  voiceTrack,
  tracks,
  activeId, onPick,
  playing,
  playback,
  formatDuration,
  onOpenStickers,
  stickers,
  entity,
}) {
  const [aboutOpen, setAboutOpen] = React.useState(false);
  const carouselRef = React.useRef(null);
  const voiceAvailable = Boolean(voiceTrack.audio);
  const voiceSelected = activeId === voiceTrack.id;
  const progress = playback.duration > 0
    ? Math.min(100, (playback.currentTime / playback.duration) * 100)
    : 0;

  React.useEffect(() => {
    if (!aboutOpen) return;
    const onKey = (event) => { if (event.key === "Escape") setAboutOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [aboutOpen]);

  React.useEffect(() => {
    const carousel = carouselRef.current;
    if (!carousel || !activeId) return;
    const card = carousel.querySelector(`[data-track-id="${activeId}"]`);
    if (card) card.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
  }, [activeId]);

  return (
    <main style={mobileStyles.root}>
      <header style={mobileStyles.header}>
        <span style={mobileStyles.brandBlock}>
          <span style={mobileStyles.brand}>AI Creator Lab</span>
          <span style={mobileStyles.kicker}>{heroCharacter.locality}</span>
        </span>
        <button type="button" onClick={() => setAboutOpen(true)} style={mobileStyles.infoButton} aria-label="Про AI Creator Lab">
          ПРО КУРС
        </button>
      </header>

      <div style={mobileStyles.stageWrap}>
        <CharacterStage entity={entity} />
      </div>

      <section aria-label="Образи цифрового персонажа" style={mobileStyles.playerSection}>
        <div style={mobileStyles.playerHead}>
          <span style={mobileStyles.playerTitle}>ДОСЛІДИ ГОТОВИЙ ПРОЄКТ</span>
          <span style={mobileStyles.playerHint}>голос, образи та музика</span>
        </div>
        <div ref={carouselRef} className="mobile-carousel" style={mobileStyles.carousel}>
          <button
            type="button"
            data-track-id={voiceTrack.id}
            className={`mobile-card mobile-voice-card${voiceSelected ? " is-selected" : ""}`}
            onClick={() => onPick(voiceTrack)}
            disabled={!voiceAvailable}
            aria-pressed={voiceSelected && playing}
            style={{
              ...mobileStyles.voiceCard,
              opacity: voiceAvailable ? 1 : 0.72,
              background: voiceSelected ? "var(--signal)" : "var(--signal-soft)",
              color: voiceSelected ? "#fff" : "var(--ink)",
            }}
          >
            <span style={{
              ...mobileStyles.voiceIcon,
              background: voiceSelected ? "#fff" : "var(--signal)",
              color: voiceSelected ? "var(--signal)" : "#fff",
            }} aria-hidden>
              <PlayStateIcon playing={voiceSelected && playing} locked={!voiceAvailable} />
            </span>
            <span style={mobileStyles.cardCopy}>
              <span style={{ ...mobileStyles.cardEyebrow, color: voiceSelected ? "rgba(255,255,255,0.72)" : "var(--signal)" }}>
                {voiceSelected && playing ? "ЗАРАЗ ЗВУЧИТЬ" : "ПОЧНИ З ГОЛОСУ"}
              </span>
              <span style={mobileStyles.voiceTitle}>{voiceTrack.track}</span>
            </span>
            <span style={{ ...mobileStyles.cardDuration, color: voiceSelected ? "rgba(255,255,255,0.72)" : "var(--ink-3)" }}>
              {voiceSelected
                ? `${formatDuration(playback.currentTime)} / ${formatDuration(playback.duration, voiceTrack.duration)}`
                : voiceTrack.duration}
            </span>
            {voiceSelected && (
              <span style={{ ...mobileStyles.progress, background: "rgba(255,255,255,0.24)" }} aria-hidden>
                <span style={{ ...mobileStyles.progressFill, width: `${progress}%`, background: "#fff" }} />
              </span>
            )}
          </button>

          {tracks.map((it, index) => {
            const selected = activeId === it.id;
            const isPlaying = selected && playing;
            return (
              <button
                type="button"
                key={it.id}
                data-track-id={it.id}
                className={`mobile-card${selected ? " is-selected" : ""}`}
                onClick={() => onPick(it)}
                aria-pressed={isPlaying}
                style={{
                  ...mobileStyles.card,
                  background: selected ? "var(--ink)" : "#fff",
                  color: selected ? "#fff" : "var(--ink)",
                  boxShadow: selected
                    ? "0 10px 24px rgba(16,16,18,0.16)"
                    : "inset 0 0 0 1px var(--rule)",
                }}
              >
                <span style={mobileStyles.thumbWrap}>
                  <img src={it.cover} alt="" style={mobileStyles.thumb} />
                  <span style={{ ...mobileStyles.playBadge, opacity: selected ? 1 : 0 }} aria-hidden>
                    {isPlaying ? "Ⅱ" : "▶"}
                  </span>
                </span>
                <span style={mobileStyles.cardCopy}>
                  <span style={{ ...mobileStyles.cardEyebrow, color: selected ? "var(--signal)" : "var(--signal)" }}>{String(index + 1).padStart(2, "0")}</span>
                  <span style={{ ...mobileStyles.cardArtist, color: selected ? "#fff" : "var(--ink)" }}>{it.artist}</span>
                  <span style={{ ...mobileStyles.cardTrack, color: selected ? "rgba(255,255,255,0.68)" : "var(--ink-2)" }}>{it.track}</span>
                </span>
                <span style={{ ...mobileStyles.cardDuration, color: selected ? "rgba(255,255,255,0.66)" : "var(--ink-3)" }}>
                  {selected && playback.duration
                    ? `${formatDuration(playback.currentTime)} / ${formatDuration(playback.duration, it.duration)}`
                    : it.duration}
                </span>
                {selected && (
                  <span style={{ ...mobileStyles.progress, background: "rgba(255,255,255,0.2)" }} aria-hidden>
                    <span style={{ ...mobileStyles.progressFill, width: `${progress}%` }} />
                  </span>
                )}
              </button>
            );
          })}
        </div>
      </section>

      <button type="button" className="mobile-sticker-button" onClick={onOpenStickers} style={mobileStyles.stickerButton}>
        <span style={mobileStyles.stickerDeck} aria-hidden>
          {stickers.map((sticker, index) => (
            <img key={sticker.src} src={sticker.src} alt="" style={{ ...mobileStyles.sticker, left: index * 10, zIndex: index + 1 }} />
          ))}
        </span>
        <span style={mobileStyles.stickerCopy}>
          <span style={mobileStyles.stickerTitle}>Стікерпак персонажа</span>
          <span style={mobileStyles.stickerSub}>Відкрити в Telegram ↗</span>
        </span>
        <span style={mobileStyles.stickerArrow} aria-hidden>↗</span>
      </button>

      {aboutOpen && (
        <div style={mobileStyles.overlay} onClick={() => setAboutOpen(false)}>
          <section role="dialog" aria-modal="true" aria-labelledby="about-title" style={mobileStyles.sheet} onClick={(event) => event.stopPropagation()}>
            <button type="button" onClick={() => setAboutOpen(false)} style={mobileStyles.sheetClose} aria-label="Закрити">×</button>
            <p style={mobileStyles.sheetKicker}>{heroCharacter.locality}</p>
            <h2 id="about-title" style={mobileStyles.sheetName}>{heroCharacter.name}</h2>
            <div style={mobileStyles.sheetBio}>
              <p style={mobileStyles.bioIntro}>
                {heroCharacter.bioLead}
              </p>
              <p style={mobileStyles.bioCourse}>{heroCharacter.bioTail}</p>
              <p style={mobileStyles.bioAuthor}>
                Майстерню веде{" "}
                <a
                  className="mobile-author-link"
                  href={heroCharacter.author.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={mobileStyles.bioAuthorLink}
                  aria-label={`${heroCharacter.author.name} у Telegram`}
                >
                  <span style={mobileStyles.bioTelegramIcon} aria-hidden>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M21.8 3.2 18.6 20c-.2 1.2-.9 1.5-1.9.9l-4.9-3.6-2.4 2.3c-.3.3-.5.5-1 .5l.4-5 9.1-8.2c.4-.4-.1-.6-.6-.2L6.1 13.8 1.3 12.3c-1.1-.3-1.1-1.1.2-1.6L20.3 3c.9-.3 1.7.2 1.5.2Z" />
                    </svg>
                  </span>
                  <span>{heroCharacter.author.name}</span>
                  <span style={mobileStyles.bioAuthorArrow} aria-hidden>↗</span>
                </a>
              </p>
            </div>
            <div style={mobileStyles.sheetFacts}>
              <span style={mobileStyles.sheetFact}>5 тижнів</span>
              <span style={mobileStyles.sheetFact}>Крок за кроком</span>
              <span style={mobileStyles.sheetFact}>Без досвіду</span>
            </div>
          </section>
        </div>
      )}

      <style>{`
        @keyframes mobile-sheet-in {
          from { transform: translateY(20px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }
        @keyframes mobile-overlay-in {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        .mobile-carousel::-webkit-scrollbar { display: none; }
        .mobile-author-link:hover { color: #087fb8 !important; background: #e4f6ff !important; text-decoration: none !important; }
        .mobile-card:active, .mobile-sticker-button:active { transform: scale(0.985); }
        @media (prefers-reduced-motion: reduce) {
          .mobile-card, .mobile-sticker-button, .mobile-sticker-button img { animation: none !important; transition: none !important; }
        }
      `}</style>
    </main>
  );
}

const mobileStyles = {
  root: { display: "flex", flexDirection: "column", width: "100%", minWidth: 0, height: "100%", boxSizing: "border-box", padding: "calc(env(safe-area-inset-top) + 12px) 12px calc(env(safe-area-inset-bottom) + 10px)", gap: 9, overflow: "hidden", background: "#fff" },
  header: { display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%", minWidth: 0, minHeight: 44, flexShrink: 0, padding: "0 2px", boxSizing: "border-box" },
  brandBlock: { display: "flex", flexDirection: "column", gap: 2 },
  brand: { fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 25, lineHeight: 0.95, letterSpacing: "-0.045em", color: "var(--ink)" },
  kicker: { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 8, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--signal)" },
  infoButton: { height: 32, padding: "0 11px", border: 0, borderRadius: 999, background: "var(--paper-2)", boxShadow: "inset 0 0 0 1px var(--rule)", color: "var(--ink-2)", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 8, letterSpacing: "0.08em", cursor: "pointer" },
  stageWrap: { position: "relative", display: "flex", width: "100%", minWidth: 0, flex: 1, minHeight: 180, overflow: "hidden", borderRadius: 22, background: "transparent" },

  playerSection: { display: "flex", flexDirection: "column", width: "100%", minWidth: 0, gap: 7, flexShrink: 0 },
  playerHead: { display: "flex", alignItems: "baseline", justifyContent: "space-between", padding: "0 2px" },
  playerTitle: { fontFamily: "var(--font-display)", fontWeight: 850, fontSize: 14, letterSpacing: "-0.015em", color: "var(--ink)" },
  playerHint: { fontSize: 9, color: "var(--ink-2)" },
  carousel: { display: "flex", width: "100%", minWidth: 0, gap: 8, overflowX: "auto", overflowY: "hidden", scrollSnapType: "x mandatory", WebkitOverflowScrolling: "touch", scrollbarWidth: "none", msOverflowStyle: "none", padding: "1px 1px 3px", boxSizing: "border-box" },
  voiceCard: { position: "relative", display: "grid", gridTemplateColumns: "46px minmax(0,1fr) auto", alignItems: "center", gap: 10, minWidth: 280, height: 70, padding: "8px 11px 8px 8px", border: 0, borderRadius: 18, color: "var(--ink)", textAlign: "left", scrollSnapAlign: "center", flexShrink: 0, overflow: "hidden", transition: "transform var(--t-fast) var(--ease), background var(--t-base) var(--ease)" },
  voiceIcon: { display: "grid", placeItems: "center", width: 46, height: 46, borderRadius: 14, background: "var(--signal)", color: "#fff" },
  voiceTitle: { maxWidth: 150, fontFamily: "var(--font-display)", fontWeight: 820, fontSize: 12, lineHeight: 1.12 },

  card: { position: "relative", display: "grid", gridTemplateColumns: "50px minmax(0,1fr) auto", alignItems: "center", gap: 10, minWidth: 250, height: 70, padding: "8px 11px 8px 8px", border: 0, borderRadius: 18, textAlign: "left", cursor: "pointer", scrollSnapAlign: "center", flexShrink: 0, overflow: "hidden", transition: "transform var(--t-fast) var(--ease), background var(--t-base) var(--ease), box-shadow var(--t-base) var(--ease)" },
  thumbWrap: { position: "relative", width: 50, height: 50, borderRadius: 13, overflow: "hidden", background: "#fff" },
  thumb: { width: "100%", height: "100%", display: "block", objectFit: "cover", objectPosition: "center top" },
  playBadge: { position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "rgba(16,16,18,0.52)", color: "#fff", fontSize: 12 },
  cardCopy: { display: "flex", flexDirection: "column", minWidth: 0 },
  cardEyebrow: { fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 7, lineHeight: 1, letterSpacing: "0.1em", color: "var(--signal)" },
  cardArtist: { marginTop: 3, fontFamily: "var(--font-display)", fontWeight: 820, fontSize: 13, lineHeight: 1.05, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" },
  cardTrack: { marginTop: 3, maxWidth: 132, fontSize: 10, lineHeight: 1.1, color: "var(--ink-2)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" },
  cardDuration: { fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-3)" },
  progress: { position: "absolute", left: 68, right: 11, bottom: 4, height: 2, borderRadius: 99, overflow: "hidden", background: "var(--rule)" },
  progressFill: { display: "block", height: "100%", borderRadius: 99, background: "var(--signal)", transition: "width 180ms linear" },

  stickerButton: { display: "flex", alignItems: "center", gap: 9, width: "100%", height: 58, padding: "3px 8px 3px 5px", border: 0, borderRadius: 19, overflow: "hidden", flexShrink: 0, background: "linear-gradient(115deg,#101012,#24242b)", color: "#fff", cursor: "pointer", textAlign: "left", boxShadow: "0 9px 22px rgba(16,16,18,0.14)", transition: "transform var(--t-fast) var(--ease)" },
  stickerDeck: { position: "relative", width: 72, height: 54, flexShrink: 0 },
  sticker: { position: "absolute", bottom: 0, width: 36, height: 36, objectFit: "contain", filter: "drop-shadow(0 3px 3px rgba(0,0,0,0.35))" },
  stickerCopy: { display: "flex", flexDirection: "column", minWidth: 0 },
  stickerTitle: { fontFamily: "var(--font-display)", fontWeight: 850, fontSize: 13, lineHeight: 1.05, whiteSpace: "nowrap" },
  stickerSub: { marginTop: 4, fontSize: 9, color: "#79c9f5", whiteSpace: "nowrap" },
  stickerArrow: { display: "grid", placeItems: "center", width: 30, height: 30, marginLeft: "auto", flexShrink: 0, borderRadius: 999, background: "rgba(255,255,255,0.1)", color: "#fff", fontSize: 13 },

  overlay: { position: "fixed", inset: 0, zIndex: 50, display: "flex", alignItems: "flex-end", justifyContent: "center", padding: "0 12px calc(env(safe-area-inset-bottom) + 12px)", background: "rgba(16,16,18,0.48)", animation: "mobile-overlay-in 180ms var(--ease) both" },
  sheet: { position: "relative", width: "100%", maxWidth: 520, boxSizing: "border-box", padding: "26px 20px 22px", borderRadius: 24, background: "#fff", boxShadow: "0 24px 60px rgba(0,0,0,0.24)", animation: "mobile-sheet-in 280ms var(--ease) both" },
  sheetClose: { position: "absolute", top: 10, right: 12, width: 32, height: 32, border: 0, borderRadius: 999, background: "var(--paper-2)", color: "var(--ink)", fontSize: 20, cursor: "pointer" },
  sheetKicker: { margin: 0, maxWidth: "85%", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 9, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--signal)" },
  sheetName: { margin: "12px 0 0", fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 44, lineHeight: 0.9, letterSpacing: "-0.05em", color: "var(--ink)" },
  sheetBio: { display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 11, margin: "16px 0 0" },
  bioIntro: { display: "flex", alignItems: "center", flexWrap: "wrap", gap: "3px 2px", margin: 0, fontFamily: "var(--font-display)", fontWeight: 720, fontSize: 14, lineHeight: 1.4, color: "var(--ink)" },
  bioCourse: { margin: 0, paddingLeft: 12, borderLeft: "2px solid var(--signal)", fontSize: 13, lineHeight: 1.5, color: "var(--ink-2)" },
  bioAuthor: { display: "flex", alignItems: "center", flexWrap: "wrap", gap: 3, margin: 0, fontSize: 12, fontWeight: 550, color: "var(--ink-2)" },
  bioAuthorLink: { display: "inline-flex", alignItems: "center", gap: 5, margin: "0 2px", padding: "4px 8px 4px 5px", borderRadius: 999, background: "#eef9ff", color: "#126d98", boxShadow: "inset 0 0 0 1px rgba(42,171,238,0.18)", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 12, lineHeight: 1, verticalAlign: "0.08em", textDecoration: "none" },
  bioTelegramIcon: { display: "grid", placeItems: "center", width: 20, height: 20, borderRadius: 999, background: "var(--tg-blue)", color: "#fff", boxShadow: "0 3px 8px rgba(42,171,238,0.24)" },
  bioAuthorArrow: { color: "var(--tg-blue)", fontSize: 9 },
  sheetFacts: { display: "flex", gap: 6, flexWrap: "wrap", marginTop: 18 },
  sheetFact: { padding: "6px 9px", borderRadius: 999, background: "var(--paper-2)", fontFamily: "var(--font-display)", fontWeight: 750, fontSize: 9, color: "var(--ink)" },
};

window.MobileLobby = MobileLobby;
