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

export function mountSettings(el) {
  const lang = store.get('language') || 'ar';
  const audioOn = store.get('audioEnabled');

  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;">${t('profile.settings')}</h2>
      </div>

      <div class="card" style="display:flex;flex-direction:column;gap:var(--s-4);">
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <span>${t('settings.sound')}</span>
          <button class="btn btn-secondary" id="toggle-audio" style="min-height:var(--tap-min);padding:var(--s-1) var(--s-3);">${audioOn ? emoji('speaker_on', '🔊', 16) + ' ' + t('settings.on') : emoji('speaker_off', '🔇', 16) + ' ' + t('settings.off')}</button>
        </div>
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <span>${t('settings.language')}</span>
          <button class="btn btn-secondary" id="toggle-lang" style="min-height:var(--tap-min);padding:var(--s-1) var(--s-3);">${lang === 'ar' ? 'العربية' : 'English'}</button>
        </div>
      </div>

      <div class="card" style="display:flex;flex-direction:column;gap:var(--s-3);">
        <button class="settings-link" id="blocked-list-btn" style="background:none;border:none;color:var(--text-secondary);font-size:14px;text-align:inherit;cursor:pointer;display:flex;align-items:center;gap:var(--s-2);padding:0;font-family:inherit;">
          ${emoji('block', '🚫', 14)} ${t('settings.blocked_list')}
        </button>
      </div>

      <div class="card" style="display:flex;flex-direction:column;gap:var(--s-3);">
        <a href="/privacy-policy" target="_blank" style="color:var(--text-secondary);font-size:14px;text-decoration:none;display:flex;align-items:center;gap:var(--s-2);">
          ${emoji('lock', '🔒', 14)} ${t('settings.privacy_policy')}
        </a>
        <a href="/terms" target="_blank" style="color:var(--text-secondary);font-size:14px;text-decoration:none;display:flex;align-items:center;gap:var(--s-2);">
          ${emoji('document', '📄', 14)} ${t('settings.terms')}
        </a>
      </div>

      <div class="card" style="border:1px solid var(--error);">
        <button class="btn w-full" id="delete-account-btn" style="background:transparent;color:var(--error);font-weight:700;min-height:44px;">
          ${t('settings.delete_account')}
        </button>
      </div>

      <div id="delete-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.8);z-index:9999;display:none;align-items:center;justify-content:center;padding:var(--s-4);">
        <div style="background:var(--bg-card);border-radius:var(--r-xl);padding:var(--s-6);max-width:340px;width:100%;display:flex;flex-direction:column;gap:var(--s-4);">
          <h3 style="color:var(--error);font-size:16px;text-align:center;">${t('settings.delete_account')}</h3>
          <p style="color:var(--text-secondary);font-size:14px;text-align:center;">${t('settings.delete_confirm')}</p>
          <input class="input" type="password" id="delete-password" placeholder="${t('settings.delete_password')}" style="display:none;">
          <div id="delete-error" style="color:var(--error);font-size:13px;min-height:18px;text-align:center;"></div>
          <div style="display:flex;gap:var(--s-3);">
            <button class="btn btn-secondary w-full" id="delete-cancel">${t('common.cancel')}</button>
            <button class="btn w-full" id="delete-confirm" style="background:var(--error);color:#fff;">${t('common.confirm')}</button>
          </div>
        </div>
      </div>
    </div>
  `;

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

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

  el.querySelector('#toggle-audio').addEventListener('click', () => {
    const current = store.get('audioEnabled');
    store.set('audioEnabled', !current);
    audio.play('click');
    mountSettings(el);
  });

  el.querySelector('#toggle-lang').addEventListener('click', () => {
    const current = store.get('language') || 'ar';
    const next = current === 'ar' ? 'en' : 'ar';
    setLang(next);
    audio.play('click');
    mountSettings(el);
  });

  const modal = el.querySelector('#delete-modal');
  const passInput = el.querySelector('#delete-password');
  const errEl = el.querySelector('#delete-error');

  el.querySelector('#delete-account-btn').addEventListener('click', async () => {
    audio.play('click');
    modal.style.display = 'flex';

    try {
      const me = await net.post('auth.php', { action: 'me' });
      if (me.provider === 'email') {
        passInput.style.display = 'block';
      }
    } catch (e) {
      passInput.style.display = 'block';
    }
  });

  el.querySelector('#delete-cancel').addEventListener('click', () => {
    modal.style.display = 'none';
    errEl.textContent = '';
    passInput.value = '';
  });

  el.querySelector('#delete-confirm').addEventListener('click', async () => {
    const btn = el.querySelector('#delete-confirm');
    btn.disabled = true;
    errEl.textContent = '';

    try {
      const payload = { action: 'delete-account' };
      if (passInput.style.display !== 'none' && passInput.value) {
        payload.password = passInput.value;
      } else {
        payload.confirm = true;
      }

      const res = await net.post('auth.php', payload);
      if (res.error) throw new Error(res.error);

      store.reset();
      bus.emit('auth:logout');
    } catch (e) {
      errEl.textContent = e.message || t('common.error');
      btn.disabled = false;
    }
  });
}
