/* ui_kits/watchover-app/App.jsx
   State machine + routing for the Watchover family phone.
   Screens: child-home (resting state) · watch · pin · parent-home ·
   review-queue · channel-detail. Child mode is the default; parent
   mode sits behind the PIN gate (1234). useState only — no router.
   Attaches to window.WatchoverApp.                                */

(function () {
  function WatchoverApp() {
    const D = window.WoData;
    const S = window.WoScreens;
    const kid = D.kids.find((k) => k.active) || D.kids[0];

    const [screen, setScreen] = React.useState('child-home'); // the family phone rests in child mode
    const [watchId, setWatchId] = React.useState(D.videos[0].id);
    const [detailId, setDetailId] = React.useState(null);
    const [detailFrom, setDetailFrom] = React.useState('home'); // 'home' | 'queue'
    const [whitelistIds, setWhitelistIds] = React.useState(D.channels.map((c) => c.id));
    const [queueStatus, setQueueStatus] = React.useState(() =>
      Object.fromEntries(D.reviewQueue.map((q) => [q.id, 'pending']))
    );
    const balance = D.balance;

    const allChannels = React.useMemo(() => [...D.channels, ...D.reviewQueue], []);
    const channelById = (id) => allChannels.find((c) => c.id === id);

    const whitelist = whitelistIds.map(channelById).filter(Boolean);
    const queue = D.reviewQueue.map((q) => ({ ...q, status: queueStatus[q.id] }));
    const pendingCount = queue.filter((q) => q.status === 'pending').length;

    /* ── Actions ─────────────────────────────────────────── */
    const approve = (id) => {
      setQueueStatus((s) => ({ ...s, [id]: 'approved' }));
      setWhitelistIds((ids) => (ids.includes(id) ? ids : [...ids, id]));
    };
    const dismiss = (id) => setQueueStatus((s) => ({ ...s, [id]: 'dismissed' }));
    const removeFromWhitelist = (id) => {
      setWhitelistIds((ids) => ids.filter((x) => x !== id));
      setScreen('parent-home');
    };
    const openDetail = (id, from) => {
      setDetailId(id);
      setDetailFrom(from);
      setScreen('channel-detail');
    };

    /* ── Routing ─────────────────────────────────────────── */
    if (screen === 'watch') {
      const video = D.videos.find((x) => x.id === watchId) || D.videos[0];
      const channel = channelById(video.channelId);
      const upNext = D.videos
        .filter((x) => x.id !== video.id && whitelistIds.includes(x.channelId))
        .slice(0, 5)
        .map((x) => ({ v: x, c: channelById(x.channelId) }));
      return (
        <S.WatchScreen
          key={video.id} /* remount on switch — never auto-advance */
          video={video}
          channel={channel}
          upNext={upNext}
          onBack={() => setScreen('child-home')}
          onSelect={(id) => setWatchId(id)}
        />
      );
    }

    if (screen === 'pin') {
      return (
        <S.PinUnlock
          onBack={() => setScreen('child-home')}
          onUnlock={() => setScreen('parent-home')}
        />
      );
    }

    if (screen === 'parent-home') {
      return (
        <S.ParentHome
          kid={kid}
          channels={whitelist}
          pendingCount={pendingCount}
          balance={balance}
          onOpenQueue={() => setScreen('review-queue')}
          onOpenChannel={(id) => openDetail(id, 'home')}
          onHandBack={() => setScreen('child-home')}
        />
      );
    }

    if (screen === 'review-queue') {
      return (
        <S.ReviewQueue
          kid={kid}
          queue={queue}
          balance={balance}
          onBack={() => setScreen('parent-home')}
          onOpenDetail={(id) => openDetail(id, 'queue')}
          onApprove={approve}
          onDismiss={dismiss}
          onGoWhitelist={() => setScreen('parent-home')}
        />
      );
    }

    if (screen === 'channel-detail') {
      const channel = channelById(detailId) || allChannels[0];
      const status = detailFrom === 'home' ? 'whitelisted' : queueStatus[channel.id];
      return (
        <S.ChannelDetail
          kid={kid}
          channel={channel}
          status={status}
          balance={balance}
          onBack={() =>
            setScreen(detailFrom === 'queue' ? 'review-queue' : 'parent-home')
          }
          onApprove={() => {
            approve(channel.id);
            setScreen('review-queue');
          }}
          onDismiss={() => {
            dismiss(channel.id);
            setScreen('review-queue');
          }}
          onRemove={() => removeFromWhitelist(channel.id)}
        />
      );
    }

    /* Default — child-home, the resting state of the family phone. */
    return (
      <S.ChildHome
        kid={kid}
        channels={whitelist}
        videos={D.videos.filter((x) => whitelistIds.includes(x.channelId))}
        onWatch={(id) => {
          setWatchId(id);
          setScreen('watch');
        }}
        onOpenPin={() => setScreen('pin')}
      />
    );
  }

  window.WatchoverApp = WatchoverApp;
})();
