import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import * as bus from '../../../core/bus.js';
import * as store from '../../../core/store.js';
import * as scene from '../../../core/scene.js';
import * as juice from '../../../core/juice.js';
import { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

const DAY_REWARDS = [50, 75, 100, 125, 150, 200, 300];

export async function mountDaily(el) {
  el.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;height:100%;background:var(--bg-deep);color:var(--text-muted);">${t('common.loading')}</div>`;

  let streak = 0;
  let alreadyClaimed = false;
  let dayIndex = 0;
  let todayReward = 50;

  try {
    const data = await net.get('daily-reward.php');
    if (data && !data.error) {
      streak = data.streak || 0;
      alreadyClaimed = data.already_claimed || false;
      dayIndex = data.day_index || 0;
      todayReward = data.today_reward || DAY_REWARDS[0];
    }
  } catch (e) {
    // Fallback to local store
    const player = store.get('player') || {};
    const lastClaim = player.last_daily_reward || null;
    const today = new Date().toISOString().slice(0, 10);
    alreadyClaimed = lastClaim && lastClaim.slice(0, 10) === today;
    streak = player.daily_streak || 0;
    dayIndex = streak % 7;
    todayReward = DAY_REWARDS[dayIndex];
  }

  render(el, streak, alreadyClaimed, dayIndex, todayReward);
}

function render(el, streak, alreadyClaimed, dayIndex, todayReward) {
  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-deep);">
      <!-- Header -->
      <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:var(--bg-panel);border-bottom:1px solid var(--border);">
        <button class="btn btn-secondary" id="back-btn" style="min-height:32px;padding:4px 12px;font-size:12px;">←</button>
        <span style="font-size:16px;font-weight:700;color:var(--text-primary);">${emoji('gift', '🎁', 16)} ${t('daily.title')}</span>
      </div>

      <div style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;align-items:center;gap:16px;">
        <!-- Streak badge -->
        <div style="background:linear-gradient(135deg,#92400e,var(--gold));padding:8px 20px;border-radius:99px;display:flex;align-items:center;gap:6px;">
          ${emoji('fire', '🔥', 18)}
          <span style="font-size:14px;font-weight:800;color:var(--bg-dark);">${t('daily.streak_days', { n: streak })}</span>
        </div>

        <!-- 7-day timeline -->
        <div style="display:flex;gap:6px;width:100%;max-width:340px;justify-content:center;">
          ${DAY_REWARDS.map((coins, i) => {
            const isPast = i < dayIndex || (i === dayIndex && alreadyClaimed);
            const isToday = i === dayIndex && !alreadyClaimed;
            const claimed = i < dayIndex || (i === dayIndex && alreadyClaimed);
            return `
              <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px;">
                <div style="width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;
                  background:${claimed ? '#1a3a1a' : isToday ? 'linear-gradient(135deg,var(--gold),var(--gold-soft))' : 'var(--bg-card)'};
                  border:2px solid ${claimed ? 'var(--success)' : isToday ? 'var(--gold)' : 'var(--border)'};
                  color:${claimed ? 'var(--success)' : isToday ? 'var(--bg-dark)' : 'var(--text-muted)'};">
                  ${claimed ? '✓' : coins}
                </div>
                <span style="font-size:9px;color:${isToday ? 'var(--gold)' : 'var(--text-dim)'};font-weight:${isToday ? '700' : '400'};">${t('daily.day', { n: i + 1 })}</span>
              </div>
            `;
          }).join('')}
        </div>

        <!-- Today's reward -->
        <div style="text-align:center;margin-top:8px;">
          ${alreadyClaimed ? `
            <div style="font-size:48px;margin-bottom:8px;">${emoji('checkmark', '✅', 48)}</div>
            <div style="font-size:16px;font-weight:700;color:var(--success);">${t('daily.claimed_today')}</div>
            <div style="font-size:13px;color:var(--text-muted);margin-top:4px;">${t('daily.come_back')}</div>
          ` : `
            <div style="font-size:56px;margin-bottom:8px;animation:float 3s ease-in-out infinite;">${emoji('gift', '🎁', 56)}</div>
            <div style="font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:4px;">${t('daily.today_reward')}</div>
            <div style="font-size:28px;font-weight:800;color:var(--gold);margin-bottom:16px;">${todayReward} ${emoji('coin', '🪙', 24)}</div>
            <button class="btn btn-primary" id="claim-btn" style="font-size:16px;padding:14px 48px;">${t('daily.claim_btn')}</button>
          `}
        </div>

        <!-- Info -->
        <div style="text-align:center;color:var(--text-dim);font-size:11px;margin-top:auto;padding:12px;">
          ${t('daily.hint')}
        </div>
      </div>
    </div>
  `;

  el.querySelector('#back-btn').addEventListener('click', () => { audio.play('click'); scene.pop(); });

  const claimBtn = el.querySelector('#claim-btn');
  if (claimBtn) {
    claimBtn.addEventListener('click', async () => {
      claimBtn.disabled = true;
      claimBtn.textContent = t('daily.claiming');

      try {
        const data = await net.post('daily-reward.php', { action: 'claim' });
        if (data.error) {
          claimBtn.textContent = data.error;
          setTimeout(() => { claimBtn.textContent = t('daily.claim_btn'); claimBtn.disabled = false; }, 2000);
          return;
        }

        audio.play('coin', 'reward');
        juice.hapticSuccess();
        juice.coinBurst(window.innerWidth / 2, window.innerHeight / 2, 10);
        juice.coinFlyTo(window.innerWidth / 2, window.innerHeight / 2, '#hud-coins', 5);

        // Update local store
        const player = store.get('player') || {};
        store.set('player', {
          ...player,
          coins: data.total_coins,
          daily_streak: data.streak,
          last_daily_reward: new Date().toISOString()
        });

        bus.emit('coins:earned', { amount: data.coins });

        // Re-render with claimed state
        render(el, data.streak, true, data.day_index, data.coins);
      } catch (e) {
        claimBtn.textContent = t('daily.failed');
        claimBtn.disabled = false;
      }
    });
  }
}
