/* Screens: NavBar, TabBar, Wall, Browse, Saved, Settings, Lightbox */
(function () {
  const { useState, useEffect, useMemo, useCallback } = React;
  const Icon = window.Icon;
  const Mark = window.Mark;
  const { Segmented, SortMenu, SearchField, Switch, Chip, Card, SkeletonCard } = window;

  /* =================== NAV BAR =================== */
  function NavBar({ title, stuck, children }) {
    return (
      <header className={"navbar " + (stuck ? "stuck" : "")}>
        <div className="nav-title">{title}</div>
        <div className="nav-actions">{children}</div>
      </header>
    );
  }

  /* =================== TAB BAR =================== */
  const TABS = [
    { id: "wall", label: "Wall", icon: "grid" },
    { id: "browse", label: "Browse", icon: "search" },
    { id: "saved", label: "Saved", icon: "heart" },
    { id: "settings", label: "Settings", icon: "sliders" },
  ];
  function TabBar({ tab, setTab, savedCount }) {
    return (
      <div className="tabbar-wrap">
        <nav className="tabbar">
          {TABS.map((t) => (
            <button key={t.id} className={"tab " + (tab === t.id ? "on" : "")} onClick={() => setTab(t.id)}>
              <span className="dot"><Icon name={tab === t.id && t.id === "saved" ? "heartFill" : t.icon} size={23} weight={tab === t.id ? 2.1 : 1.9} /></span>
              <span>{t.label}</span>
            </button>
          ))}
        </nav>
      </div>
    );
  }

  /* =================== WALL =================== */
  function Wall(props) {
    const {
      items, count, loading, interestList, current, setCurrent,
      editing, setEditing, onRemoveInterest, onManageTopics, goBrowse,
      search, setSearch, sort, setSort, type, setType,
      sourceFilter, setSourceFilter, density,
      liked, onOpen, onToggleLike, onHide, onMoreLikeThis, onLessLikeThis, onBlockTopic, onFollowRecommended, autoplay,
      nsfw, revealed, onReveal,
    } = props;

    const typeOpts = [
      { value: "all", label: "All" }, { value: "video", label: "Videos" },
      { value: "gif", label: "GIFs" }, { value: "image", label: "Photos" },
    ];
    const sortOpts = [
      { value: "hot", label: "Hot" }, { value: "new", label: "New" },
      { value: "top", label: "Top" },
    ];
    const sourceOpts = [
      { value: "all", label: "Sources" }, { value: "redgifs", label: "Redgifs" },
      { value: "eporner", label: "Eporner" }, { value: "reddit", label: "Reddit" },
    ];

    return (
      <div className="page">
        <div className="large-head">
          <div className="large-title brandtitle">
            <Mark size={30} /> Velvet
            {nsfw && <span className="adult-badge">18+</span>}
          </div>
          <div className="large-sub">{loading ? "Loading…" : nsfw
            ? `After Dark · ${count} ${count === 1 ? "item" : "items"}`
            : `${count} ${count === 1 ? "item" : "items"} · ${interestList.length} ${interestList.length === 1 ? "interest" : "interests"}`}</div>
        </div>

        <div className="spacer-sm" />
        <div className="chips">
          {interestList.map((it) => (
            <Chip key={it.id} label={it.label} icon={it.icon}
              active={current === it.id && !editing}
              editing={editing && !it.system}
              onClick={() => !editing && setCurrent(it.id)}
              onRemove={() => onRemoveInterest(it.id)} />
          ))}
          {!editing && (
            <button className="chip add" onClick={goBrowse}>
              <Icon name="plus" size={15} weight={2.6} /> Add
            </button>
          )}
          <button className="chip" onClick={onManageTopics || (() => setEditing(!editing))} style={{ color: "var(--accent)", background: "var(--accent-soft)" }}>
            Manage
          </button>
        </div>

        <div className="spacer" />
        <div className="toolbar">
          <SearchField value={search} onChange={setSearch} placeholder="Search this feed" />
          <SortMenu value={sort} onChange={setSort} options={sortOpts} />
          <SortMenu value={sourceFilter} onChange={setSourceFilter} options={sourceOpts} />
          <div className="toolbar-seg"><Segmented options={typeOpts} value={type} onChange={setType} /></div>
        </div>

        {loading ? (
          <MasonryWall
            items={[0.8, 1.2, 0.7, 1.0, 1.3, 0.9, 1.1, 0.7, 1.2, 0.8, 1.0, 1.25].map((ratio, id) => ({ id, ratio }))}
            density={density}
            renderItem={(item, i) => <SkeletonCard key={item.id} ratio={item.ratio} index={i} />}
          />
        ) : items.length === 0 ? (
          <Empty
            glyph="photo"
            title={search ? "No results" : "Build your wall"}
            text={search ? `Nothing matches “${search}”. Try another search or filter.` : "Add interests and Velvet fills your wall with a feed you actually like."}
            action={!search && { label: "Browse interests", onClick: goBrowse }}
          />
        ) : (
          <MasonryWall
            items={items}
            density={density}
            renderItem={(it, i) => (
              <Card key={it.id} item={it} index={i} liked={liked.includes(it.id)}
                onOpen={onOpen} onToggleLike={onToggleLike}
                onHide={onHide}
                onMoreLikeThis={onMoreLikeThis}
                onLessLikeThis={onLessLikeThis}
                onBlockTopic={onBlockTopic}
                onFollow={onFollowRecommended} autoplay={autoplay} />
            )}
          />
        )}
      </div>
    );
  }

  /* =================== BROWSE =================== */
  function Browse(props) {
    const { interestList, allInterests, suggested, onAdd, onRemove, gradients } = props;
    const [draft, setDraft] = useState("");
    const [q, setQ] = useState("");
    const has = (label) => interestList.some((i) => i.label.toLowerCase() === label.toLowerCase());

    const submit = () => {
      const v = draft.trim();
      if (!v) return;
      onAdd(v);
      setDraft("");
    };
    const filteredSugg = suggested.filter((s) => s.toLowerCase().includes(q.toLowerCase()));

    return (
      <div className="page">
        <div className="large-head">
          <div className="large-title">Browse</div>
          <div className="large-sub">Add interests to shape your wall</div>
        </div>
        <div className="spacer-sm" />
        <SearchField value={q} onChange={setQ} placeholder="Search interests" />

        <div className="spacer" />
        <div className="section-label">Add your own</div>
        <div className="spacer-sm" />
        <div style={{ display: "flex", gap: 10 }}>
          <div className="field" style={{ flex: 1 }}>
            <input value={draft} placeholder="e.g. Long Exposure"
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && submit()} />
          </div>
          <button className="btn filled" disabled={!draft.trim()} onClick={submit}>Add</button>
        </div>

        <div className="spacer" />
        <div className="section-label">Your interests</div>
        <div className="spacer-sm" />
        <div className="chips" style={{ flexWrap: "wrap" }}>
          {interestList.map((it) => (
            <Chip key={it.id} label={it.label} icon={it.icon} editing={!it.system}
              onRemove={() => onRemove(it.id)} onClick={() => {}} />
          ))}
        </div>

        <div className="spacer" />
        <div className="section-label">Suggested</div>
        <div className="sugg-grid">
          {filteredSugg.map((s, i) => {
            const added = has(s);
            return (
              <div key={s} className="sugg" style={{ background: gradients[(i * 3 + 1) % gradients.length] }}
                onClick={() => (added ? null : onAdd(s))}>
                <span>{s}</span>
                {added && <span className="added"><Icon name="check" size={13} weight={3} /></span>}
              </div>
            );
          })}
        </div>
        <div className="spacer" />
      </div>
    );
  }

  /* =================== SAVED =================== */
  function Saved(props) {
    const { items, liked, onOpen, onToggleLike, onHide, onMoreLikeThis, onLessLikeThis, onBlockTopic, autoplay, density, goWall, nsfw, revealed, onReveal } = props;
    return (
      <div className="page">
        <div className="large-head">
          <div className="large-title">Saved</div>
          <div className="large-sub">{items.length} {items.length === 1 ? "item" : "items"}</div>
        </div>
        <div className="spacer" />
        {items.length === 0 ? (
          <Empty glyph="bookmark" title="Nothing saved yet"
            text="Tap the heart on anything in your wall and it lands here."
            action={{ label: "Go to Wall", onClick: goWall }} />
        ) : (
          <MasonryWall
            items={items}
            density={density}
            renderItem={(it, i) => (
              <Card key={it.id} item={it} index={i} liked={liked.includes(it.id)}
                onOpen={onOpen} onToggleLike={onToggleLike} onHide={onHide} onMoreLikeThis={onMoreLikeThis} onLessLikeThis={onLessLikeThis} onBlockTopic={onBlockTopic} autoplay={autoplay} />
            )}
          />
        )}
        <div className="spacer" />
      </div>
    );
  }

  /* =================== SETTINGS =================== */
  const ACCENTS = [
    { id: "pink", color: "#ff2d55", press: "#e02448", name: "Velvet" },
    { id: "blue", color: "#0a84ff", press: "#0066cc", name: "Blue" },
    { id: "purple", color: "#bf5af2", press: "#a23ad6", name: "Purple" },
    { id: "orange", color: "#ff9f0a", press: "#e08600", name: "Orange" },
  ];
  function Settings(props) {
    const { theme, setTheme, accent, setAccent, autoplay, setAutoplay, loop, setLoop, sort, sourceFilter, setSourceFilter, density, setDensity, onReload, savedCount, hiddenCount, onClearHidden, onClearPreferences, nsfw, onSetNsfw } = props;
    const [confirm, setConfirm] = useState(false);
    const themeOpts = [
      { value: "light", label: "Light" }, { value: "dark", label: "Dark" }, { value: "system", label: "System" },
    ];
    const sourceOpts = [
      { value: "all", label: "All" }, { value: "redgifs", label: "Redgifs" },
      { value: "eporner", label: "Eporner" }, { value: "reddit", label: "Reddit" },
    ];
    const densityOpts = [
      { value: "compact", label: "Compact" }, { value: "regular", label: "Regular" }, { value: "large", label: "Large" },
    ];
    return (
      <div className="page">
        <div className="large-head"><div className="large-title">Settings</div></div>
        <div className="spacer-sm" />

        <div className="group">
          <div className="group-title">Appearance</div>
          <div className="list">
            <div className="row">
              <span className="ricon" style={{ background: "linear-gradient(135deg,#5e5ce6,#bf5af2)" }}>
                <Icon name="moon" size={17} weight={2} /></span>
              <span className="rlabel">Theme</span>
              <Segmented options={themeOpts} value={theme} onChange={setTheme} />
            </div>
            <div className="row">
              <span className="ricon" style={{ background: nsfw ? "linear-gradient(135deg,#e0114c,#2a0509)" : (accent === "pink" ? "linear-gradient(135deg,#ff5e8a,#ff2d55)" : "var(--accent)") }}>
                <Icon name="drop" size={17} weight={2} /></span>
              <span className="rlabel">Accent</span>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                {ACCENTS.map((a) => (
                  <button key={a.id} onClick={() => { if (nsfw) onSetNsfw(false); setAccent(a.id); }} aria-label={a.name}
                    style={{ width: 26, height: 26, borderRadius: "50%", background: a.color,
                      boxShadow: (!nsfw && accent === a.id) ? `0 0 0 2px var(--bg), 0 0 0 4px ${a.color}` : "none",
                      transition: "box-shadow .2s" }} />
                ))}
                <button className="swatch-ad" aria-label="After Dark" onClick={() => (nsfw ? null : setConfirm(true))}
                  style={{ boxShadow: nsfw ? "0 0 0 2px var(--bg), 0 0 0 4px #e0114c" : "none" }}>
                  <Icon name="moon" size={13} weight={2} />
                </button>
              </div>
            </div>
          </div>
          <div className="group-foot">After Dark reveals 18+ content and switches Velvet to a private dark theme.</div>
        </div>

        <div className="group">
          <div className="group-title">Playback</div>
          <div className="list">
            <div className="row">
              <span className="ricon" style={{ background: "#34c759" }}><Icon name="bolt" size={16} weight={2} /></span>
              <span className="rlabel">Autoplay media</span>
              <Switch on={autoplay} onChange={setAutoplay} />
            </div>
            <div className="row">
              <span className="ricon" style={{ background: "#ff9f0a" }}><Icon name="reload" size={16} weight={2} /></span>
              <span className="rlabel">Loop GIFs</span>
              <Switch on={loop} onChange={setLoop} />
            </div>
          </div>
          <div className="group-foot">Autoplay shows live previews on the wall. Off saves data and battery.</div>
        </div>

        <div className="group">
          <div className="group-title">Feed</div>
          <div className="list">
            <div className="row tappable" onClick={onReload}>
              <span className="ricon" style={{ background: "#0a84ff" }}><Icon name="reload" size={16} weight={2} /></span>
              <span className="rlabel">Reload wall</span>
              <Icon name="chevRight" size={17} weight={2.2} style={{ color: "var(--label-3)" }} />
            </div>
            <div className="row">
              <span className="ricon" style={{ background: "#ff2d55" }}><Icon name="bolt" size={16} weight={2} /></span>
              <span className="rlabel">Default sort</span>
              <span className="rvalue" style={{ textTransform: "capitalize" }}>{sort}</span>
            </div>
            <div className="row">
              <span className="ricon" style={{ background: "#5856d6" }}><Icon name="grid" size={15} weight={2} /></span>
              <span className="rlabel">Source mix</span>
              <Segmented options={sourceOpts} value={sourceFilter} onChange={setSourceFilter} />
            </div>
            <div className="row">
              <span className="ricon" style={{ background: "#0a84ff" }}><Icon name="sliders" size={15} weight={2} /></span>
              <span className="rlabel">Density</span>
              <Segmented options={densityOpts} value={density} onChange={setDensity} />
            </div>
            <div className="row tappable" onClick={hiddenCount ? onClearHidden : undefined}>
              <span className="ricon" style={{ background: "#8e8e93" }}><Icon name="trash" size={15} weight={2} /></span>
              <span className="rlabel">Hidden posts</span>
              <span className="rvalue">{hiddenCount || 0}</span>
            </div>
          </div>
        </div>

        <div className="group">
          <div className="group-title">Privacy</div>
          <div className="list">
            <div className="row tappable danger" onClick={onClearPreferences}>
              <span className="ricon" style={{ background: "#ff3b30" }}><Icon name="trash" size={15} weight={2} /></span>
              <span className="rlabel">Clear local preferences</span>
              <Icon name="chevRight" size={17} weight={2.2} style={{ color: "var(--label-3)" }} />
            </div>
          </div>
          <div className="group-foot">Clears interests, saved items, hidden posts, and device preferences from this browser.</div>
        </div>

        <div className="group">
          <div className="group-title">About</div>
          <div className="list">
            <div className="row">
              <span className="ricon" style={{ background: "linear-gradient(135deg,#ff5e8a,#bf5af2)" }}><Icon name="sparkles" size={16} weight={2} /></span>
              <span className="rlabel">Velvet</span>
              <span className="rvalue">2.0</span>
            </div>
          </div>
          <div className="group-foot">Reimagined with the Apple Human Interface Guidelines — SF type, system materials, and a velvet-pink tint.</div>
        </div>
        <div className="spacer" />

        {confirm && (
          <div className="alert-scrim" onClick={() => setConfirm(false)}>
            <div className="alert" onClick={(e) => e.stopPropagation()}>
              <div className="ahead">
                <Mark size={46} className="amark" style={{ borderRadius: 13 }} />
                <h3>Turn on After Dark?</h3>
                <p>This reveals 18+ content and switches Velvet to a private dark theme. You must be 18 or older.</p>
              </div>
              <div className="abtns">
                <button onClick={() => setConfirm(false)}>Cancel</button>
                <button className="primary" onClick={() => { onSetNsfw(true); setConfirm(false); }}>I’m 18+</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
  function Empty({ glyph, title, text, action }) {
    return (
      <div className="empty">
        <div className="glyph"><Icon name={glyph} size={34} weight={1.8} /></div>
        <h3>{title}</h3>
        <p>{text}</p>
        {action && <button className="btn tinted" style={{ marginTop: 4 }} onClick={action.onClick}>{action.label}</button>}
      </div>
    );
  }

  function useWallColumnCount(density = "regular") {
    const read = () => {
      const width = window.innerWidth || 1280;
      const adjust = density === "compact" ? 1 : density === "large" ? -1 : 0;
      if (width <= 640) return Math.max(1, Math.min(3, 2 + adjust));
      if (width <= 920) return Math.max(2, 3 + adjust);
      if (width <= 1200) return Math.max(2, 4 + adjust);
      return Math.max(3, 5 + adjust);
    };
    const [count, setCount] = useState(read);
    useEffect(() => {
      const onResize = () => setCount(read());
      setCount(read());
      window.addEventListener("resize", onResize, { passive: true });
      return () => window.removeEventListener("resize", onResize);
    }, [density]);
    return count;
  }

  function MasonryWall({ items, renderItem, density }) {
    const columnCount = useWallColumnCount(density);
    const columns = useMemo(() => {
      const next = Array.from({ length: columnCount }, () => ({ height: 0, items: [] }));
      items.forEach((item, index) => {
        const target = next.reduce((best, col, colIndex) => col.height < next[best].height ? colIndex : best, 0);
        next[target].items.push({ item, index });
        next[target].height += Number(item.ratio || 1) + 0.18;
      });
      return next;
    }, [items, columnCount]);
    return (
      <div className="wall" style={{ "--cols": columnCount }}>
        {columns.map((column, columnIndex) => (
          <div className="wall-column" key={columnIndex}>
            {column.items.map(({ item, index }) => renderItem(item, index))}
          </div>
        ))}
      </div>
    );
  }

  /* =================== REELS PLAYER (full-screen vertical viewer) =================== */
  function parseDur(d) { if (!d) return 6; const p = d.split(":").map(Number); return (p[0] || 0) * 60 + (p[1] || 0); }
  function embedSrc(src, active, autoplay) {
    if (!src) return "";
    try {
      const url = new URL(src, window.location.origin);
      if (active && autoplay) {
        url.searchParams.set("autoplay", "1");
        url.searchParams.set("mute", "1");
      }
      return url.toString();
    } catch {
      return src;
    }
  }

  function ReelsPlayer({ items, index, setIndex, onClose, liked, onToggleLike, onHide, onMoreLikeThis, onLessLikeThis, onBlockTopic, autoplay, setAutoplay, onTopic }) {
    const scRef = React.useRef(null);
    const progRef = React.useRef(0);
    const progLock = React.useRef(false);
    const lockT = React.useRef(null);
    const hideT = React.useRef(null);
    const press = React.useRef(null);
    const holdT = React.useRef(null);
    const [progress, setProgress] = useState(0);
    const [paused, setPaused] = useState(false);
    const [hold, setHold] = useState(false);
    const [chrome, setChrome] = useState(true);
    const item = items[index];

    const go = useCallback((n, smooth) => {
      const el = scRef.current; if (!el) return;
      const c = Math.max(0, Math.min(items.length - 1, n));
      progLock.current = true;
      el.scrollTo({ top: c * el.clientHeight, behavior: smooth ? "smooth" : "auto" });
      setIndex(c);
      clearTimeout(lockT.current);
      lockT.current = setTimeout(() => { progLock.current = false; }, smooth ? 460 : 60);
    }, [items.length, setIndex]);

    // initial scroll position
    useEffect(() => { go(index, false); /* eslint-disable-next-line */ }, []);

    const onScroll = () => {
      const el = scRef.current; if (!el || progLock.current) return;
      const n = Math.round(el.scrollTop / el.clientHeight);
      if (n !== index) setIndex(n);
    };

    // reset progress on item change
    useEffect(() => { progRef.current = 0; setProgress(0); }, [index]);

    // chrome auto-hide
    const wake = useCallback(() => {
      setChrome(true);
      clearTimeout(hideT.current);
      hideT.current = setTimeout(() => setChrome(false), 2800);
    }, []);
    useEffect(() => { wake(); return () => clearTimeout(hideT.current); }, [index, wake]);

    // autoplay progress -> auto-advance
    useEffect(() => {
      if (!autoplay || paused) return;
      const dur = item && item.type === "video" ? Math.min(parseDur(item.dur), 12) : 6;
      const tickMs = 70;
      const id = setInterval(() => {
        progRef.current += ((tickMs / 1000) * (hold ? 2 : 1)) / dur;
        if (progRef.current >= 1) {
          progRef.current = 0; setProgress(0);
          go(index + 1 >= items.length ? 0 : index + 1, true);
        } else setProgress(progRef.current);
      }, tickMs);
      return () => clearInterval(id);
    }, [autoplay, paused, hold, index, item, items.length, go]);

    // keyboard
    useEffect(() => {
      const h = (e) => {
        if (e.key === "Escape") onClose();
        else if (e.key === "ArrowDown" || e.key === "ArrowRight") { go(index + 1, true); wake(); }
        else if (e.key === "ArrowUp" || e.key === "ArrowLeft") { go(index - 1, true); wake(); }
        else if (e.key === " ") { e.preventDefault(); setPaused((v) => !v); wake(); }
      };
      window.addEventListener("keydown", h);
      return () => window.removeEventListener("keydown", h);
    }, [index, go, onClose, wake]);

    // tap vs press-hold(2x) vs swipe
    const down = (e) => {
      press.current = { y: e.clientY, x: e.clientX, t: Date.now(), moved: false };
      clearTimeout(holdT.current);
      holdT.current = setTimeout(() => { setHold(true); wake(); }, 240);
    };
    const move = (e) => {
      const p = press.current; if (!p) return;
      if (Math.abs(e.clientY - p.y) > 8 || Math.abs(e.clientX - p.x) > 8) { p.moved = true; clearTimeout(holdT.current); }
    };
    const up = () => {
      clearTimeout(holdT.current);
      const p = press.current; press.current = null;
      if (hold) { setHold(false); return; }
      if (p && !p.moved && Date.now() - p.t < 240) { setPaused((v) => !v); wake(); }
    };

    if (!item) return null;
    const hideCls = chrome ? "" : " hide-chrome";

    return (
      <div className="reels">
        <div className={"reels-top" + hideCls}>
          <button className="icon-btn" onClick={onClose} aria-label="Close"><Icon name="chevDown" size={20} weight={2.2} /></button>
          <div className="reels-prog-wrap">
            {autoplay && <div className="reels-prog"><span style={{ width: progress * 100 + "%" }} /></div>}
          </div>
          <button className={"pill-toggle " + (autoplay ? "on" : "")} onClick={() => { setAutoplay(!autoplay); wake(); }}>
            <Icon name={autoplay ? "pause" : "play"} size={13} /> {autoplay ? "Autoplay on" : "Autoplay"}
          </button>
        </div>

        {hold && <div className="badge-2x"><Icon name="play" size={13} /> 2× speed</div>}

        <div className="reels-scroll" ref={scRef} onScroll={onScroll} onMouseMove={wake}>
          {items.map((it, i) => {
            const isCur = i === index;
            const nearCurrent = Math.abs(i - index) <= 2;
            if (!nearCurrent) return <div className="reel reel-lite" key={it.id} aria-hidden="true" />;
            const mediaClass = "reel-media " + (it.embedURL ? "is-embed" : it.type === "image" ? "is-image" : "is-video");
            return (
              <div className="reel" key={it.id}>
                <div className={mediaClass} style={{ "--ar": `1 / ${it.ratio}` }}
                  onPointerDown={isCur && !it.embedURL ? down : undefined}
                  onPointerMove={isCur && !it.embedURL ? move : undefined}
                  onPointerUp={isCur && !it.embedURL ? up : undefined}
                  onPointerLeave={isCur && !it.embedURL ? up : undefined}>
                  <div className="surface" style={{ background: it.grad }}>
                    {it.embedURL && isCur ? (
                      <iframe
                        src={embedSrc(it.embedURL, isCur, autoplay)}
                        title={it.title}
                        allow="autoplay; fullscreen; encrypted-media; picture-in-picture; web-share"
                        allowFullScreen
                        referrerPolicy="no-referrer"
                      />
                    ) : it.embedURL ? (
                      <img src={it.thumbnailURL} alt="" draggable="false" />
                    ) : it.type === "image" ? (
                      <img src={it.mediaURL || it.thumbnailURL} alt="" draggable="false" />
                    ) : (
                      <video
                        src={it.mediaURL}
                        poster={it.thumbnailURL}
                        autoPlay={isCur && !paused}
                        muted={false}
                        playsInline
                        loop
                        controls={false}
                        preload={isCur ? "auto" : "metadata"}
                        ref={(node) => {
                          if (!node || !isCur) return;
                          node.playbackRate = hold ? 2 : 1;
                          if (paused) node.pause();
                          else node.play().catch(() => {
                            node.muted = true;
                            node.play().catch(() => {});
                          });
                        }}
                      />
                    )}
                  </div>
                  <div className="vignette" />
                </div>
                {isCur && paused && (
                  <div className="reel-center"><div className="glyphbig"><Icon name="play" size={30} /></div></div>
                )}
                {isCur && (
                  <>
                    <div className={"reel-info" + hideCls}>
                      <h2>{it.title}</h2>
                      <div className="meta">{it.source} · {it.interestLabel} · {it.type === "video" ? it.dur : (it.type === "gif" ? "GIF" : "Photo")}</div>
                      <div className="reel-tags">{it.tags.map((t) => (
                        <button key={t} className="tag topic-tag" onClick={() => { onTopic && onTopic(t); }}>
                          {t}
                        </button>
                      ))}</div>
                    </div>
                    <div className={"reel-rail" + hideCls}>
                      <button className={"rail-btn " + (liked.includes(it.id) ? "on" : "")} onClick={() => onToggleLike(it.id)}>
                        <span className="rail-ico"><Icon name={liked.includes(it.id) ? "heartFill" : "heart"} size={22} weight={2} /></span>
                        Save
                      </button>
                      <button className="rail-btn" onClick={() => onMoreLikeThis && onMoreLikeThis(it)}>
                        <span className="rail-ico"><Icon name="sparkles" size={19} weight={2} /></span>
                        More
                      </button>
                      <button className="rail-btn" onClick={() => onLessLikeThis && onLessLikeThis(it)}>
                        <span className="rail-ico"><Icon name="chevDown" size={19} weight={2.2} /></span>
                        Less
                      </button>
                      <button className="rail-btn" onClick={() => onBlockTopic && onBlockTopic(it)}>
                        <span className="rail-ico"><Icon name="xmark" size={18} weight={2.2} /></span>
                        Block
                      </button>
                      <button className="rail-btn" onClick={() => onHide && onHide(it)}>
                        <span className="rail-ico"><Icon name="trash" size={19} weight={2} /></span>
                        Hide
                      </button>
                    </div>
                  </>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  /* =================== PRIVATE GATE (passcode lock) =================== */
  function Gate({ onUnlock }) {
    const [code, setCode] = useState("");
    const [shake, setShake] = useState(false);
    const press = useCallback((d) => {
      if (d === "del") { setCode((c) => c.slice(0, -1)); return; }
      setCode((c) => {
        if (c.length >= 4) return c;
        const n = c + d;
        if (n.length === 4) setTimeout(onUnlock, 200);
        return n;
      });
    }, [onUnlock]);
    useEffect(() => {
      const h = (e) => {
        if (/^[0-9]$/.test(e.key)) press(e.key);
        else if (e.key === "Backspace") press("del");
      };
      window.addEventListener("keydown", h);
      return () => window.removeEventListener("keydown", h);
    }, [press]);
    const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", "del"];
    return (
      <div className="gate">
        <div className="gate-mark"><Mark size={72} /></div>
        <div className="gate-word">Velvet</div>
        <div className="gate-sub">Enter passcode</div>
        <div className={"dots" + (shake ? " shake" : "")}>
          {[0, 1, 2, 3].map((i) => <span key={i} className={code.length > i ? "on" : ""} />)}
        </div>
        <div className="keypad">
          {keys.map((k, i) => k === "" ? <span key={i} className="key blank" /> : (
            <button key={i} className="key" onClick={() => press(k)}>
              {k === "del" ? <Icon name="backspace" size={24} weight={2} /> : k}
            </button>
          ))}
        </div>
        <div className="gate-hint">Private · for your eyes only</div>
      </div>
    );
  }

  Object.assign(window, { NavBar, TabBar, Wall, Browse, Saved, Settings, ReelsPlayer, Gate, ACCENTS });
})();
