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 { t } from '../../../core/i18n.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:var(--tap-min);padding:0;display:flex;align-items:center;justify-content:center;">
          ${emoji('arrow_back', '←', 18)}
        </button>
        <div style="font-size:18px;font-weight:700;">${t('profile.edit_title')}</div>
      </div>

      <!-- Section: Basic Info -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${emoji('person', '👤', 18)} ${t('profile.basic_info')}</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;">${t('profile.display_name_en')}</label>
            <input id="field-display_name" type="text" maxlength="30" dir="auto" value="${escAttr(player.display_name || '')}"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.display_name_ar')}</label>
            <input id="field-display_name_ar" type="text" maxlength="30" dir="rtl" value="${escAttr(player.display_name_ar || '')}"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.bio_en')}</label>
            <textarea id="field-bio" maxlength="200" dir="auto" rows="3"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.bio_ar')}</label>
            <textarea id="field-bio_ar" maxlength="200" dir="rtl" rows="3"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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)} ${t('profile.location')}</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;">${t('profile.country')}</label>
            <select id="field-country_code"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
              <option value="">${t('profile.select_country')}</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;">${t('profile.city')}</label>
            <input id="field-city" type="text" dir="auto" value="${escAttr(player.city || '')}"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.preferred_language')}</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:var(--tap-min);">العربية</button>
              <button class="btn lang-opt ${player.preferred_language === 'en' ? 'btn-primary' : 'btn-secondary'}" data-lang="en" style="flex:1;min-height:var(--tap-min);">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)} ${t('profile.fide_info')}</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:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.fide_classical')}</label>
            <input id="field-fide_rating_standard" type="number" inputmode="numeric" dir="ltr" min="0" max="4000" value="${player.fide_rating_standard || ''}"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.fide_rapid')}</label>
            <input id="field-fide_rating_rapid" type="number" inputmode="numeric" dir="ltr" min="0" max="4000" value="${player.fide_rating_rapid || ''}"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.fide_blitz')}</label>
            <input id="field-fide_rating_blitz" type="number" inputmode="numeric" dir="ltr" min="0" max="4000" value="${player.fide_rating_blitz || ''}"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);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;">${t('profile.fide_title')}</label>
            <select id="field-fide_title"
              style="background:var(--bg-elevated);border:1px solid rgba(255,255,255,0.1);color:var(--text-primary);border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
              ${FIDE_TITLES.map(ft => `<option value="${ft.value}" ${player.fide_title === ft.value ? 'selected' : ''}>${ft.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)} ${t('profile.save')}
      </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 = t('profile.saving');

    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: t('profile.save_success'), type: 'success' });
      scene.pop();
    } catch (err) {
      bus.emit('toast', { text: err.message || t('profile.save_failed'), type: 'error' });
    }

    btn.disabled = false;
    btn.style.opacity = '1';
    btn.innerHTML = `${emoji('save', '💾', 18)} ${t('profile.save')}`;
  });
}

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;');
}
