@extends('layouts.app')

@section('title', '회원사관리')

@section('content')
<div class="flex flex-col h-full">
<!-- 페이지 헤더 -->
<div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6 flex-shrink-0">
    <div>
        <h1 class="text-2xl font-bold text-gray-800">회원사관리</h1>
        <p class="text-sm text-gray-500 mt-1">바로빌 연동 회원사를 관리합니다</p>
    </div>
    <button
        type="button"
        onclick="MemberModal.openCreate()"
        class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition text-center w-full sm:w-auto flex items-center justify-center gap-2"
    >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
        </svg>
        회원사 등록
    </button>
</div>

<!-- 통계 카드 -->
<div id="stats-container"
     hx-get="/api/admin/barobill/members/stats"
     hx-trigger="load, memberUpdated from:body, filterSubmit from:body"
     hx-include="#memberFilterForm"
     hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
     class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 flex-shrink-0">
    @include('barobill.members.partials.stats-skeleton')
</div>

<!-- 필터 영역 -->
<div class="flex-shrink-0">
<x-filter-collapsible id="memberFilterForm">
    <form id="memberFilterForm" class="flex flex-wrap items-center gap-2 sm:gap-3">
        <!-- 전체 테넌트 보기 토글 (바로빌본사용) -->
        <label class="flex items-center gap-2 px-3 py-2 bg-purple-50 border border-purple-200 rounded-lg cursor-pointer hover:bg-purple-100 transition-colors shrink-0">
            <input type="checkbox"
                   name="all_tenants"
                   value="1"
                   id="allTenantsToggle"
                   class="w-4 h-4 rounded border-purple-300 text-purple-600 focus:ring-purple-500">
            <span class="text-sm font-medium text-purple-700 whitespace-nowrap">전체 테넌트</span>
        </label>

        <!-- 검색 -->
        <div style="flex: 1 1 250px; max-width: 400px;">
            <input type="text"
                   name="search"
                   placeholder="상호명, 사업자번호, 바로빌ID로 검색..."
                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>

        <!-- 상태 필터 -->
        <div class="shrink-0" style="width: 140px;">
            <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">전체 상태</option>
                <option value="active">활성</option>
                <option value="inactive">비활성</option>
                <option value="pending">대기중</option>
            </select>
        </div>

        <!-- 검색 버튼 -->
        <button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition shrink-0">
            검색
        </button>
    </form>
</x-filter-collapsible>
</div>

<!-- 테이블 영역 (HTMX로 로드) -->
<div id="member-table"
     hx-get="/api/admin/barobill/members"
     hx-trigger="load, filterSubmit from:body, memberUpdated from:body"
     hx-include="#memberFilterForm"
     hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
     class="bg-white rounded-lg shadow-sm overflow-hidden flex-1 flex flex-col min-h-0">
    <!-- 로딩 스피너 -->
    <div class="flex justify-center items-center p-12">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
    </div>
</div>
</div><!-- end of flex container -->

<!-- 등록/수정 모달 -->
@include('barobill.members.partials.modal-form')


<!-- 상태 조회 모달 -->
<div id="statusModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50" onclick="BarobillService.closeStatusModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md max-h-[80vh] overflow-y-auto" onclick="event.stopPropagation()">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between sticky top-0 bg-white">
                <div>
                    <h3 class="text-lg font-semibold text-gray-800">바로빌 상태</h3>
                    <p class="text-sm text-gray-500">
                        <span id="statusModalMemberName" class="font-medium text-gray-700"></span> 회원사
                    </p>
                </div>
                <button type="button" onclick="BarobillService.closeStatusModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>
            <div id="statusModalContent" class="p-6">
                <!-- 동적으로 채워짐 -->
            </div>
            <div class="px-6 py-4 border-t border-gray-100">
                <button
                    type="button"
                    onclick="BarobillService.closeStatusModal()"
                    class="w-full px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
                >
                    닫기
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 서버 모드 변경 확인 모달 -->
<div id="serverModeConfirmModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50" onclick="ServerModeManager.closeModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-lg" onclick="event.stopPropagation()">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold text-gray-800">바로빌 서버 변경</h3>
                    <p class="text-sm text-gray-500">
                        <span id="serverModeModalMemberName" class="font-medium text-gray-700"></span> 회원사
                    </p>
                </div>
                <button type="button" onclick="ServerModeManager.closeModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>
            <div class="p-6 space-y-4">
                <!-- 변경 정보 -->
                <div class="flex items-center justify-center gap-4 text-center">
                    <div>
                        <p class="text-xs text-gray-500 mb-1">현재</p>
                        <p id="serverModeModalCurrentMode" class="font-semibold"></p>
                    </div>
                    <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                    </svg>
                    <div>
                        <p class="text-xs text-gray-500 mb-1">변경</p>
                        <p id="serverModeModalNewMode" class="font-semibold"></p>
                    </div>
                </div>

                <!-- 경고 메시지 -->
                <div id="serverModeWarning">
                    <!-- 동적으로 채워짐 -->
                </div>

                <!-- 확인 체크박스 -->
                <label class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg cursor-pointer hover:bg-gray-100 transition">
                    <input type="checkbox"
                           id="serverModeConfirmCheckbox"
                           onchange="ServerModeManager.onConfirmCheckChange(this.checked)"
                           class="mt-0.5 w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                    <span class="text-sm text-gray-700">
                        위 내용을 확인하였으며, <strong>서버 변경에 따른 요금 부과</strong>에 동의합니다.
                    </span>
                </label>
            </div>
            <div class="px-6 py-4 border-t border-gray-100 flex gap-3">
                <button
                    type="button"
                    onclick="ServerModeManager.closeModal()"
                    class="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
                >
                    취소
                </button>
                <button
                    type="button"
                    id="serverModeConfirmBtn"
                    onclick="ServerModeManager.confirmChange()"
                    disabled
                    class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    서버 변경
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    // 폼 제출 시 HTMX 이벤트 트리거
    document.getElementById('memberFilterForm').addEventListener('submit', function(e) {
        e.preventDefault();
        htmx.trigger('#member-table', 'filterSubmit');
    });

    // 회원사 모달 관리
    const MemberModal = {
        modal: null,
        form: null,
        isEditing: false,
        currentId: null,

        init() {
            this.modal = document.getElementById('memberModal');
            this.form = document.getElementById('memberForm');
        },

        openCreate() {
            this.isEditing = false;
            this.currentId = null;
            this.resetForm();
            document.getElementById('modalTitle').textContent = '회원사 등록';
            document.getElementById('submitBtn').textContent = '등록하기';
            // 비밀번호 필드 표시 (필수 입력)
            document.getElementById('passwordFields').classList.remove('hidden');
            document.getElementById('barobillIdField').classList.remove('hidden');  // 아이디 표시
            document.getElementById('idRequired').classList.remove('hidden');  // 아이디 필수 표시
            document.getElementById('idHint').classList.add('hidden');  // 아이디 힌트 숨김
            document.getElementById('pwdRequired').classList.remove('hidden');  // 비밀번호 필수 표시
            document.getElementById('pwdHint').classList.add('hidden');  // 비밀번호 힌트 숨김
            document.getElementById('pwdStatusBadge').classList.add('hidden');  // 상태 뱃지 숨김
            // API 검증 건너뛰기 체크박스 표시 (신규 등록 시에만)
            document.getElementById('skipApiField').classList.remove('hidden');
            // 전체 테넌트 모드일 때 테넌트 선택 필드 표시
            const allTenantsChecked = document.getElementById('allTenantsToggle')?.checked || false;
            const tenantSelectField = document.getElementById('tenantSelectField');
            if (tenantSelectField) {
                if (allTenantsChecked) {
                    tenantSelectField.classList.remove('hidden');
                } else {
                    tenantSelectField.classList.add('hidden');
                }
            }
            this.modal.classList.remove('hidden');
        },

        openEdit(id) {
            this.isEditing = true;
            this.currentId = id;
            this.resetForm();
            document.getElementById('modalTitle').textContent = '회원사 수정';
            document.getElementById('submitBtn').textContent = '수정하기';
            // 비밀번호 필드 표시 (선택적 입력)
            document.getElementById('passwordFields').classList.remove('hidden');
            document.getElementById('barobillIdField').classList.remove('hidden');  // 아이디 표시 (수정 가능)
            document.getElementById('idRequired').classList.add('hidden');  // 아이디 필수 표시 숨김
            document.getElementById('idHint').classList.remove('hidden');  // 아이디 변경 힌트 표시
            document.getElementById('pwdRequired').classList.add('hidden');  // 비밀번호 필수 표시 숨김
            document.getElementById('pwdHint').classList.remove('hidden');  // 힌트 표시
            // API 검증 건너뛰기 체크박스 숨김 (수정 시에는 불필요)
            document.getElementById('skipApiField').classList.add('hidden');
            // 테넌트 선택 필드 숨김 (수정 시에는 불필요)
            document.getElementById('tenantSelectField')?.classList.add('hidden');

            // 데이터 로드
            fetch(`/api/admin/barobill/members/${id}`, {
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                }
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const m = data.data;
                    this.form.biz_no.value = m.biz_no || '';
                    this.form.biz_no.disabled = true;
                    this.form.corp_name.value = m.corp_name || '';
                    this.form.ceo_name.value = m.ceo_name || '';
                    this.form.addr.value = m.addr || '';
                    this.form.biz_type.value = m.biz_type || '';
                    this.form.biz_class.value = m.biz_class || '';
                    this.form.barobill_id.value = m.barobill_id || '';
                    this.form.barobill_id.disabled = false;
                    this.form.manager_name.value = m.manager_name || '';
                    this.form.manager_email.value = m.manager_email || '';
                    this.form.manager_hp.value = m.manager_hp || '';
                    this.form.status.value = m.status || 'active';

                    // 비밀번호 설정 여부 뱃지 표시
                    const badge = document.getElementById('pwdStatusBadge');
                    badge.classList.remove('hidden', 'bg-green-100', 'text-green-700', 'bg-red-100', 'text-red-700');
                    if (m.has_password) {
                        badge.textContent = '설정됨';
                        badge.classList.add('bg-green-100', 'text-green-700');
                    } else {
                        badge.textContent = '미설정';
                        badge.classList.add('bg-red-100', 'text-red-700');
                    }
                }
            });

            this.modal.classList.remove('hidden');
        },

        close() {
            this.modal.classList.add('hidden');
            this.resetForm();
        },

        resetForm() {
            this.form.reset();
            this.form.biz_no.disabled = false;
            this.form.barobill_id.disabled = false;
            // 체크박스 초기화
            const skipApiCheckbox = this.form.querySelector('input[name="skip_api"]');
            if (skipApiCheckbox) skipApiCheckbox.checked = false;
            // 비밀번호 상태 뱃지 초기화
            const badge = document.getElementById('pwdStatusBadge');
            if (badge) {
                badge.classList.add('hidden');
                badge.classList.remove('bg-green-100', 'text-green-700', 'bg-red-100', 'text-red-700');
            }
        },

        async submit(e) {
            e.preventDefault();

            const formData = new FormData(this.form);
            const data = Object.fromEntries(formData.entries());

            // skip_api 체크박스 값을 boolean으로 변환
            data.skip_api = this.form.querySelector('input[name="skip_api"]')?.checked || false;

            // 수정 시 불필요 필드 제외
            if (this.isEditing) {
                delete data.biz_no;
                delete data.skip_api;
                // 아이디/비밀번호가 비어있으면 제외 (서버에서 기존 값 유지)
                if (!data.barobill_id) {
                    delete data.barobill_id;
                }
                if (!data.barobill_pwd) {
                    delete data.barobill_pwd;
                }
            }

            const url = this.isEditing
                ? `/api/admin/barobill/members/${this.currentId}`
                : '/api/admin/barobill/members';

            const method = this.isEditing ? 'PUT' : 'POST';

            try {
                const res = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await res.json();

                if (result.success) {
                    showToast(result.message, 'success');
                    this.close();
                    htmx.trigger(document.body, 'memberUpdated');
                } else {
                    // 상세 오류 메시지 표시
                    let errorMsg = result.message || '오류가 발생했습니다.';
                    if (result.error) {
                        errorMsg += `\n[상세] ${result.error}`;
                    }
                    if (result.error_code) {
                        errorMsg += ` (코드: ${result.error_code})`;
                    }
                    // Laravel validation 오류 처리
                    if (result.errors) {
                        const firstError = Object.values(result.errors)[0];
                        errorMsg = Array.isArray(firstError) ? firstError[0] : firstError;
                    }
                    showToast(errorMsg, 'error');
                    console.error('회원사 등록/수정 오류:', result);
                }
            } catch (error) {
                console.error('통신 오류:', error);
                showToast('통신 오류가 발생했습니다.', 'error');
            }
        },

        fillTestData() {
            const randomId = Math.random().toString(36).substring(2, 8);
            const randomBiz = `123-45-${Math.floor(10000 + Math.random() * 90000)}`;

            this.form.biz_no.value = randomBiz;
            this.form.corp_name.value = `테스트기업_${randomId}`;
            this.form.ceo_name.value = '홍길동';
            this.form.addr.value = '서울특별시 강남구 테헤란로 123';
            this.form.biz_type.value = '서비스';
            this.form.biz_class.value = '소프트웨어';
            this.form.barobill_id.value = `test_${randomId}`;
            this.form.barobill_pwd.value = 'password123!';
            this.form.manager_name.value = '김철수';
            this.form.manager_hp.value = '010-1234-5678';
            this.form.manager_email.value = `test_${randomId}@example.com`;
        }
    };

    // 삭제 확인
    window.confirmDeleteMember = function(id, name) {
        showDeleteConfirm(name, async () => {
            try {
                const res = await fetch(`/api/admin/barobill/members/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    }
                });
                const result = await res.json();
                if (result.success) {
                    showToast(result.message, 'success');
                    htmx.trigger(document.body, 'memberUpdated');
                } else {
                    showToast(result.message || '삭제 실패', 'error');
                }
            } catch (error) {
                showToast('통신 오류가 발생했습니다.', 'error');
            }
        });
    };

    // 바로빌 서비스 관리
    const BarobillService = {
        currentMemberId: null,
        currentMemberName: '',
        currentAction: '',
        currentTitle: '',

        // 액션별 엔드포인트 매핑
        endpoints: {
            // 계좌 관련
            'bank_account': 'bank-account-url',
            'bank_account_manage': 'bank-account-manage-url',
            'bank_account_log': 'bank-account-log-url',
            // 카드 관련
            'card': 'card-url',
            'card_manage': 'card-manage-url',
            'card_log': 'card-log-url',
            // 전자세금계산서 관련
            'certificate': 'certificate-url',
            'tax_invoice': 'tax-invoice-url',
            'tax_invoice_list': 'tax-invoice-list-url',
            // 공통
            'cash_charge': 'cash-charge-url',
        },

        // 통합 URL 열기 함수 (비밀번호 입력 없이 바로 호출)
        async openUrl(memberId, memberName, action, title) {
            const endpoint = this.endpoints[action];
            if (!endpoint) {
                showToast('잘못된 액션입니다.', 'error');
                return;
            }

            try {
                const res = await fetch(`/api/admin/barobill/members/${memberId}/${endpoint}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({})
                });

                const result = await res.json();

                if (result.success && result.data?.url) {
                    window.open(result.data.url, '_blank', 'width=1000,height=700');
                } else {
                    showToast(result.message || result.error || 'URL을 가져오는데 실패했습니다.', 'error');
                }
            } catch (error) {
                showToast('통신 오류가 발생했습니다.', 'error');
            }
        },

        // 상태 조회 모달 열기
        async showStatus(memberId, memberName) {
            document.getElementById('statusModalMemberName').textContent = memberName;
            document.getElementById('statusModalContent').innerHTML = `
                <div class="flex justify-center py-8">
                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                </div>
            `;
            document.getElementById('statusModal').classList.remove('hidden');

            try {
                // 병렬로 상태 조회 (인증서, 잔액, 계좌, 카드)
                const [certRes, balanceRes, accountsRes, cardsRes] = await Promise.all([
                    fetch(`/api/admin/barobill/members/${memberId}/certificate-status`, {
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
                    }),
                    fetch(`/api/admin/barobill/members/${memberId}/balance`, {
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
                    }),
                    fetch(`/api/admin/barobill/members/${memberId}/bank-accounts`, {
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
                    }),
                    fetch(`/api/admin/barobill/members/${memberId}/cards`, {
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
                    }),
                ]);

                const cert = await certRes.json();
                const balance = await balanceRes.json();
                const accounts = await accountsRes.json();
                const cards = await cardsRes.json();

                this.renderStatusContent(cert, balance, accounts, cards);
            } catch (error) {
                document.getElementById('statusModalContent').innerHTML = `
                    <div class="text-center text-red-500 py-8">
                        <p>상태 조회 중 오류가 발생했습니다.</p>
                    </div>
                `;
            }
        },

        renderStatusContent(cert, balance, accounts, cards) {
            const certData = cert.success ? cert.data : {};
            const balanceData = balance.success ? balance.data : {};

            let html = `
                <div class="space-y-4">
                    <!-- 인증서 상태 -->
                    <div class="bg-purple-50 rounded-lg p-4">
                        <h4 class="text-sm font-medium text-purple-700 mb-3 flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                            </svg>
                            공동인증서 (전자세금계산서용)
                        </h4>
                        <div class="grid grid-cols-2 gap-4 text-sm">
                            <div>
                                <span class="text-purple-600">상태</span>
                                <p class="font-medium ${certData.is_valid ? 'text-green-600' : 'text-red-600'}">
                                    ${certData.is_valid ? '유효' : '미등록 또는 만료'}
                                </p>
                            </div>
                            <div>
                                <span class="text-purple-600">만료일</span>
                                <p class="font-medium text-gray-800">${certData.expire_date || '-'}</p>
                            </div>
                        </div>
                    </div>

                    <!-- 충전 잔액 -->
                    <div class="bg-yellow-50 rounded-lg p-4">
                        <h4 class="text-sm font-medium text-yellow-700 mb-2 flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            충전 잔액
                        </h4>
                        <p class="text-2xl font-bold text-gray-800">
                            ${balanceData.balance !== undefined ? Number(balanceData.balance).toLocaleString() + '원' : '-'}
                        </p>
                    </div>

                    <!-- 등록 계좌 -->
                    <div class="bg-green-50 rounded-lg p-4">
                        <h4 class="text-sm font-medium text-green-700 mb-3 flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                            </svg>
                            등록 계좌 (빠른조회 서비스)
                        </h4>
            `;

            if (accounts.success && accounts.data) {
                const accountList = Array.isArray(accounts.data) ? accounts.data :
                    (accounts.data.BankAccountInfo ? [accounts.data.BankAccountInfo] : []);

                if (accountList.length > 0) {
                    html += `<div class="space-y-2">`;
                    accountList.forEach(acc => {
                        html += `
                            <div class="flex justify-between items-center text-sm bg-white p-2 rounded border border-green-200">
                                <span class="text-gray-600">${acc.Bank || acc.BankCode || '은행'}</span>
                                <span class="font-mono text-gray-800">${acc.BankAccountNum || acc.AccountNum || '-'}</span>
                            </div>
                        `;
                    });
                    html += `</div>`;
                } else {
                    html += `<p class="text-sm text-green-600">등록된 계좌가 없습니다.</p>`;
                }
            } else {
                html += `<p class="text-sm text-green-600">계좌 정보를 불러올 수 없습니다.</p>`;
            }

            html += `</div>`;

            // 등록 카드
            html += `
                    <div class="bg-blue-50 rounded-lg p-4">
                        <h4 class="text-sm font-medium text-blue-700 mb-3 flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                            </svg>
                            등록 카드
                        </h4>
            `;

            if (cards && cards.success && cards.data) {
                const cardList = Array.isArray(cards.data) ? cards.data :
                    (cards.data.CardInfo ? [cards.data.CardInfo] : []);

                if (cardList.length > 0) {
                    html += `<div class="space-y-2">`;
                    cardList.forEach(card => {
                        const cardNum = card.CardNum || card.cardNum || '-';
                        const maskedNum = cardNum.length > 8 ? cardNum.slice(0, 4) + '-****-****-' + cardNum.slice(-4) : cardNum;
                        html += `
                            <div class="flex justify-between items-center text-sm bg-white p-2 rounded border border-blue-200">
                                <span class="text-gray-600">${card.CardCompanyName || card.cardCompanyName || '카드사'}</span>
                                <span class="font-mono text-gray-800">${maskedNum}</span>
                            </div>
                        `;
                    });
                    html += `</div>`;
                } else {
                    html += `<p class="text-sm text-blue-600">등록된 카드가 없습니다.</p>`;
                }
            } else {
                html += `<p class="text-sm text-blue-600">카드 정보를 불러올 수 없습니다.</p>`;
            }

            html += `
                    </div>
                </div>
            `;

            document.getElementById('statusModalContent').innerHTML = html;
        },

        closeStatusModal() {
            document.getElementById('statusModal').classList.add('hidden');
        }
    };

    // 바로빌 드롭다운 토글 (vanilla JS)
    let currentOpenDropdown = null;

    function toggleBarobillDropdown(button) {
        const dropdown = button.closest('.barobill-dropdown');
        const menu = dropdown.querySelector('.barobill-menu');
        const isOpen = !menu.classList.contains('hidden');

        // 다른 열린 드롭다운 닫기
        closeBarobillDropdown();

        if (!isOpen) {
            menu.classList.remove('hidden');
            currentOpenDropdown = dropdown;
        }
    }

    function closeBarobillDropdown() {
        if (currentOpenDropdown) {
            const menu = currentOpenDropdown.querySelector('.barobill-menu');
            if (menu) menu.classList.add('hidden');
            currentOpenDropdown = null;
        }
        // 모든 드롭다운 닫기
        document.querySelectorAll('.barobill-menu').forEach(menu => {
            menu.classList.add('hidden');
        });
    }

    // 바깥 클릭 시 드롭다운 닫기
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.barobill-dropdown')) {
            closeBarobillDropdown();
        }
    });

    // ESC 키로 드롭다운 닫기
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeBarobillDropdown();
        }
    });

    // 회원사별 서버 모드 변경 관리
    const ServerModeManager = {
        pendingMemberId: null,
        pendingMode: null,

        // 서버 모드 변경 요청 (경고 모달 표시)
        requestChange(memberId, memberName, currentMode) {
            this.pendingMemberId = memberId;
            const newMode = currentMode === 'test' ? 'production' : 'test';
            this.pendingMode = newMode;

            const modal = document.getElementById('serverModeConfirmModal');
            const memberNameEl = document.getElementById('serverModeModalMemberName');
            const currentModeEl = document.getElementById('serverModeModalCurrentMode');
            const newModeEl = document.getElementById('serverModeModalNewMode');
            const warningEl = document.getElementById('serverModeWarning');
            const confirmCheckbox = document.getElementById('serverModeConfirmCheckbox');

            memberNameEl.textContent = memberName;
            currentModeEl.textContent = currentMode === 'test' ? '테스트 서버' : '운영 서버';
            currentModeEl.className = currentMode === 'test'
                ? 'font-semibold text-amber-600'
                : 'font-semibold text-green-600';
            newModeEl.textContent = newMode === 'test' ? '테스트 서버' : '운영 서버';
            newModeEl.className = newMode === 'test'
                ? 'font-semibold text-amber-600'
                : 'font-semibold text-green-600';

            // 운영 서버로 전환 시 추가 경고
            if (newMode === 'production') {
                warningEl.innerHTML = `
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
                        <div class="flex items-start gap-3">
                            <svg class="w-5 h-5 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                            </svg>
                            <div>
                                <p class="font-semibold">⚠️ 요금 부과 안내</p>
                                <ul class="mt-2 text-sm space-y-1">
                                    <li>• 운영 서버 사용 시 <strong>실제 요금이 부과</strong>됩니다.</li>
                                    <li>• 회원사 등록, 세금계산서 발행 등 모든 API 호출에 과금됩니다.</li>
                                    <li>• 테스트 목적이라면 테스트 서버를 사용해 주세요.</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                warningEl.innerHTML = `
                    <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 text-amber-700">
                        <div class="flex items-start gap-3">
                            <svg class="w-5 h-5 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <div>
                                <p class="font-semibold">테스트 서버 안내</p>
                                <ul class="mt-2 text-sm space-y-1">
                                    <li>• 테스트 서버는 개발/테스트 용도로만 사용됩니다.</li>
                                    <li>• 테스트 데이터는 실제 국세청에 전송되지 않습니다.</li>
                                    <li>• 운영 환경에서는 반드시 운영 서버로 전환해 주세요.</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                `;
            }

            confirmCheckbox.checked = false;
            document.getElementById('serverModeConfirmBtn').disabled = true;
            modal.classList.remove('hidden');
        },

        // 확인 체크박스 상태 변경
        onConfirmCheckChange(checked) {
            document.getElementById('serverModeConfirmBtn').disabled = !checked;
        },

        // 서버 모드 변경 실행
        async confirmChange() {
            if (!this.pendingMemberId || !this.pendingMode) return;

            const confirmBtn = document.getElementById('serverModeConfirmBtn');
            const originalText = confirmBtn.textContent;
            confirmBtn.disabled = true;
            confirmBtn.textContent = '변경 중...';

            try {
                const res = await fetch(`/api/admin/barobill/members/${this.pendingMemberId}/server-mode`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        server_mode: this.pendingMode,
                        confirmed: true
                    })
                });

                const data = await res.json();

                if (data.success) {
                    showToast(data.message, 'success');
                    this.closeModal();
                    htmx.trigger(document.body, 'memberUpdated');
                } else {
                    showToast(data.message || '서버 모드 변경 실패', 'error');
                }
            } catch (error) {
                console.error('서버 모드 변경 실패:', error);
                showToast('서버 모드 변경 중 오류가 발생했습니다.', 'error');
            } finally {
                confirmBtn.disabled = false;
                confirmBtn.textContent = originalText;
            }
        },

        // 모달 닫기
        closeModal() {
            document.getElementById('serverModeConfirmModal').classList.add('hidden');
            this.pendingMemberId = null;
            this.pendingMode = null;
        }
    };

    // 초기화
    document.addEventListener('DOMContentLoaded', function() {
        MemberModal.init();
    });
</script>
@endpush
