/* global React, GAMES, COLLECTIONS, Icon, CoinIcon, Progress, t, useProfile, SHASTE_API, SHASTE_HUB_TOASTS */



const STREAK_DAY_KEYS = [
  'streak_days', 'streakDays', 'daily_streak_days', 'daily_streak',
  'login_streak_days', 'login_streak', 'streak',
];

function readStreakDays(source) {
  for (let i = 0; i < STREAK_DAY_KEYS.length; i += 1) {
    const key = STREAK_DAY_KEYS[i];
    const value = Number(source && source[key]);
    if (Number.isFinite(value) && value >= 0) return value;
  }
  return 0;
}

function HomePage({ setPage, newsItems }) {
  const profile = useProfile();
  const featured = GAMES[0]; // Chimera Haven as hero

  const [latestNews, setLatestNews] = React.useState(Array.isArray(newsItems) ? newsItems : []);
  const [isNewsLoading, setIsNewsLoading] = React.useState(true);
  const [newsError, setNewsError] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;

    async function loadNews() {
      setIsNewsLoading(true);
      setNewsError(null);
      try {
        const response = await fetch('/content/news.json');
        const payload = await response.json();
        const ordered = (Array.isArray(payload) ? payload : [])
          .slice()
          .sort((a, b) => new Date(b.date || 0).getTime() - new Date(a.date || 0).getTime())
          .slice(0, 3);
        if (!cancelled) {
          setLatestNews(ordered);
        }
      } catch (err) {
        if (!cancelled) {
          setNewsError(err);
          setLatestNews([]);
        }
      } finally {
        if (!cancelled) {
          setIsNewsLoading(false);
        }
      }
    }

    loadNews();
    return () => { cancelled = true; };
  }, []);

  const profileData = profile.data || null;
  const tier = (profileData && profileData.tier ? String(profileData.tier) : '').toLowerCase();
  const supporter = tier.includes('gold')
    ? 'gold'
    : tier.includes('silver')
      ? 'silver'
      : tier.includes('bronze')
        ? 'bronze'
        : 'none';
  const isAuthenticated = Boolean(
    profileData
    && (
      profileData.is_authenticated === true
      || profileData.isAuthenticated === true
      || profileData.authenticated === true
      || profileData.user_id
      || profileData.id
    )
  );
  const isGuest = !isAuthenticated;
  const isFollower = Boolean(profileData && (profileData.follower || supporter !== 'none'));
  const recurringObjectives = Array.isArray(profileData && profileData.recurring_objectives)
    ? profileData.recurring_objectives
    : [];
  const [isClaimingDaily, setIsClaimingDaily] = React.useState(false);
  const profileStreakDays = readStreakDays(profileData);
  const canClaimDaily = Boolean(profileData && profileData.can_claim_daily);

  const claimDaily = React.useCallback(async () => {
    if (isClaimingDaily) return;
    if (!SHASTE_API || typeof SHASTE_API.claimDaily !== 'function') return;

    setIsClaimingDaily(true);
    try {
      const result = await SHASTE_API.claimDaily();
      const claimedDays = readStreakDays(result) || readStreakDays(result && result.profile) || profileStreakDays + 1;
      if (!window.SHASTE_HUB_TOASTS || window.SHASTE_HUB_TOASTS.attachStreakToast(result) !== true) {
        window.SHASTE_HUB_TOASTS?.showClaimSuccess(claimedDays);
      }
      await profile.refetch(true);
    } catch (e) {
      // Fail silently to match existing hub API affordances.
    } finally {
      setIsClaimingDaily(false);
    }
  }, [isClaimingDaily, profile, profileStreakDays]);

  // Context-aware upsell, the most important one first for this user
  let upsell;
  if (profile.loading) {
    upsell = null;
  } else if (isGuest) {
    upsell = { kind: 'login', title: t('home.sign_in_title'), sub: t('home.sign_in_sub'), cta: t('action.login_free'), icon: 'user' };
  } else if (!isFollower) {
    upsell = { kind: 'follow', title: t('home.follow_title'), sub: t('home.follow_sub'), cta: t('action.follow'), icon: 'heart' };
  } else if (supporter === 'none') {
    upsell = { kind: 'patreon', title: t('home.support_title'), sub: t('home.support_sub'), cta: t('action.support'), icon: 'support' };
  } else {
    upsell = { kind: 'referral', title: t('home.invite_title'), sub: t('home.invite_sub'), cta: t('action.share_link'), icon: 'gift' };
  }

  const goPlay = (slug) => {
    window.location.href = `/play/?slug=${encodeURIComponent(slug)}`;
  };

  return (
    <div className="container fade-in">
      {/* HERO */}
      <section className="hero">
        <div className="hero__featured">
          <img
            src={featured.img}
            alt={featured.title}
            onError={(e) => { e.target.style.display = 'none'; }}
          />
          <div className="hero__body">
            <div className="hero__tags">
              <span className="tag tag--featured">{t('home.featured')}</span>
              <span className="tag">{COLLECTIONS[featured.collection].label}</span>
              <span className="tag tag--coin"><CoinIcon size={11} /> {t('home.earn_up_to')}</span>
            </div>
            <h1 className="hero__title">{featured.title}</h1>
            <p className="hero__blurb">{COLLECTIONS[featured.collection].sub}</p>
            <div className="hero__actions">
              <button className="btn btn--primary btn--lg" onClick={() => goPlay(featured.slug)}>
                <Icon name="play" size={16}/> {t('action.play_now')}
              </button>
              <button
                className="btn btn--ghost btn--lg"
                onClick={() => { window.location.href = featured.aboutUrl; }}
              >
                {t('action.about_game')}
              </button>
            </div>
          </div>
        </div>

        <div className="hero__rail">
          <div className="quest">
            <div className="quest__eye"><Icon name="bolt" size={12}/> {t('home.daily_quest')}</div>
            <div className="quest__ttl">{t('home.daily_quest_title')}</div>
            {profile.loading ? (
              <>
                {[0, 1].map((idx) => (
                  <div key={idx} style={{ padding: '8px 0', borderTop: idx ? '1px solid var(--hairline)' : 'none' }}>
                    <div style={{ height: 12, background: 'var(--surface-2)', borderRadius: 6, marginBottom: 8 }} />
                    <div style={{ height: 10, background: 'var(--surface-2)', borderRadius: 6 }} />
                  </div>
                ))}
              </>
            ) : recurringObjectives.length ? (
              recurringObjectives.map((objective, idx) => {
                const currentRaw = Number(objective.current_progress ?? objective.current ?? objective.progress ?? objective.value ?? 0);
                const targetRaw = Number(objective.target_progress ?? objective.target ?? objective.goal ?? objective.max ?? 0);
                const current = Number.isFinite(currentRaw) ? Math.max(0, currentRaw) : 0;
                const target = Number.isFinite(targetRaw) && targetRaw > 0 ? targetRaw : 1;
                const progress = Math.max(0, Math.min(1, current / target));
                const rewardCoins = Number(objective.reward_coins ?? objective.coins ?? objective.coin_reward ?? 0) || 0;
                const rewardXp = Number(objective.reward_xp ?? objective.xp ?? objective.xp_reward ?? 0) || 0;
                return (
                  <div key={objective.id || objective.slug || objective.name || idx} style={{ padding: '8px 0', borderTop: idx ? '1px solid var(--hairline)' : 'none' }}>
                    <div style={{ fontSize: 12, marginBottom: 6 }}>{objective.title || objective.name || t('home.daily_quest_title')}</div>
                    <Progress value={progress} color="var(--coin)" />
                    <div className="quest__meta">
                      <span>{current} / {target}</span>
                      <span className="quest__reward"><CoinIcon size={14}/> {rewardCoins} · {rewardXp} XP</span>
                    </div>
                  </div>
                );
              })
            ) : (
              <div className="quest__meta">
                <span>{t('home.quest_unlock')}</span>
                <span className="quest__reward"><CoinIcon size={14}/> 0 · 0 XP</span>
              </div>
            )}
          </div>

          <div className="daily-login-card card" style={{ padding: 18 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Daily login</div>
            <div className="daily-login-card__row">
              <div>
                <div className="daily-login-card__days tabular">{profileStreakDays} day{profileStreakDays === 1 ? '' : 's'}</div>
                <div className="daily-login-card__subtle">Current streak</div>
              </div>
              {canClaimDaily ? (
                <button
                  className="btn btn--primary btn--sm"
                  onClick={claimDaily}
                  disabled={isClaimingDaily}
                >
                  {isClaimingDaily ? 'Claiming…' : 'Claim'}
                </button>
              ) : (
                <span className="daily-login-card__claimed">Claimed</span>
              )}
            </div>
          </div>

          {/* Contextual upsell */}
          {profile.loading ? (
            <div className="upsell upsell--login">
              <div className="upsell__ic"><Icon name="user" size={20}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ height: 14, width: '70%', background: 'var(--surface-2)', borderRadius: 8, marginBottom: 8 }} />
                <div style={{ height: 12, width: '95%', background: 'var(--surface-2)', borderRadius: 8 }} />
              </div>
              <div style={{ width: 92, height: 28, background: 'var(--surface-2)', borderRadius: 14 }} />
            </div>
          ) : (
            <div className={`upsell upsell--${upsell.kind}`}>
              <div className="upsell__ic"><Icon name={upsell.icon} size={20}/></div>
              <div>
                <p className="upsell__ttl">{upsell.title}</p>
                <p className="upsell__sub">{upsell.sub}</p>
              </div>
              <button
                className="btn btn--primary btn--sm"
                onClick={() => setPage(
                  upsell.kind === 'referral' ? 'referral' :
                  upsell.kind === 'patreon' ? 'support' :
                  upsell.kind === 'follow' ? 'profile' :
                  'login'
                )}
              >
                {upsell.cta}<Icon name="arrow" size={13}/>
              </button>
            </div>
          )}

          {/* Latest news */}
          <div className="card" style={{ padding: 18 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>{t('home.latest_updates')}</div>
            {isNewsLoading ? (
              [0, 1, 2].map((idx) => (
                <div key={idx} style={{ padding: '8px 0', borderTop: idx ? '1px solid var(--hairline)' : 'none' }}>
                  <div style={{ height: 11, width: '40%', background: 'var(--surface-2)', borderRadius: 6, marginBottom: 8 }} />
                  <div style={{ height: 12, width: '100%', background: 'var(--surface-2)', borderRadius: 6 }} />
                </div>
              ))
            ) : newsError ? (
              <div style={{ color: 'var(--subtle)' }}>—</div>
            ) : latestNews.map((n, i) => (
              <div
                key={n.slug || i}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '70px 1fr',
                  gap: 12,
                  padding: '8px 0',
                  borderTop: i ? '1px solid var(--hairline)' : 'none',
                  cursor: 'pointer',
                }}
                onClick={() => setPage('news')}
              >
                <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', color: 'var(--subtle)' }}>{n.date || ''}</span>
                <div>
                  <span className="tag" style={{ fontSize: 9, padding: '2px 6px', marginRight: 6 }}>{(Array.isArray(n.tags) ? n.tags[0] : n.tag) || 'news'}</span>
                  <span style={{ fontSize: 13 }}>{n.title}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Shelves, straight into games */}
      <Shelf collection="vorenka" title={t('coll.vorenka')} sub={t('coll.vorenka_sub')} setPage={setPage} />
      <Shelf collection="velvet" title={t('coll.velvet')} sub={t('coll.velvet_sub')} setPage={setPage} />
    </div>
  );
}

function Shelf({ collection, title, sub, setPage, games: gamesProp }) {
  const games = (Array.isArray(gamesProp) ? gamesProp : GAMES).filter((g) => g.collection === collection);
  return (
    <section>
      <div className="section">
        <h2 className="section__ttl">{title}<span className="collection">· {sub}</span></h2>
        <a href="#games" className="section__more" onClick={(e) => { e.preventDefault(); setPage('games'); }}>{t('action.see_all')}</a>
      </div>
      <div className="shelf">
        {games.map((g) => <GameCard key={g.slug} g={g} progress={g.progress} />)}
      </div>
    </section>
  );
}

function GameCard({ g, progress }) {
  const goPlay = () => { window.location.href = g.playUrl; };
  const pct = Math.round(Math.max(0, Math.min(1, Number(progress) || 0)) * 100);
  return (
    <article className="gcard" onClick={goPlay} role="link" tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goPlay(); } }}
      style={{ cursor: 'pointer' }}>
      <div className="gcard__art">
        <img
          src={g.img}
          alt={g.title}
          onError={(e) => {
            e.target.parentElement.classList.add('placeholder');
            e.target.style.display = 'none';
            if (!e.target.parentElement.querySelector('span.__ph')) {
              const s = document.createElement('span');
              s.className = '__ph';
              s.textContent = g.title.toUpperCase();
              e.target.parentElement.appendChild(s);
            }
          }}
        />
        <div className="gcard__ribbons">
          <span className="tag">{COLLECTIONS[g.collection].label}</span>
        </div>
        <button className="gcard__play" aria-label={`Play ${g.title}`} onClick={(e) => { e.stopPropagation(); goPlay(); }}>
          <Icon name="play" size={18}/>
        </button>
      </div>
      <div className="gcard__body">
        <h3 className="gcard__ttl">{g.title}</h3>
        <p className="gcard__blurb">{t('action.play_now')}</p>
      </div>
      <div className="gcard__foot">
        <span className="gcard__collection">{COLLECTIONS[g.collection].label}</span>
        <span className="gcard__progress tabular">{pct}%</span>
        <button
          className="btn btn--ghost btn--sm"
          onClick={(e) => { e.stopPropagation(); window.location.href = g.aboutUrl; }}
        >
          {t('action.about_game')}
        </button>
      </div>
    </article>
  );
}

Object.assign(window, { HomePage, GameCard, Shelf });
