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

export async function mountView(el, params = {}) {
  const myId = store.get('auth.userId');
  const targetId = params.playerId || null;
  const isOther = targetId && targetId !== myId;

  if (isOther) {
    await mountOtherProfile(el, targetId);
  } else {
    await mountOwnProfile(el);
  }
}

// ========== OWN PROFILE ==========
async function mountOwnProfile(el) {
  try {
    const fresh = await net.get('profile.php');
    if (fresh && !fresh.error) store.set('player', fresh);
  } catch (e) {}
  const player = store.get('player') || {};

  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <!-- Player Card -->
      <div class="card" style="text-align:center;padding:var(--s-6);">
        <div class="profile-avatar-wrap" id="avatar-wrap">
          <div class="profile-avatar">
            ${player.avatar_url ? `<img src="${player.avatar_url}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">` : emoji('person', '👤', 40)}
          </div>
          <div class="profile-avatar-edit">${emoji('camera', '📷', 14)}</div>
        </div>
        <input type="file" id="avatar-input" accept="image/*" style="display:none;">
        <div id="avatar-uploading" style="display:none;margin:var(--s-2) auto 0;font-size:12px;color:var(--text-secondary);">جاري الرفع...</div>
        <div style="font-size:18px;font-weight:700;margin-top:var(--s-3);">${player.display_name || player.username || 'Player'}</div>
        <div style="font-size:13px;color:var(--text-secondary);margin-top:2px;">Level ${player.level || 1}</div>
      </div>

      <!-- Stats -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${t('profile.stats')}</div>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:var(--s-3);text-align:center;">
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--gold);font-family:var(--font-lat);">${player.games_played || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">مباريات</div>
          </div>
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--win);font-family:var(--font-lat);">${player.games_won || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">فوز</div>
          </div>
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--cyan);font-family:var(--font-lat);">${player.current_streak || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">سلسلة</div>
          </div>
        </div>
      </div>

      <!-- Ratings -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">التصنيف</div>
        <div style="display:flex;flex-direction:column;gap:var(--s-2);">
          ${renderRating('شطرنج (سريع)', player.elo_rapid)}
          ${renderRating('شطرنج (خاطف)', player.elo_blitz)}
          ${renderRating('شطرنج (رصاصة)', player.elo_bullet)}
        </div>
      </div>

      <!-- Organization Membership -->
      <div class="card" id="org-section">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${emoji('building', '🏢', 18)} المنظمة</div>
        <div id="org-membership-content" style="font-size:13px;color:var(--text-secondary);">جاري التحميل...</div>
      </div>

      <!-- Profile Actions -->
      <div style="display:flex;flex-direction:column;gap:var(--s-3);">
        <button class="btn btn-primary w-full" id="btn-edit-profile" style="min-height:44px;">${emoji('edit', '✏️', 16)} تعديل الملف الشخصي</button>
        <button class="btn btn-secondary w-full" id="btn-org-apply" style="min-height:44px;">${emoji('building', '🏢', 16)} الانضمام لمنظمة</button>
      </div>

      <!-- Actions -->
      <div style="display:flex;gap:var(--s-3);">
        <button class="btn btn-secondary w-full" id="btn-settings">${t('profile.settings')}</button>
        <button class="btn btn-secondary w-full" id="btn-logout" style="color:var(--error);">خروج</button>
      </div>
    </div>
  `;

  const avatarInput = el.querySelector('#avatar-input');
  const avatarWrap = el.querySelector('#avatar-wrap');
  let isUploading = false;

  avatarWrap.addEventListener('click', () => {
    if (isUploading) return;
    audio.play('click');
    avatarInput.click();
  });

  avatarInput.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    if (!file || isUploading) return;
    isUploading = true;
    avatarWrap.style.opacity = '0.5';
    const uploading = el.querySelector('#avatar-uploading');
    uploading.style.display = 'block';
    try {
      const compressed = await compressAvatar(file);
      const formData = new FormData();
      formData.append('avatar', compressed, 'avatar.jpg');
      const token = store.get('auth.token');
      const res = await fetch('/api/avatar.php', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: formData
      });
      const data = await res.json();
      if (data.avatar_url) {
        store.set('player', { ...store.get('player'), avatar_url: data.avatar_url });
        bus.emit('store:player');
        mountView(el);
        return;
      } else {
        bus.emit('toast', { text: data.error || 'فشل رفع الصورة', type: 'error' });
      }
    } catch (err) {
      bus.emit('toast', { text: 'فشل رفع الصورة', type: 'error' });
    }
    isUploading = false;
    avatarWrap.style.opacity = '1';
    uploading.style.display = 'none';
  });

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

  el.querySelector('#btn-org-apply').addEventListener('click', () => {
    audio.play('click');
    scene.push('profile-org-apply');
  });

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

  el.querySelector('#btn-logout').addEventListener('click', () => {
    audio.play('click');
    bus.emit('auth:logout');
  });

  loadOrgMembership(el);
}

// ========== OTHER PLAYER'S PROFILE ==========
async function mountOtherProfile(el, playerId) {
  el.innerHTML = `<div style="padding:var(--s-4);text-align:center;color:var(--text-secondary);">${t('common.loading')}</div>`;

  let player;
  try {
    player = await net.get('profile.php', { id: playerId });
    if (!player || player.error) {
      el.innerHTML = `
        <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-3);align-items:center;">
          <button class="btn btn-secondary" id="back-btn" style="align-self:flex-start;width:36px;height:36px;padding:0;">←</button>
          <div style="color:var(--text-secondary);padding:var(--s-6);">${player?.error || 'Profile not available'}</div>
        </div>`;
      el.querySelector('#back-btn').addEventListener('click', () => { audio.play('click'); scene.pop(); });
      return;
    }
  } catch (e) {
    el.innerHTML = `
      <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-3);align-items:center;">
        <button class="btn btn-secondary" id="back-btn" style="align-self:flex-start;width:36px;height:36px;padding:0;">←</button>
        <div style="color:var(--error);padding:var(--s-6);">${t('common.error')}</div>
      </div>`;
    el.querySelector('#back-btn').addEventListener('click', () => { audio.play('click'); scene.pop(); });
    return;
  }

  const friendStatus = player.friendship_status || 'none';
  const blockStatus = player.block_status || 'none';

  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <div style="display:flex;align-items:center;gap:var(--s-3);">
        <button class="btn btn-secondary" id="back-btn" style="width:36px;height:36px;padding:0;">←</button>
        <h2 style="font-size:18px;font-weight:700;flex:1;">الملف الشخصي</h2>
      </div>

      <!-- Player Card -->
      <div class="card" style="text-align:center;padding:var(--s-6);">
        <div style="width:80px;height:80px;border-radius:50%;margin:0 auto;background:var(--bg-surface);display:flex;align-items:center;justify-content:center;overflow:hidden;">
          ${player.avatar_url ? `<img src="${player.avatar_url}" style="width:80px;height:80px;border-radius:50%;object-fit:cover;">` : emoji('person', '👤', 40)}
        </div>
        <div style="font-size:18px;font-weight:700;margin-top:var(--s-3);">${player.display_name || player.username || 'Player'}</div>
        <div style="font-size:13px;color:var(--text-secondary);margin-top:2px;">Level ${player.level || 1}</div>
        ${player.bio ? `<div style="font-size:13px;color:var(--text-secondary);margin-top:var(--s-2);">${escapeHtml(player.bio)}</div>` : ''}
        ${player.country_code ? `<div style="font-size:12px;color:var(--text-secondary);margin-top:2px;">${emoji('flag', '🏳️', 12)} ${player.country_code}</div>` : ''}
      </div>

      <!-- Stats -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${t('profile.stats')}</div>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:var(--s-3);text-align:center;">
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--gold);font-family:var(--font-lat);">${player.games_played || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">مباريات</div>
          </div>
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--win);font-family:var(--font-lat);">${player.games_won || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">فوز</div>
          </div>
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--cyan);font-family:var(--font-lat);">${player.current_streak || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">سلسلة</div>
          </div>
        </div>
      </div>

      <!-- Ratings -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">التصنيف</div>
        <div style="display:flex;flex-direction:column;gap:var(--s-2);">
          ${renderRating('شطرنج (سريع)', player.elo_rapid)}
          ${renderRating('شطرنج (خاطف)', player.elo_blitz)}
          ${renderRating('شطرنج (رصاصة)', player.elo_bullet)}
        </div>
      </div>

      <!-- Spectate -->
      <div id="spectate-section" style="display:none;"></div>

      <!-- Action Buttons -->
      <div id="profile-actions" style="display:flex;flex-direction:column;gap:var(--s-3);">
        ${renderActionButtons(friendStatus, blockStatus)}
      </div>
    </div>
  `;

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

  // Action button handlers
  const addFriendBtn = el.querySelector('#btn-add-friend');
  if (addFriendBtn) {
    addFriendBtn.addEventListener('click', async () => {
      addFriendBtn.disabled = true;
      addFriendBtn.style.opacity = '0.5';
      try {
        await net.post('friends.php', { action: 'request', target_id: playerId });
        addFriendBtn.textContent = '✓ تم إرسال الطلب';
        addFriendBtn.style.color = 'var(--success)';
      } catch (e) {
        addFriendBtn.textContent = e.message || t('common.error');
        addFriendBtn.disabled = false;
        addFriendBtn.style.opacity = '1';
      }
    });
  }

  const challengeBtn = el.querySelector('#btn-challenge');
  if (challengeBtn) {
    challengeBtn.addEventListener('click', () => {
      audio.play('click');
      scene.push('challenge', { friendId: playerId, friendName: player.display_name });
    });
  }

  const messageBtn = el.querySelector('#btn-message');
  if (messageBtn) {
    messageBtn.addEventListener('click', () => {
      audio.play('click');
      scene.push('chat', { friendId: playerId, friendName: player.display_name });
    });
  }

  const blockBtn = el.querySelector('#btn-block');
  if (blockBtn) {
    blockBtn.addEventListener('click', async () => {
      const confirmed = await modal.confirm(t('block.confirm_block'), {
        title: 'حظر',
        icon: '🚫',
        confirmText: 'حظر',
        cancelText: 'إلغاء',
        danger: true
      });
      if (!confirmed) return;
      blockBtn.disabled = true;
      blockBtn.style.opacity = '0.5';
      try {
        await net.post('friends.php', { action: 'block', target_id: playerId });
        blockBtn.textContent = '✓ ' + t('block.blocked');
        blockBtn.style.color = 'var(--text-secondary)';
        const actionsDiv = el.querySelector('#profile-actions');
        if (addFriendBtn) addFriendBtn.remove();
        if (challengeBtn) challengeBtn.remove();
        if (messageBtn) messageBtn.remove();
      } catch (e) {
        blockBtn.disabled = false;
        blockBtn.style.opacity = '1';
      }
    });
  }

  const unblockBtn = el.querySelector('#btn-unblock');
  if (unblockBtn) {
    unblockBtn.addEventListener('click', async () => {
      unblockBtn.disabled = true;
      unblockBtn.style.opacity = '0.5';
      try {
        await net.post('friends.php', { action: 'unblock', target_id: playerId });
        mountOtherProfile(el, playerId);
      } catch (e) {
        unblockBtn.disabled = false;
        unblockBtn.style.opacity = '1';
      }
    });
  }

  // Check if player has an active match (for spectate)
  if (blockStatus !== 'block') {
    checkActiveMatch(el, playerId);
  }
}

async function checkActiveMatch(el, playerId) {
  const section = el.querySelector('#spectate-section');
  if (!section) return;
  try {
    const data = await net.post('game.php', { action: 'find-active-match', player_id: playerId });
    if (data.match_id) {
      section.style.display = 'block';
      const gameLabel = data.game_key === 'ludo' ? 'لودو' : data.game_key === 'domino' ? 'دومينو' : 'شطرنج';
      section.innerHTML = `
        <div class="card" style="background:linear-gradient(135deg,#1a2a1a,#0f1f0f);border:1px solid rgba(52,211,153,0.3);padding:var(--s-3);display:flex;align-items:center;gap:var(--s-3);">
          <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#EF4444;animation:specPulse 1.5s infinite;"></span>
          <div style="flex:1;">
            <div style="font-size:13px;font-weight:600;color:#34D399;">يلعب الآن — ${gameLabel}</div>
          </div>
          <button class="btn btn-primary" id="btn-spectate" style="min-height:32px;padding:4px 14px;font-size:12px;">${emoji('eye', '👁', 13)} شاهد</button>
        </div>
        <style>@keyframes specPulse{0%,100%{opacity:1}50%{opacity:0.3}}</style>
      `;
      section.querySelector('#btn-spectate').addEventListener('click', () => {
        audio.play('click');
        if (data.game_key === 'chess') {
          scene.push('chess-spectate', { matchId: data.match_id });
        } else if (data.game_key === 'ludo') {
          scene.push('ludo-game', { matchId: data.match_id, mode: 'spectate' });
        } else if (data.game_key === 'domino') {
          scene.push('domino-game', { matchId: data.match_id, mode: 'spectate' });
        } else if (data.game_key === 'backgammon') {
          scene.push('backgammon-game', { matchId: data.match_id, mode: 'spectate' });
        }
      });
    }
  } catch (e) {}
}

function renderActionButtons(friendStatus, blockStatus) {
  if (blockStatus === 'block') {
    return `<button class="btn btn-secondary w-full" id="btn-unblock" style="min-height:44px;">${t('block.unblock')}</button>`;
  }

  let buttons = '';

  if (friendStatus === 'accepted') {
    buttons += `<button class="btn btn-primary w-full" id="btn-challenge" style="min-height:44px;">${emoji('swords', '⚔️', 16)} تحدي</button>`;
    buttons += `<button class="btn btn-secondary w-full" id="btn-message" style="min-height:44px;">${emoji('chat', '💬', 16)} مراسلة</button>`;
  } else if (friendStatus === 'pending') {
    buttons += `<button class="btn btn-secondary w-full" disabled style="min-height:44px;opacity:0.6;">طلب صداقة معلق</button>`;
  } else {
    buttons += `<button class="btn btn-primary w-full" id="btn-add-friend" style="min-height:44px;">➕ إضافة صديق</button>`;
  }

  buttons += `<button class="btn btn-secondary w-full" id="btn-block" style="min-height:44px;color:var(--error);">${emoji('block', '🚫', 16)} ${t('block.block')}</button>`;

  return buttons;
}

// ========== SHARED HELPERS ==========
async function loadOrgMembership(el) {
  const content = el.querySelector('#org-membership-content');
  if (!content) return;
  try {
    const [memberships, applications] = await Promise.all([
      net.post('profile.php', { action: 'my-memberships' }),
      net.post('profile.php', { action: 'my-applications' })
    ]);

    let html = '';

    // Show active memberships
    const active = (Array.isArray(memberships) ? memberships : []).filter(m => m.status === 'active');
    if (active.length > 0) {
      html += active.map(m => {
        const org = m.organizations;
        const logoHtml = org && org.logo_url
          ? `<img src="${org.logo_url}" style="width:28px;height:28px;border-radius:6px;object-fit:contain;" alt="">`
          : `<div style="width:28px;height:28px;border-radius:6px;background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;">${emoji('building', '🏢', 14)}</div>`;
        return `
          <div style="display:flex;align-items:center;gap:var(--s-2);padding:var(--s-2) 0;">
            ${logoHtml}
            <div style="flex:1;">
              <div style="font-size:13px;font-weight:600;color:var(--text-primary);">${org ? org.name : 'منظمة'}</div>
              <div style="font-size:11px;color:var(--text-secondary);">${m.role || 'عضو'}</div>
            </div>
            <span style="background:var(--success);color:#fff;font-size:10px;padding:2px 6px;border-radius:10px;">عضو</span>
          </div>
        `;
      }).join('');
    }

    // Show pending/rejected applications
    const pending = (Array.isArray(applications) ? applications : []).filter(a => a.status === 'pending' || a.status === 'rejected');
    if (pending.length > 0) {
      html += pending.map(a => {
        const org = a.organizations || a.el3ab_organizations;
        const orgName = org ? org.name : 'منظمة';
        const logoHtml = org && org.logo_url
          ? `<img src="${org.logo_url}" style="width:28px;height:28px;border-radius:6px;object-fit:contain;" alt="">`
          : `<div style="width:28px;height:28px;border-radius:6px;background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;">${emoji('building', '🏢', 14)}</div>`;
        const statusBadge = a.status === 'pending'
          ? `<span style="background:#f59e0b;color:#000;font-size:10px;padding:2px 6px;border-radius:10px;">قيد المراجعة</span>`
          : `<span style="background:var(--error);color:#fff;font-size:10px;padding:2px 6px;border-radius:10px;">مرفوض</span>`;
        return `
          <div style="display:flex;align-items:center;gap:var(--s-2);padding:var(--s-2) 0;">
            ${logoHtml}
            <div style="flex:1;">
              <div style="font-size:13px;font-weight:600;color:var(--text-primary);">${orgName}</div>
              <div style="font-size:11px;color:var(--text-secondary);">طلب انضمام</div>
            </div>
            ${statusBadge}
          </div>
        `;
      }).join('');
    }

    content.innerHTML = html || `<div style="font-size:13px;color:var(--text-secondary);">لست عضواً في أي منظمة بعد</div>`;
  } catch (e) {
    content.innerHTML = `<div style="font-size:13px;color:var(--text-secondary);">لست عضواً في أي منظمة بعد</div>`;
  }
}

function compressAvatar(file) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      const size = 512;
      const canvas = document.createElement('canvas');
      canvas.width = size;
      canvas.height = size;
      const ctx = canvas.getContext('2d');

      const min = Math.min(img.width, img.height);
      const sx = (img.width - min) / 2;
      const sy = (img.height - min) / 2;
      ctx.drawImage(img, sx, sy, min, min, 0, 0, size, size);

      canvas.toBlob(
        (blob) => blob ? resolve(blob) : reject(new Error('Compression failed')),
        'image/jpeg',
        0.82
      );
      URL.revokeObjectURL(img.src);
    };
    img.onerror = () => { URL.revokeObjectURL(img.src); reject(new Error('Invalid image')); };
    img.src = URL.createObjectURL(file);
  });
}

function renderRating(label, rating) {
  const display = rating ? rating : '—';
  return `
    <div style="display:flex;justify-content:space-between;align-items:center;">
      <span style="font-size:13px;color:var(--text-secondary);">${label}</span>
      <span style="font-size:15px;font-weight:700;font-family:var(--font-lat);${!rating ? 'color:var(--text-muted);' : ''}">${display}</span>
    </div>
  `;
}

function escapeHtml(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}
