import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';

export function renderMobileList(filterKeyword: string = '') {
  const container = document.getElementById('view-container');
  if (!container) return;

  const items = state.masterData.mobile.filter(i => 
    i.자산코드?.includes(filterKeyword) || 
    i.사용자?.includes(filterKeyword) ||
    i.명칭?.includes(filterKeyword)
  );

  container.innerHTML = `
    <div class="view-header">
      <div class="header-left">
        <h2>모바일 자산 현황</h2>
        <span class="count-badge">총 ${items.length}대</span>
      </div>
      <div class="header-actions">
        <button id="btn-add-mobile" class="btn btn-primary"><i data-lucide="plus"></i> 기기 등록</button>
      </div>
    </div>
    <div class="table-container">
      <table class="itam-table">
        <thead>
          <tr>
            <th>구분</th>
            <th>자산번호</th>
            <th>기기명</th>
            <th>사용자</th>
            <th>OS</th>
            <th>도입일</th>
            <th>상태</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          ${items.length === 0 ? '<tr><td colspan="8" class="empty-row">데이터가 없습니다.</td></tr>' : 
            items.map(i => `
            <tr class="asset-row" data-id="${i.id}">
              <td>${i.법인 || 'HM'}</td>
              <td><span class="code-link">${i.자산코드 || '미부여'}</span></td>
              <td>${i.명칭 || '-'}</td>
              <td>${i.사용자 || i.관리자 || '-'}</td>
              <td>${i.OS || '-'}</td>
              <td>${i.도입일 || '-'}</td>
              <td><span class="status-badge ${i.상태 === '사용중' ? 'active' : ''}">${i.상태 || '사용중'}</span></td>
              <td><button class="btn btn-sm btn-outline btn-detail" data-id="${i.id}">상세</button></td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  `;

  container.querySelectorAll('.asset-row, .btn-detail').forEach(el => {
    el.addEventListener('click', (e) => {
      e.stopPropagation();
      const id = (el as HTMLElement).getAttribute('data-id');
      const asset = state.masterData.mobile.find(a => a.id === id);
      if (asset) openHwModal(asset, 'view');
    });
  });

  document.getElementById('btn-add-mobile')?.addEventListener('click', () => {
    const newItem: any = { 
      id: Math.random().toString(36).substring(2, 9), 
      type: '모바일기기',
      법인: 'HM',
      상태: '사용중'
    };
    openHwModal(newItem, 'add');
  });
}
