import { icons } from '../services/icons.js';
import { apiGet, apiPost, apiPut } from '../services/apiClient.js';
import { getCountries } from '../services/setup.js';
import { showToast } from '../services/toast.js';

const API_ACCOUNTS  = '/api/Bank/accounts';
const API_MOVEMENTS = '/api/Bank/movements';

const DOLIBARR_LABELS = {
  '(InitialBankBalance)': 'Saldo inicial',
  '(banktransfert)':      'Transferencia interna',
  '(payment)':            'Pago',
  '(withdraw)':           'Retirada',
};

function cleanLabel(raw) {
  if (!raw) return 'Movimiento';
  return DOLIBARR_LABELS[raw] ?? raw;
}

export function renderBancoPage() {
  const container = document.createElement('div');
  container.className = 'banco-page';

  const fmt     = (n) => new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(n ?? 0);
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString('es-ES') : '—';

  container.innerHTML = /*html*/`
    <div class="banco-header">
      <h1>Banco</h1>
      <p class="banco-subtitle">Gestión de cuentas bancarias y movimientos</p>
    </div>

    <div class="banco-summary-grid">
      <div class="banco-stat-card banco-stat-card--balance">
        <div class="banco-stat-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/>
          </svg>
        </div>
        <div class="banco-stat-body">
          <span class="banco-stat-label">Saldo total</span>
          <span class="banco-stat-value" id="stat-balance">—</span>
        </div>
      </div>

      <div class="banco-stat-card banco-stat-card--income">
        <div class="banco-stat-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/>
            <polyline points="17 6 23 6 23 12"/>
          </svg>
        </div>
        <div class="banco-stat-body">
          <span class="banco-stat-label">Ingresos</span>
          <span class="banco-stat-value" id="stat-income">—</span>
        </div>
      </div>

      <div class="banco-stat-card banco-stat-card--expense">
        <div class="banco-stat-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="23 18 13.5 8.5 8.5 13.5 1 6"/>
            <polyline points="17 18 23 18 23 12"/>
          </svg>
        </div>
        <div class="banco-stat-body">
          <span class="banco-stat-label">Gastos</span>
          <span class="banco-stat-value" id="stat-expense">—</span>
        </div>
      </div>

      <div class="banco-stat-card banco-stat-card--accounts">
        <div class="banco-stat-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9 22 9 12 15 12 15 22"/>
          </svg>
        </div>
        <div class="banco-stat-body">
          <span class="banco-stat-label">Cuentas</span>
          <span class="banco-stat-value" id="stat-accounts">—</span>
        </div>
      </div>
    </div>

    <div class="banco-content-grid">
      <div class="banco-card banco-card--accounts">
        <div class="banco-card-header">
          <h2>Cuentas bancarias</h2>
          <button class="btn-banco-new" id="btn-new-account">+ Nueva cuenta</button>
        </div>
        <div class="banco-accounts-list" id="banco-accounts">
          <div class="banco-loading">
            <div class="banco-skeleton"></div>
            <div class="banco-skeleton"></div>
            <div class="banco-skeleton"></div>
          </div>
        </div>
      </div>

      <div class="banco-card banco-card--transactions">
        <div class="banco-card-header">
          <h2 id="tx-title">Últimos movimientos</h2>
          <button class="btn-banco-back" id="btn-all-movements" style="display:none">
            ← Todos
          </button>
        </div>
        <div class="banco-transactions-list" id="banco-transactions">
          <div class="banco-loading">
            <div class="banco-skeleton"></div>
            <div class="banco-skeleton"></div>
            <div class="banco-skeleton"></div>
            <div class="banco-skeleton"></div>
          </div>
        </div>
      </div>
    </div>
  `;

  let allMovements = [];
  let selectedAccountId = null;

  // ── Render helpers ────────────────────────────────────────────────

  function renderAccounts(list) {
    const el = container.querySelector('#banco-accounts');
    if (!list || list.length === 0) {
      el.innerHTML = `<div class="banco-empty">
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" style="color:var(--gray-300)">
          <rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/>
        </svg>
        <p>No hay cuentas bancarias registradas</p>
      </div>`;
      return;
    }

    const totalBalance = list.reduce((s, a) => s + (parseFloat(a.balance) || 0), 0);
    container.querySelector('#stat-balance').textContent  = fmt(totalBalance);
    container.querySelector('#stat-accounts').textContent = list.length;

    el.innerHTML = '';
    list.forEach(acc => {
      const item = document.createElement('div');
      item.className = `banco-account-item${acc.isClosed ? ' banco-account-item--closed' : ''}`;
      item.dataset.id = acc.id;
      item.innerHTML = `
        <div class="banco-account-icon">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/>
          </svg>
        </div>
        <div class="banco-account-info">
          <span class="banco-account-name">${acc.label || acc.ref || 'Cuenta sin nombre'}${acc.isClosed ? ' <span class="banco-account-closed-badge">Cerrada</span>' : ''}</span>
          <span class="banco-account-sub">${acc.iban || acc.accountNumber || acc.ref || '—'}</span>
        </div>
        <div class="banco-account-right">
          <span class="banco-account-balance ${parseFloat(acc.balance) < 0 ? 'banco-account-balance--negative' : ''}">${fmt(acc.balance)}</span>
          <button class="btn-account-edit" title="Editar cuenta" aria-label="Editar ${acc.label}">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="pointer-events:none">
              <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/>
            </svg>
          </button>
          <svg class="banco-account-arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
        </div>
      `;
      item.querySelector('.btn-account-edit').addEventListener('click', (e) => {
        e.stopPropagation();
        showEditAccountModal(acc);
      });
      item.addEventListener('click', () => selectAccount(acc));
      el.appendChild(item);
    });
  }

  function renderTransactions(list, subtitle = null) {
    const el    = container.querySelector('#banco-transactions');
    const title = container.querySelector('#tx-title');
    const back  = container.querySelector('#btn-all-movements');

    title.textContent = subtitle ? `Movimientos · ${subtitle}` : 'Últimos movimientos';
    back.style.display = subtitle ? 'inline-flex' : 'none';

    if (!list || list.length === 0) {
      el.innerHTML = `<div class="banco-empty"><p>No hay movimientos${subtitle ? ' para esta cuenta' : ' recientes'}</p></div>`;
      return;
    }

    let income = 0, expense = 0;
    el.innerHTML = list.map(tx => {
      const amount = parseFloat(tx.amount) || 0;
      if (amount >= 0) income += amount; else expense += Math.abs(amount);
      return `
        <div class="banco-tx-item">
          <div class="banco-tx-indicator ${amount >= 0 ? 'banco-tx-indicator--credit' : 'banco-tx-indicator--debit'}"></div>
          <div class="banco-tx-info">
            <span class="banco-tx-label">${cleanLabel(tx.label)}</span>
            <span class="banco-tx-date">${fmtDate(tx.dateValue || tx.date)}</span>
          </div>
          <span class="banco-tx-amount ${amount >= 0 ? 'banco-tx-amount--credit' : 'banco-tx-amount--debit'}">
            ${amount >= 0 ? '+' : ''}${fmt(amount)}
          </span>
        </div>
      `;
    }).join('');

    if (!subtitle) {
      container.querySelector('#stat-income').textContent  = fmt(income);
      container.querySelector('#stat-expense').textContent = fmt(expense);
    }
  }

  function renderUnavailable(section) {
    const el = container.querySelector(section);
    el.innerHTML = `<div class="banco-empty banco-empty--soon">
      <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" style="color:var(--gray-300)">
        <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
      </svg>
      <p>Módulo bancario no disponible aún</p>
      <span class="banco-soon-tag">Próximamente</span>
    </div>`;
  }

  // ── Account selection ─────────────────────────────────────────────

  async function selectAccount(acc) {
    selectedAccountId = acc.id;

    // Highlight selected
    container.querySelectorAll('.banco-account-item').forEach(el => {
      el.classList.toggle('banco-account-item--active', String(el.dataset.id) === String(acc.id));
    });

    const el = container.querySelector('#banco-transactions');
    el.innerHTML = `<div class="banco-loading"><div class="banco-skeleton"></div><div class="banco-skeleton"></div><div class="banco-skeleton"></div></div>`;
    container.querySelector('#tx-title').textContent = `Movimientos · ${acc.label || acc.ref}`;
    container.querySelector('#btn-all-movements').style.display = 'inline-flex';

    try {
      const raw  = await apiGet(`${API_ACCOUNTS}/${acc.id}/lines`);
      const lines = Array.isArray(raw) ? raw : raw?.data ?? [];
      renderTransactions(lines, acc.label || acc.ref);
    } catch {
      el.innerHTML = `<div class="banco-empty"><p>No se pudieron cargar los movimientos</p></div>`;
    }
  }

  function showAllMovements() {
    selectedAccountId = null;
    container.querySelectorAll('.banco-account-item').forEach(el => el.classList.remove('banco-account-item--active'));
    renderTransactions(allMovements);
  }

  container.querySelector('#btn-all-movements').addEventListener('click', showAllMovements);

  // ── Load all data ─────────────────────────────────────────────────

  async function loadData() {
    try {
      const raw      = await apiGet(API_ACCOUNTS);
      const accounts = Array.isArray(raw) ? raw : raw?.data ?? [];
      renderAccounts(accounts);
    } catch {
      renderUnavailable('#banco-accounts');
      container.querySelector('#stat-balance').textContent  = '—';
      container.querySelector('#stat-accounts').textContent = '—';
    }

    try {
      const raw = await apiGet(`${API_MOVEMENTS}?limit=50`);
      allMovements = Array.isArray(raw) ? raw : raw?.data ?? [];
      renderTransactions(allMovements);
    } catch {
      renderUnavailable('#banco-transactions');
      container.querySelector('#stat-income').textContent  = '—';
      container.querySelector('#stat-expense').textContent = '—';
    }
  }

  // ── Edit account modal ────────────────────────────────────────────

  function showEditAccountModal(acc) {
    const overlay = document.createElement('div');
    overlay.className = 'banco-modal-overlay';
    overlay.innerHTML = /*html*/`
      <div class="banco-modal">
        <div class="banco-modal-header">
          <div class="banco-modal-title-group">
            <div class="banco-modal-icon banco-modal-icon--edit">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
              </svg>
            </div>
            <div>
              <h2>Editar cuenta bancaria</h2>
              <p class="banco-modal-subtitle">${acc.label || acc.ref || 'Cuenta sin nombre'}</p>
            </div>
          </div>
          <button class="banco-modal-close" type="button" aria-label="Cerrar">✕</button>
        </div>

        <form class="banco-modal-form" id="edit-account-form" novalidate>
          <div class="banco-form-section">
            <span class="banco-form-section-label">Identificación</span>
            <div class="banco-form-grid">
              <div class="banco-form-field banco-form-field--full">
                <label class="banco-form-label" for="edit-label">Nombre de la cuenta</label>
                <input type="text" class="banco-form-input" id="edit-label" value="${acc.label || ''}" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-ref">Código / Ref</label>
                <input type="text" class="banco-form-input" id="edit-ref" value="${acc.ref || ''}" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-type">Tipo de cuenta</label>
                <select class="banco-form-input" id="edit-type">
                  <option value="1">Cuenta corriente</option>
                  <option value="0">Cuenta de ahorro</option>
                  <option value="2">Caja</option>
                </select>
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-currency">Divisa</label>
                <input type="text" class="banco-form-input" id="edit-currency" value="${acc.currencyCode || 'EUR'}" maxlength="3" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-country">País</label>
                <select class="banco-form-input" id="edit-country">
                  <option value="">Cargando...</option>
                </select>
              </div>
            </div>
          </div>

          <div class="banco-form-section">
            <span class="banco-form-section-label">Datos bancarios <span class="banco-form-section-optional">(opcional)</span></span>
            <div class="banco-form-grid">
              <div class="banco-form-field banco-form-field--full">
                <label class="banco-form-label" for="edit-bank">Entidad bancaria</label>
                <input type="text" class="banco-form-input" id="edit-bank" value="${acc.bank || ''}" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-number">Número de cuenta</label>
                <input type="text" class="banco-form-input" id="edit-number" value="${acc.accountNumber || ''}" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-iban">IBAN</label>
                <input type="text" class="banco-form-input" id="edit-iban" value="${acc.iban || ''}" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="edit-bic">BIC / SWIFT</label>
                <input type="text" class="banco-form-input" id="edit-bic" value="${acc.bic || ''}" autocomplete="off" />
              </div>
            </div>
          </div>

          <div class="banco-modal-footer">
            <button type="button" class="btn-banco-cancel" id="cancel-edit">Cancelar</button>
            <button type="submit" class="btn-banco-submit">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              Guardar cambios
            </button>
          </div>
        </form>
      </div>
    `;

    document.body.appendChild(overlay);

    // Set type select value
    const typeSelect = overlay.querySelector('#edit-type');
    if (acc.type != null) typeSelect.value = String(acc.type);

    // Load countries and pre-select current
    (async () => {
      const sel = overlay.querySelector('#edit-country');
      try {
        const countries = await getCountries();
        const priority  = ['ES','FR','DE','PT','GB','US'];
        const first = countries.filter(c => priority.includes(c.code));
        const rest  = countries.filter(c => !priority.includes(c.code));
        sel.innerHTML = '<option value="">Sin especificar</option>';
        first.forEach(c => { const o = document.createElement('option'); o.value = c.id; o.textContent = c.label; sel.appendChild(o); });
        if (rest.length) {
          const sep = document.createElement('option'); sep.disabled = true; sep.textContent = '──────────'; sel.appendChild(sep);
          rest.forEach(c => { const o = document.createElement('option'); o.value = c.id; o.textContent = c.label; sel.appendChild(o); });
        }
        if (acc.countryId) sel.value = String(acc.countryId);
      } catch {
        sel.innerHTML = `
          <option value="">Sin especificar</option>
          <option value="4">España</option>
          <option value="1">Francia</option>
          <option value="5">Alemania</option>
          <option value="25">Portugal</option>
          <option value="7">Reino Unido</option>
          <option value="11">Estados Unidos</option>`;
        if (acc.countryId) sel.value = String(acc.countryId);
      }
    })();

    const close = () => { if (overlay.isConnected) overlay.remove(); };
    overlay.querySelector('.banco-modal-close').addEventListener('click', close);
    overlay.querySelector('#cancel-edit').addEventListener('click', close);
    overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
    document.addEventListener('keydown', function esc(e) {
      if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc); }
    });

    overlay.querySelector('#edit-account-form').addEventListener('submit', async (e) => {
      e.preventDefault();

      const payload = {};
      const label    = overlay.querySelector('#edit-label').value.trim();
      const ref      = overlay.querySelector('#edit-ref').value.trim();
      const currency = overlay.querySelector('#edit-currency').value.trim();
      const bank     = overlay.querySelector('#edit-bank').value.trim();
      const number   = overlay.querySelector('#edit-number').value.trim();
      const iban     = overlay.querySelector('#edit-iban').value.trim();
      const bic      = overlay.querySelector('#edit-bic').value.trim();
      const countryId = parseInt(overlay.querySelector('#edit-country').value) || null;
      const type      = parseInt(overlay.querySelector('#edit-type').value);

      if (label)     payload.label         = label;
      if (ref)       payload.ref           = ref;
      if (currency)  payload.currencyCode  = currency;
      if (bank)      payload.bank          = bank;
      if (number)    payload.accountNumber = number;
      if (iban)      payload.iban          = iban;
      if (bic)       payload.bic           = bic;
      if (countryId) payload.countryId     = countryId;
      payload.type = type;

      if (Object.keys(payload).length === 1 && payload.type === acc.type) {
        close(); return;
      }

      const submitBtn = overlay.querySelector('.btn-banco-submit');
      submitBtn.disabled = true;
      submitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation:spin 0.8s linear infinite"><circle cx="12" cy="12" r="10" stroke-opacity="0.25"/><path d="M12 2a10 10 0 0 1 10 10"/></svg> Guardando...';

      try {
        await apiPut(`/api/Bank/accounts/${acc.id}`, payload);
        showToast('Cuenta actualizada', 'success');
        close();
        loadData();
      } catch (err) {
        showToast(err.message || 'Error al actualizar la cuenta', 'error');
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg> Guardar cambios';
      }
    });
  }

  // ── Create account modal ──────────────────────────────────────────

  function showCreateAccountModal() {
    const overlay = document.createElement('div');
    overlay.className = 'banco-modal-overlay';
    overlay.innerHTML = /*html*/`
      <div class="banco-modal">
        <div class="banco-modal-header">
          <div class="banco-modal-title-group">
            <div class="banco-modal-icon">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
                <rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/>
              </svg>
            </div>
            <div>
              <h2>Nueva cuenta bancaria</h2>
              <p class="banco-modal-subtitle">Los campos marcados con * son obligatorios</p>
            </div>
          </div>
          <button class="banco-modal-close" type="button" aria-label="Cerrar">✕</button>
        </div>

        <form class="banco-modal-form" id="create-account-form" novalidate>

          <div class="banco-form-section">
            <span class="banco-form-section-label">Identificación</span>
            <div class="banco-form-grid">
              <div class="banco-form-field banco-form-field--full">
                <label class="banco-form-label" for="acc-label">Nombre de la cuenta <span class="required">*</span></label>
                <input type="text" class="banco-form-input" id="acc-label" placeholder="Ej: Cuenta corriente principal" autocomplete="off" required />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-ref">Código / Ref <span class="required">*</span></label>
                <input type="text" class="banco-form-input" id="acc-ref" placeholder="Ej: CAJA-01" autocomplete="off" required />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-type">Tipo de cuenta <span class="required">*</span></label>
                <select class="banco-form-input" id="acc-type">
                  <option value="1">Cuenta corriente</option>
                  <option value="0">Cuenta de ahorro</option>
                  <option value="2">Caja</option>
                </select>
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-currency">Divisa <span class="required">*</span></label>
                <input type="text" class="banco-form-input" id="acc-currency" value="EUR" maxlength="3" autocomplete="off" required />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-country">País <span class="required">*</span></label>
                <select class="banco-form-input" id="acc-country">
                  <option value="">Cargando países...</option>
                </select>
              </div>
            </div>
          </div>

          <div class="banco-form-section">
            <span class="banco-form-section-label">Datos bancarios <span class="banco-form-section-optional">(opcional)</span></span>
            <div class="banco-form-grid">
              <div class="banco-form-field banco-form-field--full">
                <label class="banco-form-label" for="acc-bank">Entidad bancaria</label>
                <input type="text" class="banco-form-input" id="acc-bank" placeholder="Nombre del banco" autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-number">Número de cuenta</label>
                <input type="text" class="banco-form-input" id="acc-number" placeholder="ES12 3456 7890..." autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-iban">IBAN</label>
                <input type="text" class="banco-form-input" id="acc-iban" placeholder="ES00 0000 0000..." autocomplete="off" />
              </div>
              <div class="banco-form-field">
                <label class="banco-form-label" for="acc-bic">BIC / SWIFT</label>
                <input type="text" class="banco-form-input" id="acc-bic" placeholder="CAIXESBBXXX" autocomplete="off" />
              </div>
            </div>
          </div>

          <div class="banco-modal-footer">
            <button type="button" class="btn-banco-cancel" id="cancel-account">Cancelar</button>
            <button type="submit" class="btn-banco-submit">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              Crear cuenta
            </button>
          </div>
        </form>
      </div>
    `;

    document.body.appendChild(overlay);
    // Focus first input
    setTimeout(() => overlay.querySelector('#acc-label')?.focus(), 50);

    // Load countries
    (async () => {
      const sel = overlay.querySelector('#acc-country');
      try {
        const countries = await getCountries();
        const priority  = ['ES','FR','DE','PT','GB','US'];
        const first = countries.filter(c => priority.includes(c.code));
        const rest  = countries.filter(c => !priority.includes(c.code));
        sel.innerHTML = '<option value="">Seleccionar país...</option>';
        first.forEach(c => {
          const o = document.createElement('option');
          o.value = c.id; o.textContent = c.label;
          if (c.code === 'ES') o.selected = true;
          sel.appendChild(o);
        });
        if (rest.length) {
          const sep = document.createElement('option'); sep.disabled = true; sep.textContent = '──────────';
          sel.appendChild(sep);
          rest.forEach(c => { const o = document.createElement('option'); o.value = c.id; o.textContent = c.label; sel.appendChild(o); });
        }
      } catch {
        sel.innerHTML = `
          <option value="">Seleccionar país...</option>
          <option value="4" selected>España</option>
          <option value="1">Francia</option>
          <option value="5">Alemania</option>
          <option value="25">Portugal</option>
          <option value="7">Reino Unido</option>
          <option value="11">Estados Unidos</option>`;
      }
    })();

    const close = () => { if (overlay.isConnected) overlay.remove(); };
    overlay.querySelector('.banco-modal-close').addEventListener('click', close);
    overlay.querySelector('#cancel-account').addEventListener('click', close);
    overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
    document.addEventListener('keydown', function esc(e) {
      if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc); }
    });

    overlay.querySelector('#create-account-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const label = overlay.querySelector('#acc-label').value.trim();
      const ref   = overlay.querySelector('#acc-ref').value.trim();
      const countryId = parseInt(overlay.querySelector('#acc-country').value);

      if (!label) { showToast('El nombre es obligatorio', 'warning'); overlay.querySelector('#acc-label').focus(); return; }
      if (!ref)   { showToast('El código/ref es obligatorio', 'warning'); overlay.querySelector('#acc-ref').focus(); return; }
      if (!countryId) { showToast('Selecciona un país', 'warning'); overlay.querySelector('#acc-country').focus(); return; }

      const submitBtn = overlay.querySelector('.btn-banco-submit');
      submitBtn.disabled = true;
      submitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation:spin 0.8s linear infinite"><circle cx="12" cy="12" r="10" stroke-opacity="0.25"/><path d="M12 2a10 10 0 0 1 10 10"/></svg> Guardando...';

      try {
        await apiPost('/api/Bank/accounts', {
          label,
          ref,
          type:          parseInt(overlay.querySelector('#acc-type').value),
          currencyCode:  overlay.querySelector('#acc-currency').value.trim() || 'EUR',
          countryId,
          bank:          overlay.querySelector('#acc-bank').value.trim() || null,
          accountNumber: overlay.querySelector('#acc-number').value.trim() || null,
          iban:          overlay.querySelector('#acc-iban').value.trim() || null,
          bic:           overlay.querySelector('#acc-bic').value.trim() || null,
        });
        showToast('Cuenta bancaria creada', 'success');
        close();
        loadData();
      } catch (err) {
        showToast(err.message || 'Error al crear la cuenta', 'error');
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg> Crear cuenta';
      }
    });
  }

  container.querySelector('#btn-new-account').addEventListener('click', showCreateAccountModal);

  loadData();
  return container;
}
