// Mobile composition — character-first, no-scroll layout for narrow viewports.
// Reuses window.CharacterStage and the same state shape as the desktop branch.
// Bio/name live in a popup behind the "Про мене" button so the character stays
// dominant on small screens.

function MobileLobby({
  heroCharacter,
  tracks,
  activeId, onPick,
  playMode, onVoice,
  onOpenStickers,
  entity,
}) {
  const voiceActive = playMode === "voice";
  const [aboutOpen, setAboutOpen] = React.useState(false);
  const carouselRef = React.useRef(null);

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

  // Scroll the active card into view when track changes.
  React.useEffect(() => {
    const el = carouselRef.current;
    if (!el) return;
    const card = el.querySelector(`[data-track-id="${activeId}"]`);
    if (card) card.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
  }, [activeId]);

  return (
    <div style={mobileStyles.root}>
      {/* Row 1 — top controls */}
      <div style={mobileStyles.topRow}>
        <button
          onClick={onVoice}
          style={{ ...mobileStyles.voiceBtn, background: voiceActive ? "var(--signal-deep)" : "var(--signal)" }}
        >
          {voiceActive ? (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><rect x="7" y="5" width="3.5" height="14" rx="0.5"/><rect x="13.5" y="5" width="3.5" height="14" rx="0.5"/></svg>
          ) : (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><polygon points="8,5 19,12 8,19"/></svg>
          )}
          Voice
        </button>
        <button onClick={() => setAboutOpen(true)} style={mobileStyles.aboutBtn}>
          Про мене
        </button>
      </div>

      {/* Row 2 — character (primary) */}
      <div style={mobileStyles.stageWrap}>
        <CharacterStage entity={entity} playing={playMode !== null} />
      </div>

      {/* Row 3 — tracks carousel (secondary) */}
      <div ref={carouselRef} style={mobileStyles.carousel}>
        {tracks.map((it, i) => {
          const isActive = playMode === "track" && activeId === it.id;
          return (
            <button
              key={it.id}
              data-track-id={it.id}
              onClick={() => onPick(it)}
              style={{
                ...mobileStyles.card,
                background: isActive ? "var(--paper-2)" : "transparent",
                boxShadow: isActive ? "inset 0 0 0 1px var(--rule)" : "inset 0 0 0 1px var(--rule)",
              }}
            >
              <span style={mobileStyles.cardThumb}>
                <img
                  src={it.cover ?? it.figure}
                  alt=""
                  style={{
                    ...mobileStyles.cardThumbImg,
                    filter: it.tint,
                    transform: `scale(${it.pose?.scale ?? 1}) ${it.pose?.flipX ? "scaleX(-1)" : ""}`,
                  }}
                />
              </span>
              <span style={mobileStyles.cardBody}>
                <span style={mobileStyles.cardNum}>{String(i + 1).padStart(2, "0")}</span>
                <span style={{ ...mobileStyles.cardArtist, color: isActive ? "var(--signal)" : "var(--ink)" }}>
                  {it.artist}
                </span>
                <span style={mobileStyles.cardTitle}>{it.track}</span>
                {isActive ? (
                  <span style={mobileStyles.eqMini} aria-hidden>
                    <i style={{ ...mobileStyles.eqBar, animationDelay: "0ms"   }} />
                    <i style={{ ...mobileStyles.eqBar, animationDelay: "120ms" }} />
                    <i style={{ ...mobileStyles.eqBar, animationDelay: "240ms" }} />
                  </span>
                ) : (
                  <span style={mobileStyles.cardDuration}>{it.duration}</span>
                )}
              </span>
            </button>
          );
        })}
      </div>

      {/* Row 4 — stickers chip (tertiary) */}
      <button onClick={onOpenStickers} style={mobileStyles.stickersChip}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 4H7a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h6l7-7V7a3 3 0 0 0-3-3z"/>
          <path d="M13 20v-4a3 3 0 0 1 3-3h4"/>
        </svg>
        Stickers on Telegram
        <span style={mobileStyles.stickersArrow}>→</span>
      </button>

      {/* About popup */}
      {aboutOpen && (
        <div style={mobileStyles.overlay} onClick={() => setAboutOpen(false)}>
          <div style={mobileStyles.sheet} onClick={(e) => e.stopPropagation()}>
            <button
              onClick={() => setAboutOpen(false)}
              style={mobileStyles.sheetClose}
              aria-label="Close"
            >
              ×
            </button>
            <h2 style={mobileStyles.sheetName}>{heroCharacter.name}</h2>
            {heroCharacter.locality && (
              <p style={mobileStyles.sheetLocality}>{heroCharacter.locality}</p>
            )}
            <p style={mobileStyles.sheetBio}>{heroCharacter.bio}</p>
          </div>
        </div>
      )}

      <style>{`
        @keyframes lobby-eq {
          0%, 100% { transform: scaleY(0.35); }
          50%      { transform: scaleY(1.0);  }
        }
        @keyframes mobile-sheet-in {
          0%   { transform: translateY(24px); opacity: 0; }
          100% { transform: translateY(0);    opacity: 1; }
        }
        @keyframes mobile-overlay-in {
          0%   { opacity: 0; }
          100% { opacity: 1; }
        }
        .mobile-carousel::-webkit-scrollbar { display: none; }
      `}</style>
    </div>
  );
}

const mobileStyles = {
  root: {
    display: "flex",
    flexDirection: "column",
    width: "100%",
    height: "100%",
    boxSizing: "border-box",
    padding: "calc(env(safe-area-inset-top) + 12px) 16px calc(env(safe-area-inset-bottom) + 10px)",
    gap: 10,
    overflow: "hidden",
  },

  topRow: {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: 10,
    flexShrink: 0,
  },
  aboutBtn: {
    display: "inline-flex",
    alignItems: "center",
    padding: "9px 16px",
    borderRadius: 999,
    background: "var(--paper-2)",
    color: "var(--ink)",
    fontFamily: "var(--font-display)",
    fontWeight: 700,
    fontSize: 13,
    border: 0,
    cursor: "pointer",
    boxShadow: "inset 0 0 0 1px var(--rule)",
  },
  voiceBtn: {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "9px 18px",
    borderRadius: 999,
    color: "#fff",
    fontFamily: "var(--font-display)",
    fontWeight: 700,
    fontSize: 13,
    border: 0,
    cursor: "pointer",
    transition: "background 220ms cubic-bezier(0.2,0.8,0.2,1)",
  },

  stageWrap: {
    position: "relative",
    flex: 1,
    minHeight: 0,
    display: "flex",
  },

  carousel: {
    display: "flex",
    gap: 8,
    overflowX: "auto",
    overflowY: "hidden",
    scrollSnapType: "x mandatory",
    WebkitOverflowScrolling: "touch",
    flexShrink: 0,
    paddingBottom: 2,
    scrollbarWidth: "none",
    msOverflowStyle: "none",
  },
  card: {
    display: "flex",
    alignItems: "center",
    gap: 10,
    minWidth: 220,
    padding: "8px 12px 8px 8px",
    borderRadius: 14,
    border: 0,
    textAlign: "left",
    cursor: "pointer",
    scrollSnapAlign: "center",
    flexShrink: 0,
    transition: "background 160ms cubic-bezier(0.2,0.8,0.2,1)",
  },
  cardThumb: {
    width: 48,
    height: 48,
    borderRadius: 10,
    overflow: "hidden",
    background: "var(--paper-2)",
    display: "flex",
    alignItems: "flex-end",
    justifyContent: "center",
    flexShrink: 0,
  },
  cardThumbImg: {
    width: "100%",
    height: "100%",
    objectFit: "cover",
    objectPosition: "center top",
  },
  cardBody: {
    display: "grid",
    gridTemplateColumns: "auto 1fr auto",
    rowGap: 0,
    columnGap: 6,
    alignItems: "center",
    minWidth: 0,
  },
  cardNum: {
    gridRow: "1 / span 2",
    fontFamily: "var(--font-display)",
    fontWeight: 300,
    fontSize: 18,
    color: "var(--ink-3)",
    fontVariantNumeric: "tabular-nums",
    paddingRight: 4,
  },
  cardArtist: {
    fontFamily: "var(--font-display)",
    fontWeight: 700,
    fontSize: 13,
    lineHeight: 1.1,
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    maxWidth: 130,
  },
  cardTitle: {
    gridRow: 2,
    gridColumn: 2,
    fontSize: 11,
    lineHeight: 1.2,
    color: "var(--ink-2)",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    maxWidth: 130,
  },
  cardDuration: {
    gridRow: "1 / span 2",
    fontFamily: "var(--font-display)",
    fontWeight: 400,
    fontSize: 11,
    color: "var(--ink-3)",
    fontVariantNumeric: "tabular-nums",
  },
  eqMini: {
    gridRow: "1 / span 2",
    display: "inline-flex",
    alignItems: "center",
    gap: 3,
    height: 14,
  },
  eqBar: {
    display: "inline-block",
    width: 3,
    height: "100%",
    background: "var(--signal)",
    borderRadius: 1,
    transformOrigin: "center",
    animation: "lobby-eq 700ms ease-in-out infinite",
  },

  stickersChip: {
    alignSelf: "center",
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "7px 14px",
    borderRadius: 999,
    background: "var(--shadow-ink)",
    color: "#fff",
    border: 0,
    cursor: "pointer",
    fontFamily: "var(--font-display)",
    fontWeight: 600,
    fontSize: 11,
    letterSpacing: "0.02em",
    flexShrink: 0,
  },
  stickersArrow: {
    fontSize: 12,
    color: "rgba(255,255,255,0.75)",
  },

  overlay: {
    position: "fixed",
    inset: 0,
    background: "rgba(10,10,10,0.45)",
    display: "flex",
    alignItems: "flex-end",
    justifyContent: "center",
    zIndex: 50,
    animation: "mobile-overlay-in 220ms cubic-bezier(0.2,0.8,0.2,1) both",
    padding: "0 12px calc(env(safe-area-inset-bottom) + 12px)",
  },
  sheet: {
    position: "relative",
    width: "100%",
    maxWidth: 520,
    background: "var(--paper)",
    borderRadius: 24,
    padding: "28px 22px 26px",
    boxShadow: "0 24px 60px rgba(0,0,0,0.25)",
    animation: "mobile-sheet-in 320ms cubic-bezier(0.2,0.8,0.2,1) both",
    boxSizing: "border-box",
  },
  sheetClose: {
    position: "absolute",
    top: 10,
    right: 12,
    width: 32,
    height: 32,
    borderRadius: 999,
    background: "var(--paper-2)",
    color: "var(--ink)",
    border: 0,
    cursor: "pointer",
    fontSize: 20,
    lineHeight: 1,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
  },
  sheetName: {
    fontFamily: "var(--font-display)",
    fontWeight: 900,
    fontSize: 56,
    lineHeight: 0.92,
    letterSpacing: "-0.04em",
    margin: 0,
    color: "var(--ink)",
  },
  sheetLocality: {
    fontFamily: "var(--font-display)",
    fontWeight: 700,
    fontSize: 13,
    color: "var(--ink-2)",
    margin: "12px 0 0",
  },
  sheetBio: {
    fontSize: 14,
    lineHeight: 1.5,
    color: "var(--ink-2)",
    margin: "10px 0 0",
  },
};

window.MobileLobby = MobileLobby;
