// The dark Y2K room: TV stand, TV with static+logo,
// VHS on shelf. Clicking any VHS opens the gallery.

const { useMemo } = React;

function Dust({ count = 40 }) {
  const particles = useMemo(() => Array.from({ length: count }).map((_, i) => ({
    left: Math.random() * 100,
    bottom: -(Math.random() * 20),
    dur: 12 + Math.random() * 22,
    delay: -Math.random() * 30,
    size: 1 + Math.random() * 2.5,
  })), [count]);
  return (
    <div className="dust" aria-hidden>
      {particles.map((p, i) => (
        <i key={i} style={{
          left: p.left + "%",
          bottom: p.bottom + "%",
          animationDuration: p.dur + "s",
          animationDelay: p.delay + "s",
          width: p.size + "px",
          height: p.size + "px",
        }} />
      ))}
    </div>
  );
}

function TVContent({ tvScreen, setTvScreen, user, setUser }) {
  const compact = tvScreen === "login" || tvScreen === "register";
  return (
    <div className={"tv-title" + (compact ? " compact" : "")}>
      <div className="brand-title">TROOPER</div>
      <TVMenu
        screen={tvScreen}
        setScreen={setTvScreen}
        user={user}
        setUser={setUser}
      />
    </div>
  );
}

function VHSSpineInShelf({ ch, onClick }) {
  const { bg, stripe } = ch.spine;
  return (
    <div
      className="vhs-spine"
      style={{
        background: `linear-gradient(90deg, ${bg} 0%, ${shadeRoom(bg,-15)} 50%, ${bg} 100%)`,
      }}
      onClick={onClick}
    />
  );
}

// little helper for tinting. Renombrado de `shade` a `shadeRoom` porque
// gallery4.jsx también define un `shade` con escala/formato distintos y los
// scripts babel comparten scope global (ver proto_global_scope_gotcha).
function shadeRoom(hex, p) {
  // hex can be #rgb, #rrggbb
  let c = hex.replace("#","");
  if (c.length === 3) c = c.split("").map(x=>x+x).join("");
  const r = parseInt(c.substr(0,2),16),
        g = parseInt(c.substr(2,2),16),
        b = parseInt(c.substr(4,2),16);
  const amt = Math.round(2.55 * p);
  const nr = Math.min(255, Math.max(0, r + amt));
  const ng = Math.min(255, Math.max(0, g + amt));
  const nb = Math.min(255, Math.max(0, b + amt));
  return "#" + [nr, ng, nb].map(v => v.toString(16).padStart(2, "0")).join("");
}

function Room({ zooming, dim, vhsCount, onOpenGallery, onClickTV, onOpenAlbum, tvScreen, setTvScreen, user, setUser, ownedCount, totalCards }) {
  // Use the shared store hook so Room re-renders on any novel update, including
  // when toggling between EDITOR/LECTOR (it remounts and re-fetches from server).
  const [store] = window.NovelStore.useNovelStore();
  const arcs = window.NovelStore.filterForReader(store);
  const fallback = window.TROOPER_CHAPTERS || [];
  const source = arcs.length ? arcs : fallback;
  const chapters = source.slice(0, vhsCount);

  // Shelf door state: "closed" (no user) | "opening" (just logged in) | "open" (user)
  const [doorState, setDoorState] = React.useState(() => user ? "open" : "closed");
  const prevUserRef = React.useRef(user);

  React.useEffect(() => {
    const wasLoggedIn = !!prevUserRef.current;
    const isLoggedIn = !!user;
    if (!wasLoggedIn && isLoggedIn) {
      // Just logged in -> play opening animation
      setDoorState("opening");
      const t = setTimeout(() => setDoorState("open"), 2200);
      prevUserRef.current = user;
      return () => clearTimeout(t);
    }
    if (wasLoggedIn && !isLoggedIn) {
      setDoorState("closed");
    }
    prevUserRef.current = user;
  }, [user]);

  return (
    <div className={"room" + (dim ? " dim" : "") + (zooming ? " zooming" : "")}>
      {/* Fully black walls */}
      <div className="wall" />

      {/* Floor */}
      <div className="floor" />

      {/* TV stand + VHS 3D — three.js inside the shelf cubby */}
      <div className="tv-stand">
        <img className="stand-img" src="assets/shelf.png" alt="" />
        <div className="cubby-tapes">
          <VHS3D chapters={chapters} onOpenGallery={onOpenGallery} />
        </div>
        {doorState !== "open" && (
          <div className={"shelf-door shelf-door-" + doorState}>
            <img src="assets/shelf-door.png" alt="" className="shelf-door-img" />
            {doorState === "opening" && (
              <>
                <div className="shelf-door-dust" />
                <div className="shelf-door-crack shelf-door-crack-1" />
                <div className="shelf-door-crack shelf-door-crack-2" />
                <div className="shelf-door-crack shelf-door-crack-3" />
              </>
            )}
          </div>
        )}
      </div>

      {/* Card collection box — to the right of the shelf */}
      {window.CardBox && (
        <window.CardBox
          onClick={onOpenAlbum}
          ownedCount={ownedCount || 0}
          totalCount={totalCards || 0}
          locked={!user}
        />
      )}

      {/* TV cast */}
      <div className="tv-cast" />

      {/* TV */}
      <div className={"tv" + (zooming ? " zooming" : "")} onClick={onClickTV}>
        <div className="screen">
          <div className="static" />
          <div className="crt-bloom" />
          <TVContent
            tvScreen={tvScreen}
            setTvScreen={setTvScreen}
            user={user}
            setUser={setUser}
          />
          <div className="scanlines" />
        </div>
        <img className="tv-frame-img" src="tv-frame-v2.png" alt="" />
        <div className="power-led" />
      </div>

      {/* Ambient */}
      <div className="noise" />
      <div className="vignette" />
    </div>
  );
}

window.Room = Room;
