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

export async function mountBrowser(el) {
  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <h2 style="font-size:20px;font-weight:700;">${t('org.title')}</h2>
      <div id="org-list">
        <div class="skeleton" style="height:80px;margin-bottom:var(--s-3);"></div>
        <div class="skeleton" style="height:80px;"></div>
      </div>
    </div>
  `;

  try {
    const data = await net.get('orgs.php', { action: 'list' });
    renderOrgs(el, data.organizations || []);
  } catch (e) {
    el.querySelector('#org-list').innerHTML = `<p style="color:var(--text-secondary);text-align:center;">${t('common.empty')}</p>`;
  }
}

function renderOrgs(el, orgs) {
  const list = el.querySelector('#org-list');
  if (orgs.length === 0) {
    list.innerHTML = `<p style="color:var(--text-secondary);text-align:center;padding:var(--s-8);">${t('common.empty')}</p>`;
    return;
  }

  list.innerHTML = orgs.map(org => `
    <div class="card" data-id="${org.id}" style="display:flex;align-items:center;gap:var(--s-3);padding:var(--s-3);margin-bottom:var(--s-3);cursor:pointer;">
      <div style="width:48px;height:48px;border-radius:var(--r-md);background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;font-size:20px;overflow:hidden;">
        ${org.logo_url ? `<img src="${org.logo_url}" style="width:100%;height:100%;object-fit:cover;">` : emoji('building', '🏛️', 20)}
      </div>
      <div style="flex:1;">
        <div style="font-size:14px;font-weight:600;">${org.name_ar || org.name}</div>
        <div style="font-size:11px;color:var(--text-secondary);">${emoji('people', '👥', 11)} ${org.member_count || 0} ${t('profile.member')}</div>
      </div>
      <button class="btn btn-secondary" style="font-size:11px;min-height:32px;padding:var(--s-1) var(--s-3);">${t('org.join_btn')}</button>
    </div>
  `).join('');

  list.querySelectorAll('.card[data-id]').forEach(card => {
    card.addEventListener('click', () => {
      audio.play('click');
      scene.push('org-home', { orgId: card.dataset.id });
    });
  });
}
