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 { emoji } from '../../../core/theme.js';

const COUNTRIES = [
  { code: 'EG', name: 'مصر' },
  { code: 'SA', name: 'السعودية' },
  { code: 'AE', name: 'الإمارات' },
  { code: 'KW', name: 'الكويت' },
  { code: 'QA', name: 'قطر' },
  { code: 'BH', name: 'البحرين' },
  { code: 'OM', name: 'عُمان' },
  { code: 'JO', name: 'الأردن' },
  { code: 'IQ', name: 'العراق' },
  { code: 'SY', name: 'سوريا' },
  { code: 'LB', name: 'لبنان' },
  { code: 'PS', name: 'فلسطين' },
  { code: 'LY', name: 'ليبيا' },
  { code: 'TN', name: 'تونس' },
  { code: 'DZ', name: 'الجزائر' },
  { code: 'MA', name: 'المغرب' },
  { code: 'SD', name: 'السودان' },
  { code: 'YE', name: 'اليمن' },
  { code: 'MR', name: 'موريتانيا' },
  { code: 'OTHER', name: 'أخرى' }
];

const FIDE_TITLES = [
  { value: '', label: 'بدون' },
  { value: 'GM', label: 'GM — أستاذ كبير' },
  { value: 'IM', label: 'IM — أستاذ دولي' },
  { value: 'FM', label: 'FM — أستاذ فيدرالي' },
  { value: 'CM', label: 'CM — مرشح أستاذ' },
  { value: 'WGM', label: 'WGM — أستاذة كبيرة' },
  { value: 'WIM', label: 'WIM — أستاذة دولية' },
  { value: 'WFM', label: 'WFM — أستاذة فيدرالية' },
  { value: 'WCM', label: 'WCM — مرشحة أستاذة' }
];

export async function mountEdit(el) {
  const player = store.get('player') || {};

  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);padding-bottom:max(var(--s-4), env(safe-area-inset-bottom));">
      <!-- Header -->
      <div style="display:flex;align-items:center;gap:var(--s-3);">
        <button id="btn-back" class="btn btn-secondary" style="min-width:40px;min-height:40px;padding:0;display:flex;align-items:center;justify-content:center;">
          ${emoji('arrow_back', '←', 18)}
        </button>
        <div style="font-size:18px;font-weight:700;">تعديل الملف الشخصي</div>
      </div>

      <!-- Section: Basic Info -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${emoji('person', '👤', 18)} المعلومات الأساسية</div>

        <div style="display:flex;flex-direction:column;gap:var(--s-3);">
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">الاسم المعروض (إنجليزي)</label>
            <input id="field-display_name" type="text" maxlength="30" dir="auto" value="${escAttr(player.display_name || '')}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">الاسم المعروض (عربي)</label>
            <input id="field-display_name_ar" type="text" maxlength="30" dir="rtl" value="${escAttr(player.display_name_ar || '')}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">النبذة (إنجليزي)</label>
            <textarea id="field-bio" maxlength="200" dir="auto" rows="3"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;resize:vertical;">${escHtml(player.bio || '')}</textarea>
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">النبذة (عربي)</label>
            <textarea id="field-bio_ar" maxlength="200" dir="rtl" rows="3"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;resize:vertical;">${escHtml(player.bio_ar || '')}</textarea>
          </div>
        </div>
      </div>

      <!-- Section: Location -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${emoji('globe', '🌍', 18)} الموقع</div>

        <div style="display:flex;flex-direction:column;gap:var(--s-3);">
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">الدولة</label>
            <select id="field-country_code"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
              <option value="">اختر الدولة</option>
              ${COUNTRIES.map(c => `<option value="${c.code}" ${player.country_code === c.code ? 'selected' : ''}>${c.name}</option>`).join('')}
            </select>
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">المدينة</label>
            <input id="field-city" type="text" dir="auto" value="${escAttr(player.city || '')}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">اللغة المفضلة</label>
            <div id="lang-toggle" style="display:flex;gap:var(--s-2);">
              <button class="btn lang-opt ${(player.preferred_language || 'ar') === 'ar' ? 'btn-primary' : 'btn-secondary'}" data-lang="ar" style="flex:1;min-height:40px;">العربية</button>
              <button class="btn lang-opt ${player.preferred_language === 'en' ? 'btn-primary' : 'btn-secondary'}" data-lang="en" style="flex:1;min-height:40px;">English</button>
            </div>
          </div>
        </div>
      </div>

      <!-- Section: FIDE Info -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${emoji('trophy', '🏆', 18)} معلومات FIDE</div>

        <div style="display:flex;flex-direction:column;gap:var(--s-3);">
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">FIDE ID</label>
            <input id="field-fide_id" type="text" inputmode="numeric" dir="ltr" value="${escAttr(player.fide_id || '')}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">تصنيف FIDE الكلاسيكي</label>
            <input id="field-fide_rating_standard" type="number" inputmode="numeric" dir="ltr" min="0" max="4000" value="${player.fide_rating_standard || ''}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">تصنيف FIDE السريع</label>
            <input id="field-fide_rating_rapid" type="number" inputmode="numeric" dir="ltr" min="0" max="4000" value="${player.fide_rating_rapid || ''}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">تصنيف FIDE الخاطف</label>
            <input id="field-fide_rating_blitz" type="number" inputmode="numeric" dir="ltr" min="0" max="4000" value="${player.fide_rating_blitz || ''}"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
          </div>
          <div>
            <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">لقب FIDE</label>
            <select id="field-fide_title"
              style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
              ${FIDE_TITLES.map(t => `<option value="${t.value}" ${player.fide_title === t.value ? 'selected' : ''}>${t.label}</option>`).join('')}
            </select>
          </div>
        </div>
      </div>

      <!-- Save Button -->
      <button id="btn-save" class="btn btn-primary" style="width:100%;min-height:48px;font-size:16px;font-weight:700;">
        ${emoji('save', '💾', 18)} حفظ التغييرات
      </button>
    </div>
  `;

  // Language toggle
  let selectedLang = player.preferred_language || 'ar';
  el.querySelectorAll('.lang-opt').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      selectedLang = btn.dataset.lang;
      el.querySelectorAll('.lang-opt').forEach(b => {
        b.classList.remove('btn-primary');
        b.classList.add('btn-secondary');
      });
      btn.classList.remove('btn-secondary');
      btn.classList.add('btn-primary');
    });
  });

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

  // Save
  el.querySelector('#btn-save').addEventListener('click', async () => {
    audio.play('click');
    const btn = el.querySelector('#btn-save');
    btn.disabled = true;
    btn.style.opacity = '0.6';
    btn.textContent = 'جاري الحفظ...';

    const data = {
      display_name: el.querySelector('#field-display_name').value.trim(),
      display_name_ar: el.querySelector('#field-display_name_ar').value.trim(),
      bio: el.querySelector('#field-bio').value.trim(),
      bio_ar: el.querySelector('#field-bio_ar').value.trim(),
      country_code: el.querySelector('#field-country_code').value,
      city: el.querySelector('#field-city').value.trim(),
      preferred_language: selectedLang,
      fide_id: el.querySelector('#field-fide_id').value.trim(),
      fide_rating_standard: el.querySelector('#field-fide_rating_standard').value ? parseInt(el.querySelector('#field-fide_rating_standard').value) : null,
      fide_rating_rapid: el.querySelector('#field-fide_rating_rapid').value ? parseInt(el.querySelector('#field-fide_rating_rapid').value) : null,
      fide_rating_blitz: el.querySelector('#field-fide_rating_blitz').value ? parseInt(el.querySelector('#field-fide_rating_blitz').value) : null,
      fide_title: el.querySelector('#field-fide_title').value || null
    };

    // Remove empty strings to avoid overwriting with blanks
    Object.keys(data).forEach(k => {
      if (data[k] === '') data[k] = null;
    });

    try {
      const result = await net.patch('profile.php', data);
      // Update local store
      const updated = { ...store.get('player'), ...data };
      store.set('player', updated);
      bus.emit('store:player');
      bus.emit('toast', { text: 'تم حفظ التغييرات بنجاح', type: 'success' });
      scene.pop();
    } catch (err) {
      bus.emit('toast', { text: err.message || 'فشل حفظ التغييرات', type: 'error' });
    }

    btn.disabled = false;
    btn.style.opacity = '1';
    btn.innerHTML = `${emoji('save', '💾', 18)} حفظ التغييرات`;
  });
}

function escAttr(str) {
  return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function escHtml(str) {
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
