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:#0a0a1a;color:#64748b;">جاري التحميل...</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:#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 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,#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'};">يوم ${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:#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;">${todayReward} ${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;
          setTimeout(() => { claimBtn.textContent = 'استلم المكافأة'; 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 = 'فشل — حاول مرة أخرى';
        claimBtn.disabled = false;
      }
    });
  }
}
