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) {
  const player = store.get('player') || {};
  const lastClaim = player.last_daily_reward || null;
  const today = new Date().toISOString().slice(0, 10);
  const alreadyClaimed = lastClaim && lastClaim.slice(0, 10) === today;
  const streak = player.daily_streak || 0;

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:#0a0a1a;">
      <!-- Header -->
      <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.06);">
        <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:#f8fafc;">${emoji('gift', '🎁', 16)} المكافأة اليومية</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,#E4AC38);padding:8px 20px;border-radius:99px;display:flex;align-items:center;gap:6px;">
          <span style="font-size:18px;">🔥</span>
          <span style="font-size:14px;font-weight:800;color:#1a1a1a;">${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 dayNum = i + 1;
            const isPast = i < streak;
            const isToday = i === streak;
            const isFuture = i > streak;
            const claimed = isPast || (isToday && 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,#E4AC38,#FFCC66)' : '#1a1a2e'};
                  border:2px solid ${claimed ? '#34D399' : isToday ? '#E4AC38' : 'rgba(255,255,255,0.06)'};
                  color:${claimed ? '#34D399' : isToday ? '#1a1a1a' : '#64748b'};">
                  ${claimed ? '✓' : coins}
                </div>
                <span style="font-size:9px;color:${isToday ? '#E4AC38' : '#475569'};font-weight:${isToday ? '700' : '400'};">يوم ${dayNum}</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:#34D399;">تم استلام مكافأة اليوم</div>
            <div style="font-size:13px;color:#64748b;margin-top:4px;">عد غداً لمكافأة أكبر!</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:#f8fafc;margin-bottom:4px;">مكافأة اليوم</div>
            <div style="font-size:28px;font-weight:800;color:#E4AC38;margin-bottom:16px;">${DAY_REWARDS[Math.min(streak, 6)]} ${emoji('coin', '🪙', 24)}</div>
            <button class="btn btn-primary" id="claim-btn" style="font-size:16px;padding:14px 48px;">استلم المكافأة</button>
          `}
        </div>

        <!-- Info -->
        <div style="text-align:center;color:#475569;font-size:11px;margin-top:auto;padding:12px;">
          كل يوم تجمع فيه المكافأة يزيد المبلغ • اليوم السابع = 300 عملة!
        </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 = 'جاري الاستلام...';

      try {
        const data = await net.post('daily-reward.php', { action: 'claim' });
        if (data.error) {
          claimBtn.textContent = data.error;
          claimBtn.disabled = false;
          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 UI to claimed state
        claimBtn.textContent = '✅ تم!';
        claimBtn.style.background = '#34D399';

        bus.emit('coins:earned', { amount: data.coins || 100 });
        const player = store.get('player');
        if (player) {
          store.set('player', { ...player, coins: data.total_coins || (player.coins || 0) + (data.coins || 100), last_daily_reward: new Date().toISOString() });
        }
      } catch (e) {
        claimBtn.textContent = 'فشل — حاول مرة أخرى';
        claimBtn.disabled = false;
      }
    });
  }
}
