/* ═══════════════════════════════════════════════════════════
   Feed rails — desktop shell around the social feed:
   · CBFeedSideRail  — left navigation + City Planner card
   · CBFeedRightRail — Trending Builds, Daily Missions,
     Recent Activity, Create CTA, City Points, quick actions
   Every row navigates to a real screen and every number comes
   from live state (CBGame, CBQuests, wallet, feed API).
   Rendered only ≥1024px (CSS hides them below).
   ═══════════════════════════════════════════════════════════ */
(function() {
  var useState  = React.useState;
  var useEffect = React.useEffect;
  var Icon      = window.CBIcon;

  function hov()  { document.body.classList.add('hov'); }
  function leave(){ document.body.classList.remove('hov'); }

  function go(screen, params) {
    return function() { window.navigate(screen, params || {}); };
  }

  function initialsOf(name) {
    return (name || '?').split(' ').map(function(n){ return n[0] || ''; }).join('').slice(0, 2).toUpperCase();
  }

  /* ── Left sidebar ────────────────────────────────────────── */
  function SideRail(props) {
    /* An explicit '' means "this section has no rail entry" — don't fall
       back to 'feed', which lit up Feed on Missions and every wrapped
       section page. Only a missing prop defaults. */
    var active = props.active == null ? 'feed' : props.active;
    var _pend = useState(window.CBQuests ? window.CBQuests.pendingCount() : 0);
    var pending = _pend[0], setPending = _pend[1];
    var _game = useState(window.CBGame ? window.CBGame.state() : null);
    var game = _game[0], setGame = _game[1];

    useEffect(function() {
      var offQ = window.CBQuests && window.CBQuests.on(function(){ setPending(window.CBQuests.pendingCount()); });
      var offG = window.CBGame && window.CBGame.on(function(){ setGame(window.CBGame.state()); });
      return function() { if (offQ) offQ(); if (offG) offG(); };
    }, []);

    function Item(p) {
      return (
        <button type="button"
          className={'fx-side-item' + (p.id === active ? ' on' : '')}
          onClick={p.onClick} onMouseEnter={hov} onMouseLeave={leave}>
          <span className="fx-side-ico"><Icon name={p.icon} size={17} /></span>
          <span className="fx-side-label">{p.label}</span>
          {p.badge > 0 && <span className="fx-side-badge">{p.badge}</span>}
          {p.id === active && <span className="fx-side-arrow"><Icon name="arrow-right" size={14} /></span>}
        </button>
      );
    }

    function Group(p) { return <div className="fx-side-group">{p.label}</div>; }

    return (
      <aside className="fx-side" aria-label="Sections">
        <nav className="fx-side-nav">
          <Item id="feed"      icon="building"       label="Feed"      onClick={go('home')} />
          <Item id="following" icon="users"          label="Following" onClick={props.onFollowing || go('home')} />
          <Item id="notifs"    icon="zap"            label="Notifications" badge={pending} onClick={go('quests')} />
          <Item id="messages"  icon="mail"           label="Messages"  onClick={go('messages')} />
          <Group label="BUILD" />
          <Item id="proposals" icon="upload"         label="My Proposals"    onClick={go('profile')} />
          <Item id="builds"    icon="box"            label="My Builds"       onClick={go('projects')} />
          <Item id="contrib"   icon="heart"          label="My Contributions" onClick={go('funding')} />
          <Group label="COMMUNITY" />
          <Item id="leaderboard" icon="trophy"         label="Leaderboard" onClick={go('community')} />
          <Item id="teams"       icon="users"          label="Teams"       onClick={go('community')} />
          <Item id="forum"       icon="message-circle" label="Forum"       onClick={go('messages')} />
        </nav>

        {game && (
          <button type="button" className="fx-planner" onClick={go('quests')}
            onMouseEnter={hov} onMouseLeave={leave}>
            <div className="fx-planner-head">
              <span className="fx-planner-title">City Planner</span>
              <span className="fx-planner-level">Level {game.level + 1}</span>
            </div>
            <div className="fx-planner-ring" style={{ '--fx-pct': game.pct }}>
              <span className="fx-planner-ring-core"><Icon name="building" size={22} /></span>
            </div>
            <div className="fx-planner-bar"><span style={{ width: Math.max(4, game.pct) + '%' }} /></div>
            <div className="fx-planner-xp">{game.xp.toLocaleString()} / {game.next.toLocaleString()} XP</div>
            <div className="fx-planner-next">
              Next reward: {Math.max(0, game.next - game.xp)} XP
              <span className="fx-planner-gift"><Icon name="gift" size={14} /></span>
            </div>
          </button>
        )}
      </aside>
    );
  }

  /* ── Right rail ──────────────────────────────────────────── */
  function RightRail(props) {
    var posts = props.posts || [];
    var _daily = useState([]); var daily = _daily[0], setDaily = _daily[1];
    var _pts   = useState(null); var pts = _pts[0], setPts = _pts[1];

    function readDaily() {
      var qs = (window.CB_QUESTS || []).filter(function(q){ return q.cat === 'daily'; }).slice(0, 3);
      return qs.map(function(q) {
        return {
          id: q.id, title: q.title, icon: q.icon, xp: q.xp, target: q.target,
          done: window.CBQuests ? Math.min(q.target, window.CBQuests.progress(q.id)) : 0,
          complete: window.CBQuests ? window.CBQuests.complete(q.id) : false,
        };
      });
    }

    useEffect(function() {
      setDaily(readDaily());
      var offQ = window.CBQuests && window.CBQuests.on(function(){ setDaily(readDaily()); });
      // City Points: BuildCoins wallet when signed in, XP otherwise.
      var setFromGame = function() { if (window.CBGame) setPts({ n: window.CBGame.state().xp, label: 'City Points' }); };
      if (window.AuthState && window.AuthState.isLoggedIn() && window.CBBuildCoins) {
        window.CBBuildCoins.getWallet()
          .then(function(w){ setPts({ n: (w && (w.balance != null ? w.balance : (w.wallet && w.wallet.balance))) || 0, label: 'BuildCoins' }); })
          .catch(setFromGame);
      } else setFromGame();
      var offG = window.CBGame && window.CBGame.on(function() {
        if (!(window.AuthState && window.AuthState.isLoggedIn())) setFromGame();
      });
      return function() { if (offQ) offQ(); if (offG) offG(); };
    }, []);

    /* Trending = live feed ranked by engagement; activity = real comments/likes */
    var trending = posts.slice()
      .sort(function(a, b){ return (b.engagementScore || 0) - (a.engagementScore || 0); })
      .slice(0, 5);

    var activity = [];
    posts.forEach(function(p) {
      (p.topComments || []).forEach(function(c) {
        activity.push({ id: 'c' + c._id, who: (c.author && c.author.name) || 'Builder',
          what: 'commented on ' + p.title, when: c.createdAt, ava: c.author && c.author.avatar, icon: 'message-circle' });
      });
      if (p.likes > 0) activity.push({ id: 'l' + p.id, who: p.likes + (p.likes === 1 ? ' builder' : ' builders'),
        what: 'liked ' + p.title, when: p.createdAt, ava: null, icon: 'heart' });
    });
    activity = activity.slice(0, 4);

    function pct(p) {
      if (!p.funding || !p.funding.goal) return null;
      return Math.min(100, Math.round((p.funding.raised / p.funding.goal) * 100));
    }

    function QuickBtn(p) {
      return (
        <button type="button" className="fx-quick-btn" onClick={p.onClick}
          onMouseEnter={hov} onMouseLeave={leave}>
          <span className="fx-quick-ico"><Icon name={p.icon} size={20} /></span>
          <span className="fx-quick-label">{p.label}</span>
        </button>
      );
    }

    return (
      <aside className="fx-right" aria-label="Community panels">
        <div className="fx-right-col">
          {trending.length > 0 && (
            <section className="fx-panel">
              <header className="fx-panel-head">
                <h3>Trending Builds</h3>
                <button type="button" className="fx-panel-more" onClick={go('projects')}
                  onMouseEnter={hov} onMouseLeave={leave}>View All</button>
              </header>
              {trending.map(function(p, i) {
                var f = pct(p);
                return (
                  <button type="button" key={p.id} className="fx-trend-row"
                    onClick={go('project-detail', { id: p.id })}
                    onMouseEnter={hov} onMouseLeave={leave}>
                    <span className="fx-trend-rank">{i + 1}</span>
                    <span className="fx-trend-thumb">
                      {p.afterUrl ? <img src={p.afterUrl} alt="" loading="lazy" /> : <Icon name="building" size={16} />}
                    </span>
                    <span className="fx-trend-meta">
                      <span className="fx-trend-title">{p.title}</span>
                      <span className="fx-trend-sub">{f != null ? f + '% funded' : (p.likes || 0) + ' likes'}</span>
                    </span>
                  </button>
                );
              })}
            </section>
          )}

          {daily.length > 0 && (
            <section className="fx-panel">
              <header className="fx-panel-head">
                <h3>Daily Missions</h3>
                <button type="button" className="fx-panel-more" onClick={go('quests')}
                  onMouseEnter={hov} onMouseLeave={leave}>View All</button>
              </header>
              {daily.map(function(q) {
                return (
                  <button type="button" key={q.id} className="fx-mission-row" onClick={go('quests')}
                    onMouseEnter={hov} onMouseLeave={leave}>
                    <span className={'fx-mission-ico' + (q.complete ? ' done' : '')}>
                      <Icon name={q.complete ? 'check' : q.icon} size={16} />
                    </span>
                    <span className="fx-mission-meta">
                      <span className="fx-mission-top">
                        <span className="fx-mission-title">{q.title}</span>
                        <span className="fx-mission-count">{q.done}/{q.target}</span>
                      </span>
                      <span className={'fx-mission-bar' + (q.complete ? ' done' : '')}>
                        <span style={{ width: Math.max(4, Math.round((q.done / q.target) * 100)) + '%' }} />
                      </span>
                    </span>
                    <span className="fx-mission-xp">{q.xp} XP</span>
                  </button>
                );
              })}
            </section>
          )}

          {activity.length > 0 && (
            <section className="fx-panel">
              <header className="fx-panel-head">
                <h3>Recent Activity</h3>
                <button type="button" className="fx-panel-more" onClick={go('community')}
                  onMouseEnter={hov} onMouseLeave={leave}>View All</button>
              </header>
              {activity.map(function(a) {
                return (
                  <div key={a.id} className="fx-act-row">
                    <span className="fx-act-ava">
                      {a.ava ? <img src={a.ava} alt="" loading="lazy" /> : <Icon name={a.icon} size={14} />}
                    </span>
                    <span className="fx-act-meta">
                      <span className="fx-act-who">{a.who}</span>
                      <span className="fx-act-what">{a.what}</span>
                    </span>
                  </div>
                );
              })}
            </section>
          )}
        </div>

        <div className="fx-actions-col">
          <button type="button" className="fx-create" onClick={go('submit')}
            onMouseEnter={hov} onMouseLeave={leave}>
            <Icon name="plus" size={16} /> Create
          </button>

          {pts && (
            <button type="button" className="fx-points" onClick={go('wallet')}
              onMouseEnter={hov} onMouseLeave={leave}>
              <span className="fx-points-gem"><Icon name="box" size={22} /></span>
              <span className="fx-points-n">{pts.n.toLocaleString()}</span>
              <span className="fx-points-label">{pts.label}</span>
            </button>
          )}

          <div className="fx-quick">
            <QuickBtn icon="scan"     label="Scan Site"  onClick={go('submit')} />
            <QuickBtn icon="radio"    label="AR Walk"    onClick={go('ar-demo')} />
            <QuickBtn icon="sparkles" label="AI Vision"  onClick={go('submit')} />
            <QuickBtn icon="check"    label="Quick Vote" onClick={go('projects')} />
            <QuickBtn icon="gift"     label="Donate"     onClick={go('funding')} />
          </div>
        </div>
      </aside>
    );
  }

  window.CBFeedSideRail  = SideRail;
  window.CBFeedRightRail = RightRail;
})();
