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 DOC_TYPES = [
  { value: 'membership_card', get label() { return t('org.doc_membership'); } },
  { value: 'id_card', get label() { return t('org.doc_id'); } },
  { value: 'receipt', get label() { return t('org.doc_receipt'); } },
  { value: 'other', get label() { return t('org.doc_other'); } }
];

export async function mountOrgApply(el) {
  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));">
      <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('org.join_title')}</div>
      </div>
      <div id="org-content" style="display:flex;flex-direction:column;gap:var(--s-3);">
        <div style="text-align:center;padding:var(--s-6);color:var(--text-secondary);">${t('common.loading')}</div>
      </div>
    </div>
  `;

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

  await loadOrgs(el);
}

async function loadOrgs(el) {
  const content = el.querySelector('#org-content');

  try {
    const [orgs, memberships, applications] = await Promise.all([
      net.post('profile.php', { action: 'get-orgs' }),
      net.post('profile.php', { action: 'my-memberships' }),
      net.post('profile.php', { action: 'my-applications' })
    ]);

    if (!orgs || !Array.isArray(orgs) || orgs.length === 0) {
      content.innerHTML = `<div class="card" style="text-align:center;padding:var(--s-6);color:var(--text-secondary);">${t('org.no_orgs')}</div>`;
      return;
    }

    const memberOrgIds = new Set(
      (Array.isArray(memberships) ? memberships : [])
        .filter(m => m.status === 'active')
        .map(m => m.organization_id)
    );

    const appMap = {};
    (Array.isArray(applications) ? applications : []).forEach(app => {
      if (!appMap[app.org_id] || new Date(app.created_at) > new Date(appMap[app.org_id].created_at)) {
        appMap[app.org_id] = app;
      }
    });

    content.innerHTML = orgs.map(org => {
      const isMember = memberOrgIds.has(org.id);
      const app = appMap[org.id];
      let badge = '';
      let actionBtn = '';

      if (isMember) {
        badge = `<span style="background:var(--success);color:#fff;font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;">${emoji('check', '✓', 12)} ${t('profile.member')}</span>`;
      } else if (app && app.status === 'pending') {
        badge = `<span style="background:var(--warning);color:#000;font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;">${t('profile.pending_review')}</span>`;
      } else if (app && app.status === 'rejected') {
        badge = `<span style="background:var(--error);color:#fff;font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;">${t('profile.rejected')}</span>`;
        if (app.rejection_reason) {
          badge += `<div style="font-size:11px;color:var(--error);margin-top:4px;">${t('profile.rejection_reason', { reason: escHtml(app.rejection_reason) })}</div>`;
        }
        actionBtn = `<button class="btn btn-primary btn-apply" data-org-id="${org.id}" style="min-height:var(--tap-min);font-size:13px;margin-top:var(--s-2);">${t('org.reapply')}</button>`;
      } else {
        actionBtn = `<button class="btn btn-primary btn-apply" data-org-id="${org.id}" style="min-height:var(--tap-min);font-size:13px;margin-top:var(--s-2);">${t('org.apply')}</button>`;
      }

      const logoHtml = org.logo_url
        ? `<img src="${org.logo_url}" style="width:40px;height:40px;border-radius:8px;object-fit:contain;" alt="">`
        : `<div style="width:40px;height:40px;border-radius:8px;background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;">${emoji('building', '🏢', 20)}</div>`;

      return `
        <div class="card" style="padding:var(--s-3);">
          <div style="display:flex;align-items:center;gap:var(--s-3);">
            ${logoHtml}
            <div style="flex:1;min-width:0;">
              <div style="font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${escHtml(org.name)}</div>
              ${org.country_code ? `<div style="font-size:12px;color:var(--text-secondary);">${org.country_code}</div>` : ''}
            </div>
            <div style="text-align:center;">${badge}</div>
          </div>
          ${actionBtn}
        </div>
      `;
    }).join('');

    // Apply button handlers
    content.querySelectorAll('.btn-apply').forEach(btn => {
      btn.addEventListener('click', () => {
        audio.play('click');
        const orgId = btn.dataset.orgId;
        const org = orgs.find(o => o.id === orgId);
        showApplyForm(el, org, content);
      });
    });

  } catch (err) {
    content.innerHTML = `<div class="card" style="text-align:center;padding:var(--s-4);color:var(--error);">${t('common.error_load')}</div>`;
  }
}

function showApplyForm(el, org, contentParent) {
  const content = el.querySelector('#org-content');

  content.innerHTML = `
    <div class="card" style="padding:var(--s-4);">
      <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${t('org.apply_title', { name: escHtml(org.name) })}</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('org.doc_type')}</label>
          <select id="apply-doc-type"
            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;">
            ${DOC_TYPES.map(d => `<option value="${d.value}">${d.label}</option>`).join('')}
          </select>
        </div>

        <div>
          <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">${t('org.notes')}</label>
          <textarea id="apply-notes" maxlength="500" 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;"
            placeholder="${t('org.notes_placeholder')}"></textarea>
        </div>

        <div>
          <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">${t('org.proof_image')}</label>
          <div id="upload-area" style="background:var(--bg-elevated);border:2px dashed var(--border-hover);border-radius:8px;padding:var(--s-4);text-align:center;cursor:pointer;">
            <div id="upload-placeholder">
              <div>${emoji('camera', '📷', 28)}</div>
              <div style="font-size:13px;color:var(--text-secondary);margin-top:var(--s-2);">${t('org.tap_to_select')}</div>
              <div style="font-size:11px;color:var(--text-secondary);">${t('org.file_limit')}</div>
            </div>
            <div id="upload-preview" style="display:none;">
              <img id="preview-img" style="max-width:100%;max-height:200px;border-radius:6px;object-fit:contain;">
            </div>
          </div>
          <input type="file" id="apply-file" accept="image/jpeg,image/png,image/webp" style="display:none;">
        </div>

        <div style="display:flex;gap:var(--s-3);margin-top:var(--s-2);">
          <button id="btn-cancel-apply" class="btn btn-secondary" style="flex:1;min-height:44px;">${t('common.cancel')}</button>
          <button id="btn-submit-apply" class="btn btn-primary" style="flex:1;min-height:44px;font-weight:700;">${t('org.submit')}</button>
        </div>
      </div>
    </div>
  `;

  let selectedFile = null;

  // Upload area click
  const uploadArea = content.querySelector('#upload-area');
  const fileInput = content.querySelector('#apply-file');

  uploadArea.addEventListener('click', () => {
    fileInput.click();
  });

  fileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) {
      bus.emit('toast', { text: t('org.file_too_large'), type: 'error' });
      return;
    }
    selectedFile = file;
    const reader = new FileReader();
    reader.onload = (ev) => {
      content.querySelector('#upload-placeholder').style.display = 'none';
      const preview = content.querySelector('#upload-preview');
      preview.style.display = 'block';
      content.querySelector('#preview-img').src = ev.target.result;
    };
    reader.readAsDataURL(file);
  });

  // Cancel
  content.querySelector('#btn-cancel-apply').addEventListener('click', () => {
    audio.play('click');
    loadOrgs(el);
  });

  // Submit
  content.querySelector('#btn-submit-apply').addEventListener('click', async () => {
    audio.play('click');
    const docType = content.querySelector('#apply-doc-type').value;
    const notes = content.querySelector('#apply-notes').value.trim();
    const btn = content.querySelector('#btn-submit-apply');

    btn.disabled = true;
    btn.style.opacity = '0.6';
    btn.textContent = t('org.submitting');

    try {
      const formData = new FormData();
      formData.append('org_id', org.id);
      formData.append('document_type', docType);
      formData.append('notes', notes);

      if (selectedFile) {
        const compressed = await compressProofImage(selectedFile);
        formData.append('proof_document', compressed, 'proof.' + getExt(selectedFile));
      }

      const token = store.get('auth.token');
      const res = await fetch('/api/org-apply.php', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: formData
      });

      const data = await res.json();
      if (!res.ok || data.error) {
        throw new Error(data.error || t('org.submit_failed'));
      }

      bus.emit('toast', { text: t('org.submit_success'), type: 'success' });
      await loadOrgs(el);
    } catch (err) {
      bus.emit('toast', { text: err.message || t('org.submit_failed'), type: 'error' });
      btn.disabled = false;
      btn.style.opacity = '1';
      btn.textContent = t('org.submit');
    }
  });
}

function compressProofImage(file) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      const maxDim = 1200;
      let w = img.width;
      let h = img.height;
      if (w > maxDim || h > maxDim) {
        if (w > h) { h = Math.round(h * maxDim / w); w = maxDim; }
        else { w = Math.round(w * maxDim / h); h = maxDim; }
      }
      const canvas = document.createElement('canvas');
      canvas.width = w;
      canvas.height = h;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, w, h);
      canvas.toBlob(
        (blob) => blob ? resolve(blob) : reject(new Error('Compression failed')),
        'image/jpeg',
        0.8
      );
      URL.revokeObjectURL(img.src);
    };
    img.onerror = () => { URL.revokeObjectURL(img.src); reject(new Error('Invalid image')); };
    img.src = URL.createObjectURL(file);
  });
}

function getExt(file) {
  const type = file.type;
  if (type === 'image/png') return 'png';
  if (type === 'image/webp') return 'webp';
  return 'jpg';
}

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