<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>반품 관리 - 청춘약국</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0f172a;
            --bg-secondary: #1e293b;
            --bg-card: #1e293b;
            --bg-card-hover: #334155;
            --border: #334155;
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --text-muted: #64748b;
            --accent-teal: #14b8a6;
            --accent-blue: #3b82f6;
            --accent-purple: #a855f7;
            --accent-amber: #f59e0b;
            --accent-emerald: #10b981;
            --accent-rose: #f43f5e;
            --accent-orange: #f97316;
            --accent-cyan: #06b6d4;
            --accent-gold: #eab308;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            -webkit-font-smoothing: antialiased;
            min-height: 100vh;
        }

        /* ══════════════════ 헤더 ══════════════════ */
        .header {
            background: linear-gradient(135deg, #dc2626 0%, #f97316 50%, #f59e0b 100%);
            padding: 20px 24px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }
        .header-inner {
            max-width: 1800px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header-left h1 {
            font-size: 22px;
            font-weight: 700;
            letter-spacing: -0.5px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .header-left p {
            font-size: 13px;
            opacity: 0.85;
            margin-top: 4px;
        }
        .header-nav {
            display: flex;
            gap: 8px;
        }
        .header-nav a {
            color: rgba(255,255,255,0.85);
            text-decoration: none;
            font-size: 13px;
            font-weight: 500;
            padding: 8px 14px;
            border-radius: 8px;
            background: rgba(255,255,255,0.1);
            transition: all 0.2s;
        }
        .header-nav a:hover {
            background: rgba(255,255,255,0.2);
            color: #fff;
        }
        .header-nav a.active {
            background: rgba(255,255,255,0.25);
        }

        /* ══════════════════ 컨텐츠 ══════════════════ */
        .content {
            max-width: 1800px;
            margin: 0 auto;
            padding: 24px;
        }

        /* ══════════════════ 통계 카드 (2줄) ══════════════════ */
        .stats-row {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;
        }
        .stats-row.amount-row {
            margin-bottom: 24px;
        }
        .stat-card {
            flex: 1;
            background: var(--bg-card);
            border-radius: 14px;
            padding: 18px 20px;
            border: 1px solid var(--border);
            position: relative;
            overflow: hidden;
        }
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
        }
        .stat-card.rose::before { background: var(--accent-rose); }
        .stat-card.amber::before { background: var(--accent-amber); }
        .stat-card.cyan::before { background: var(--accent-cyan); }
        .stat-card.emerald::before { background: var(--accent-emerald); }
        .stat-card.purple::before { background: var(--accent-purple); }
        .stat-card.gold::before { background: var(--accent-gold); }
        
        .stat-icon {
            font-size: 20px;
            margin-bottom: 8px;
        }
        .stat-value {
            font-size: 24px;
            font-weight: 700;
            letter-spacing: -1px;
            margin-bottom: 2px;
        }
        .stat-value.small {
            font-size: 18px;
        }
        .stat-card.rose .stat-value { color: var(--accent-rose); }
        .stat-card.amber .stat-value { color: var(--accent-amber); }
        .stat-card.cyan .stat-value { color: var(--accent-cyan); }
        .stat-card.emerald .stat-value { color: var(--accent-emerald); }
        .stat-card.purple .stat-value { color: var(--accent-purple); }
        .stat-card.gold .stat-value { color: var(--accent-gold); }
        
        .stat-label {
            font-size: 11px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .stat-sub {
            font-size: 10px;
            color: var(--text-muted);
            margin-top: 2px;
        }

        /* ══════════════════ 필터 바 ══════════════════ */
        .filter-bar {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 20px;
            border: 1px solid var(--border);
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
            align-items: flex-end;
        }
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        .filter-group label {
            font-size: 11px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .filter-group select, .filter-group input {
            padding: 10px 14px;
            background: var(--bg-primary);
            border: 1px solid var(--border);
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
            color: var(--text-primary);
            min-width: 140px;
            transition: all 0.2s;
        }
        .filter-group select:focus, .filter-group input:focus {
            outline: none;
            border-color: var(--accent-orange);
            box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.2);
        }
        .filter-btn {
            background: linear-gradient(135deg, var(--accent-orange), #ea580c);
            color: #fff;
            border: none;
            padding: 10px 28px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        .filter-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(249, 115, 22, 0.4);
        }

        /* ══════════════════ 긴급도 탭 ══════════════════ */
        .urgency-tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 16px;
        }
        .urgency-tab {
            padding: 10px 20px;
            border-radius: 10px;
            border: 1px solid var(--border);
            background: var(--bg-card);
            color: var(--text-secondary);
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .urgency-tab:hover {
            border-color: var(--text-muted);
        }
        .urgency-tab.active {
            background: linear-gradient(135deg, var(--accent-orange), #ea580c);
            border-color: transparent;
            color: #fff;
        }
        .urgency-tab .count {
            background: rgba(255,255,255,0.2);
            padding: 2px 8px;
            border-radius: 100px;
            font-size: 11px;
        }
        .urgency-tab.active .count {
            background: rgba(255,255,255,0.3);
        }

        /* ══════════════════ 테이블 ══════════════════ */
        .table-wrap {
            background: var(--bg-card);
            border-radius: 16px;
            border: 1px solid var(--border);
            overflow: hidden;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        .data-table th {
            padding: 14px 12px;
            font-size: 11px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            text-align: left;
            background: var(--bg-secondary);
            border-bottom: 1px solid var(--border);
            position: sticky;
            top: 0;
            white-space: nowrap;
        }
        .data-table th.center { text-align: center; }
        .data-table th.right { text-align: right; }
        .data-table td {
            padding: 12px;
            font-size: 13px;
            border-bottom: 1px solid rgba(255,255,255,0.05);
            vertical-align: middle;
        }
        .data-table tr:hover {
            background: rgba(255,255,255,0.02);
        }
        .data-table tr.urgent-critical {
            background: rgba(244, 63, 94, 0.08);
        }
        .data-table tr.urgent-warning {
            background: rgba(249, 115, 22, 0.05);
        }

        /* 약품 셀 */
        .drug-cell {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }
        .drug-name {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 12px;
        }
        .drug-code {
            font-family: 'JetBrains Mono', monospace;
            font-size: 10px;
            color: var(--text-muted);
        }

        /* 위치 셀 */
        .location-cell { text-align: center; }
        .location-badge {
            display: inline-block;
            background: rgba(251, 191, 36, 0.2);
            color: var(--accent-amber);
            font-size: 11px;
            font-weight: 600;
            padding: 4px 8px;
            border-radius: 6px;
            font-family: 'JetBrains Mono', monospace;
            cursor: pointer;
            transition: all 0.15s;
        }
        .location-badge:hover { background: rgba(251, 191, 36, 0.4); transform: scale(1.05); }
        .location-badge.unset {
            background: rgba(100, 116, 139, 0.2);
            color: var(--text-muted);
            border: 1px dashed var(--border);
        }
        .location-badge.unset:hover { background: rgba(168, 85, 247, 0.2); border-color: var(--accent-purple); color: var(--accent-purple); }

        /* 위치 모달 */
        .location-modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 2000; align-items: center; justify-content: center; backdrop-filter: blur(4px); }
        .location-modal.show { display: flex; }
        .location-modal-content { background: var(--bg-card); border-radius: 16px; padding: 24px; max-width: 400px; width: 90%; border: 1px solid var(--border); box-shadow: 0 20px 60px rgba(0,0,0,0.5); animation: locModalIn 0.2s ease; }
        @keyframes locModalIn { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }
        .location-modal-content h3 { margin: 0 0 16px 0; color: var(--accent-amber); font-size: 18px; display: flex; align-items: center; gap: 8px; }
        .location-product-info { background: var(--bg-secondary); border-radius: 8px; padding: 12px; margin-bottom: 16px; border: 1px solid var(--border); }
        .location-product-info .name { font-weight: 600; color: var(--text-primary); margin-bottom: 4px; }
        .location-product-info .code { font-size: 12px; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; }
        .location-select-wrapper, .location-input-wrapper { margin-bottom: 12px; }
        .location-select-wrapper label, .location-input-wrapper label { display: block; font-size: 12px; font-weight: 500; color: var(--text-secondary); margin-bottom: 6px; }
        .location-select, .location-input { width: 100%; padding: 12px; border: 2px solid var(--border); border-radius: 8px; font-size: 14px; font-family: inherit; background: var(--bg-primary); color: var(--text-primary); transition: border-color 0.2s; }
        .location-select:focus, .location-input:focus { outline: none; border-color: var(--accent-amber); }
        .location-hint { font-size: 11px; color: var(--text-muted); margin-top: 6px; }
        .location-modal-btns { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; }
        .location-modal-btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; font-size: 14px; transition: all 0.15s; }
        .location-modal-btn.secondary { background: var(--bg-secondary); color: var(--text-secondary); }
        .location-modal-btn.secondary:hover { background: var(--bg-card-hover); }
        .location-modal-btn.danger { background: rgba(244, 63, 94, 0.2); color: var(--accent-rose); }
        .location-modal-btn.danger:hover { background: rgba(244, 63, 94, 0.3); }
        .location-modal-btn.primary { background: linear-gradient(135deg, var(--accent-amber), #d97706); color: #fff; }
        .location-modal-btn.primary:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4); }

        /* 긴급도 배지 */
        .urgency-badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 10px;
            font-weight: 600;
        }
        .urgency-badge.critical {
            background: rgba(244, 63, 94, 0.2);
            color: var(--accent-rose);
        }
        .urgency-badge.warning {
            background: rgba(249, 115, 22, 0.2);
            color: var(--accent-orange);
        }
        .urgency-badge.normal {
            background: rgba(100, 116, 139, 0.2);
            color: var(--text-muted);
        }

        /* 상태 배지 */
        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 600;
        }
        .status-badge.pending { background: rgba(249, 115, 22, 0.2); color: var(--accent-orange); }
        .status-badge.reviewed { background: rgba(59, 130, 246, 0.2); color: var(--accent-blue); }
        .status-badge.returned { background: rgba(16, 185, 129, 0.2); color: var(--accent-emerald); }
        .status-badge.keep { background: rgba(168, 85, 247, 0.2); color: var(--accent-purple); }
        .status-badge.disposed { background: rgba(244, 63, 94, 0.2); color: var(--accent-rose); }
        .status-badge.resolved { background: rgba(100, 116, 139, 0.2); color: var(--text-muted); }

        /* 수량/날짜/금액 셀 */
        .qty-cell {
            font-family: 'JetBrains Mono', monospace;
            font-weight: 600;
            text-align: center;
            font-size: 12px;
        }
        .date-cell {
            font-size: 11px;
            color: var(--text-secondary);
        }
        .months-cell {
            font-family: 'JetBrains Mono', monospace;
            font-weight: 700;
            font-size: 12px;
        }
        .months-cell.critical { color: var(--accent-rose); }
        .months-cell.warning { color: var(--accent-orange); }
        .months-cell.normal { color: var(--text-muted); }

        .amount-cell {
            font-family: 'JetBrains Mono', monospace;
            font-weight: 600;
            text-align: right;
            font-size: 12px;
            color: var(--accent-gold);
        }
        .amount-cell.zero {
            color: var(--text-muted);
        }

        /* 액션 버튼 */
        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        .action-btn.primary {
            background: linear-gradient(135deg, var(--accent-orange), #ea580c);
            color: #fff;
        }
        .action-btn.primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(249, 115, 22, 0.4);
        }

        /* ══════════════════ 페이지네이션 ══════════════════ */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            padding: 20px;
        }
        .page-btn {
            padding: 8px 14px;
            border: 1px solid var(--border);
            border-radius: 8px;
            background: var(--bg-secondary);
            color: var(--text-secondary);
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
        .page-btn:hover { border-color: var(--accent-orange); color: var(--accent-orange); }
        .page-btn.active { background: linear-gradient(135deg, var(--accent-orange), #ea580c); border-color: transparent; color: #fff; }
        .page-btn:disabled { opacity: 0.3; cursor: not-allowed; }
        .page-info { color: var(--text-muted); font-size: 13px; }

        /* ══════════════════ 모달 ══════════════════ */
        .modal-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.7);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        .modal-overlay.open { display: flex; }
        .modal {
            background: var(--bg-card);
            border-radius: 20px;
            padding: 28px;
            width: 90%;
            max-width: 500px;
            border: 1px solid var(--border);
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }
        .modal-title { font-size: 18px; font-weight: 700; }
        .modal-close { background: none; border: none; color: var(--text-muted); font-size: 24px; cursor: pointer; }
        .modal-body { margin-bottom: 24px; }
        .form-group { margin-bottom: 16px; }
        .form-group label { display: block; font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 8px; }
        .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            background: var(--bg-primary);
            border: 1px solid var(--border);
            border-radius: 10px;
            font-size: 14px;
            font-family: inherit;
            color: var(--text-primary);
        }
        .form-group textarea { min-height: 100px; resize: vertical; }
        .form-group select:focus, .form-group textarea:focus { outline: none; border-color: var(--accent-orange); }
        .modal-footer { display: flex; justify-content: flex-end; gap: 12px; }
        .modal-btn {
            padding: 12px 24px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        .modal-btn.cancel { background: var(--bg-secondary); border: 1px solid var(--border); color: var(--text-secondary); }
        .modal-btn.submit { background: linear-gradient(135deg, var(--accent-orange), #ea580c); border: none; color: #fff; }
        .modal-btn.submit:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(249, 115, 22, 0.4); }

        .drug-detail {
            background: var(--bg-secondary);
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 20px;
        }
        .drug-detail-name { font-size: 16px; font-weight: 700; margin-bottom: 8px; }
        .drug-detail-info { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size: 13px; }
        .drug-detail-item { display: flex; justify-content: space-between; }
        .drug-detail-label { color: var(--text-muted); }
        .drug-detail-value { font-weight: 600; font-family: 'JetBrains Mono', monospace; }

        /* ══════════════════ 로딩/빈 상태 ══════════════════ */
        .loading-state, .empty-state { text-align: center; padding: 60px 20px; color: var(--text-muted); }
        .loading-spinner {
            width: 40px; height: 40px;
            border: 3px solid var(--border);
            border-top-color: var(--accent-orange);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        .empty-icon { font-size: 48px; margin-bottom: 16px; }

        /* ══════════════════ 토스트 ══════════════════ */
        .toast {
            position: fixed;
            bottom: 32px;
            left: 50%;
            transform: translateX(-50%) translateY(20px);
            padding: 14px 28px;
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            color: var(--text-primary);
            font-size: 14px;
            font-weight: 500;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            opacity: 0;
            transition: all 0.3s;
            z-index: 300;
        }
        .toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
        .toast.success { border-color: var(--accent-emerald); }
        .toast.error { border-color: var(--accent-rose); }

        /* ══════════════════ 반응형 ══════════════════ */
        @media (max-width: 1200px) {
            .stats-row { flex-wrap: wrap; }
            .stat-card { min-width: calc(33% - 12px); }
        }
        @media (max-width: 768px) {
            .stat-card { min-width: calc(50% - 8px); }
            .header-nav { display: none; }
            .filter-bar { flex-direction: column; }
            .filter-group { width: 100%; }
            .filter-group select, .filter-group input { width: 100%; }
            .urgency-tabs { flex-wrap: wrap; }
        }

        /* ══════════════════ 입고이력 모달 ══════════════════ */
        .purchase-modal {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.8);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1100;
            backdrop-filter: blur(4px);
        }
        .purchase-modal.open { display: flex; }
        .purchase-modal-content {
            background: var(--bg-card);
            border-radius: 20px;
            width: 95%;
            max-width: 650px;
            max-height: 80vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            border: 1px solid var(--border);
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
        }
        .purchase-modal-header {
            padding: 20px 24px;
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: #fff;
        }
        .purchase-modal-header h3 {
            margin: 0 0 6px 0;
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .purchase-modal-header .drug-name {
            font-size: 14px;
            opacity: 0.9;
        }
        .purchase-modal-body {
            padding: 16px 24px 24px;
            overflow-y: auto;
            flex: 1;
        }
        .purchase-history-table {
            width: 100%;
            border-collapse: collapse;
        }
        .purchase-history-table th {
            background: var(--bg-secondary);
            padding: 12px 10px;
            font-size: 12px;
            font-weight: 600;
            color: var(--text-secondary);
            text-align: left;
            border-bottom: 2px solid var(--border);
            position: sticky;
            top: 0;
        }
        .purchase-history-table td {
            padding: 14px 10px;
            font-size: 13px;
            border-bottom: 1px solid var(--border);
            color: var(--text-primary);
        }
        .purchase-history-table tr:hover td {
            background: var(--bg-card-hover);
        }
        .supplier-name {
            font-weight: 600;
            color: var(--accent-cyan);
        }
        .supplier-tel {
            font-size: 12px;
            color: var(--accent-blue);
            cursor: pointer;
        }
        .supplier-tel:hover {
            text-decoration: underline;
        }
        .purchase-date {
            color: var(--text-secondary);
            font-family: 'JetBrains Mono', monospace;
            font-size: 12px;
        }
        .purchase-qty {
            font-weight: 600;
            color: var(--accent-emerald);
        }
        .purchase-price {
            color: var(--accent-gold);
            font-family: 'JetBrains Mono', monospace;
        }
        .purchase-empty {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-muted);
        }
        .purchase-empty .icon {
            font-size: 40px;
            margin-bottom: 12px;
        }
        .purchase-modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--border);
            display: flex;
            justify-content: flex-end;
        }
        .purchase-modal-btn {
            padding: 10px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            font-size: 14px;
            background: var(--bg-secondary);
            color: var(--text-secondary);
            transition: all 0.15s;
        }
        .purchase-modal-btn:hover {
            background: var(--bg-card-hover);
            color: var(--text-primary);
        }
        /* 테이블 행 더블클릭 가능 표시 */
        #dataTableBody tr {
            cursor: pointer;
        }
        #dataTableBody tr:active {
            background: var(--bg-card-hover) !important;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-inner">
            <div class="header-left">
                <h1>📦 반품 후보 관리</h1>
                <p>장기 미사용 의약품 반품/폐기 관리</p>
            </div>
            <nav class="header-nav">
                <a href="/admin">📊 대시보드</a>
                <a href="/admin/rx-usage">💊 Rx 사용량</a>
                <a href="/admin/return-management" class="active">📦 반품관리</a>
            </nav>
        </div>
    </div>

    <div class="content">
        <!-- 통계 카드 1줄: 건수 -->
        <div class="stats-row">
            <div class="stat-card rose">
                <div class="stat-icon">🔴</div>
                <div class="stat-value" id="statCritical">-</div>
                <div class="stat-label">3년+ 미사용</div>
                <div class="stat-sub">긴급 처리 필요</div>
            </div>
            <div class="stat-card amber">
                <div class="stat-icon">🟠</div>
                <div class="stat-value" id="statWarning">-</div>
                <div class="stat-label">2년+ 미사용</div>
                <div class="stat-sub">검토 권장</div>
            </div>
            <div class="stat-card cyan">
                <div class="stat-icon">📋</div>
                <div class="stat-value" id="statPending">-</div>
                <div class="stat-label">미결정</div>
                <div class="stat-sub">pending 상태</div>
            </div>
            <div class="stat-card emerald">
                <div class="stat-icon">✅</div>
                <div class="stat-value" id="statProcessed">-</div>
                <div class="stat-label">처리완료</div>
            </div>
            <div class="stat-card purple">
                <div class="stat-icon">📊</div>
                <div class="stat-value" id="statTotal">-</div>
                <div class="stat-label">전체 후보</div>
            </div>
        </div>

        <!-- 통계 카드 2줄: 회수가능 금액 -->
        <div class="stats-row amount-row">
            <div class="stat-card gold">
                <div class="stat-icon">💰</div>
                <div class="stat-value" id="statTotalAmount">-</div>
                <div class="stat-label">총 회수가능 금액</div>
                <div class="stat-sub">전체 반품 대상</div>
            </div>
            <div class="stat-card rose">
                <div class="stat-icon">🔴💵</div>
                <div class="stat-value small" id="statCriticalAmount">-</div>
                <div class="stat-label">3년+ 금액</div>
                <div class="stat-sub">긴급 회수 대상</div>
            </div>
            <div class="stat-card amber">
                <div class="stat-icon">🟠💵</div>
                <div class="stat-value small" id="statWarningAmount">-</div>
                <div class="stat-label">2년+ 금액</div>
                <div class="stat-sub">주의 대상</div>
            </div>
        </div>

        <!-- 필터 바 -->
        <div class="filter-bar">
            <div class="filter-group">
                <label>상태</label>
                <select id="filterStatus">
                    <option value="">전체</option>
                    <option value="pending" selected>미결정 (pending)</option>
                    <option value="reviewed">검토됨</option>
                    <option value="returned">반품완료</option>
                    <option value="keep">보류</option>
                    <option value="disposed">폐기</option>
                    <option value="resolved">재고소진</option>
                </select>
            </div>
            <div class="filter-group">
                <label>긴급도</label>
                <select id="filterUrgency">
                    <option value="">전체</option>
                    <option value="critical">🔴 3년+ (긴급)</option>
                    <option value="warning">🟠 2년+ (주의)</option>
                    <option value="normal">일반</option>
                </select>
            </div>
            <div class="filter-group">
                <label>검색어</label>
                <input type="text" id="searchInput" placeholder="약품명, 코드...">
            </div>
            <div class="filter-group">
                <label>정렬</label>
                <select id="sortSelect">
                    <option value="months_desc">미사용기간 긴 순</option>
                    <option value="months_asc">미사용기간 짧은 순</option>
                    <option value="stock_desc">재고량 많은 순</option>
                    <option value="name_asc">약품명순</option>
                    <option value="detected_desc">감지일 최신순</option>
                </select>
            </div>
            <button class="filter-btn" onclick="loadData()">🔍 조회</button>
        </div>

        <!-- 긴급도 탭 -->
        <div class="urgency-tabs">
            <button class="urgency-tab active" data-urgency="" onclick="setUrgencyTab('')">
                전체 <span class="count" id="tabAll">0</span>
            </button>
            <button class="urgency-tab" data-urgency="critical" onclick="setUrgencyTab('critical')">
                🔴 3년+ <span class="count" id="tabCritical">0</span>
            </button>
            <button class="urgency-tab" data-urgency="warning" onclick="setUrgencyTab('warning')">
                🟠 2년+ <span class="count" id="tabWarning">0</span>
            </button>
            <button class="urgency-tab" data-urgency="normal" onclick="setUrgencyTab('normal')">
                일반 <span class="count" id="tabNormal">0</span>
            </button>
        </div>

        <!-- 데이터 테이블 -->
        <div style="margin-bottom: 8px; font-size: 12px; color: var(--text-muted);">
            💡 행 더블클릭 → 입고이력 확인 (도매상 연락처)
        </div>
        <div class="table-wrap">
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width:4%">긴급</th>
                        <th style="width:20%">약품</th>
                        <th class="center" style="width:5%">위치</th>
                        <th class="center" style="width:5%">현재고</th>
                        <th class="right" style="width:8%">단가</th>
                        <th class="right" style="width:10%">회수가능금액</th>
                        <th class="center" style="width:10%">마지막 처방</th>
                        <th class="center" style="width:8%">미사용</th>
                        <th class="center" style="width:10%">마지막 입고</th>
                        <th class="center" style="width:7%">상태</th>
                        <th style="width:10%">액션</th>
                    </tr>
                </thead>
                <tbody id="dataTableBody">
                    <tr>
                        <td colspan="10">
                            <div class="loading-state">
                                <div class="loading-spinner"></div>
                                <div>데이터 로딩 중...</div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 페이지네이션 -->
        <div class="pagination" id="pagination"></div>
    </div>

    <!-- 상태 변경 모달 -->
    <div class="modal-overlay" id="statusModal">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">📋 상태 변경</h3>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="drug-detail" id="modalDrugDetail"></div>
                
                <div class="form-group">
                    <label>변경할 상태</label>
                    <select id="modalStatus">
                        <option value="reviewed">검토됨</option>
                        <option value="returned">반품완료</option>
                        <option value="keep">보류 (유지)</option>
                        <option value="disposed">폐기</option>
                        <option value="resolved">재고소진</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>결정 사유</label>
                    <textarea id="modalReason" placeholder="상태 변경 사유를 입력하세요... (보류 선택 시 필수)"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn cancel" onclick="closeModal()">취소</button>
                <button class="modal-btn submit" onclick="submitStatusChange()">변경 저장</button>
            </div>
        </div>
    </div>

    <!-- 토스트 -->
    <div class="toast" id="toast"></div>

    <!-- 입고이력 모달 -->
    <div class="purchase-modal" id="purchaseModal">
        <div class="purchase-modal-content">
            <div class="purchase-modal-header">
                <h3>📦 입고 이력</h3>
                <div class="drug-name" id="purchaseDrugName">-</div>
            </div>
            <div class="purchase-modal-body">
                <table class="purchase-history-table">
                    <thead>
                        <tr>
                            <th>도매상</th>
                            <th>입고일</th>
                            <th>수량</th>
                            <th>단가</th>
                        </tr>
                    </thead>
                    <tbody id="purchaseHistoryBody">
                        <tr><td colspan="4" class="purchase-empty"><div class="icon">📭</div><p>로딩 중...</p></td></tr>
                    </tbody>
                </table>
            </div>
            <div class="purchase-modal-footer">
                <button class="purchase-modal-btn" onclick="closePurchaseModal()">닫기</button>
            </div>
        </div>
    </div>

    <!-- 위치 모달 -->
    <div class="location-modal" id="locationModal">
        <div class="location-modal-content">
            <h3>📍 위치 설정</h3>
            <div class="location-product-info">
                <div class="name" id="locModalProductName">제품명</div>
                <div class="code" id="locModalDrugCode">상품코드</div>
            </div>
            <div class="location-select-wrapper">
                <label>기존 위치에서 선택</label>
                <select class="location-select" id="locationSelect" onchange="onLocationSelectChange()">
                    <option value="">-- 선택하세요 --</option>
                </select>
            </div>
            <div class="location-input-wrapper">
                <label>또는 직접 입력</label>
                <input type="text" class="location-input" id="locationInput" placeholder="예: 진열대1-3, 냉장고, 창고A" maxlength="20">
                <div class="location-hint">최대 20자 / 새 위치를 입력하면 목록에 추가됩니다</div>
            </div>
            <div class="location-modal-btns">
                <button class="location-modal-btn danger" onclick="clearLocation()" id="locClearBtn" style="display:none;">삭제</button>
                <div style="flex:1;"></div>
                <button class="location-modal-btn secondary" onclick="closeLocationModal()">취소</button>
                <button class="location-modal-btn primary" onclick="saveLocation()">저장</button>
            </div>
        </div>
    </div>

    <script>
    let allData = [];
    let currentPage = 1;
    const pageSize = 30;
    let currentItemId = null;

    document.addEventListener('DOMContentLoaded', function() {
        loadData();
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') loadData();
        });
    });

    async function loadData() {
        const tbody = document.getElementById('dataTableBody');
        tbody.innerHTML = `<tr><td colspan="10"><div class="loading-state"><div class="loading-spinner"></div><div>데이터 로딩 중...</div></div></td></tr>`;

        const status = document.getElementById('filterStatus').value;
        const urgency = document.getElementById('filterUrgency').value;
        const search = document.getElementById('searchInput').value;
        const sort = document.getElementById('sortSelect').value;

        try {
            let url = '/api/return-candidates?';
            if (status) url += `status=${status}&`;
            if (urgency) url += `urgency=${urgency}&`;
            if (search) url += `search=${encodeURIComponent(search)}&`;
            if (sort) url += `sort=${sort}&`;

            const res = await fetch(url);
            const data = await res.json();

            if (data.success) {
                allData = data.items;
                updateStats(data.stats);
                updateTabs();
                currentPage = 1;
                renderTable();
            } else {
                tbody.innerHTML = `<tr><td colspan="10"><div class="empty-state"><div class="empty-icon">⚠️</div><div>오류: ${data.error}</div></div></td></tr>`;
            }
        } catch (err) {
            tbody.innerHTML = `<tr><td colspan="10"><div class="empty-state"><div class="empty-icon">❌</div><div>데이터 로드 실패</div></div></td></tr>`;
        }
    }

    function updateStats(stats) {
        document.getElementById('statCritical').textContent = stats.critical || 0;
        document.getElementById('statWarning').textContent = stats.warning || 0;
        document.getElementById('statPending').textContent = stats.pending || 0;
        document.getElementById('statProcessed').textContent = stats.processed || 0;
        document.getElementById('statTotal').textContent = stats.total || 0;
        
        // 금액 표시
        document.getElementById('statTotalAmount').textContent = formatAmount(stats.total_amount || 0);
        document.getElementById('statCriticalAmount').textContent = formatAmount(stats.critical_amount || 0);
        document.getElementById('statWarningAmount').textContent = formatAmount(stats.warning_amount || 0);
    }

    function formatAmount(amount) {
        if (!amount || amount === 0) return '₩0';
        if (amount >= 1000000) {
            return '₩' + (amount / 10000).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '만';
        }
        return '₩' + Math.round(amount).toLocaleString();
    }

    function formatPrice(price) {
        if (!price || price === 0) return '-';
        return '₩' + Math.round(price).toLocaleString();
    }

    function updateTabs() {
        const counts = { all: allData.length, critical: 0, warning: 0, normal: 0 };
        allData.forEach(item => {
            const urgency = getUrgencyLevel(item);
            counts[urgency]++;
        });
        
        document.getElementById('tabAll').textContent = counts.all;
        document.getElementById('tabCritical').textContent = counts.critical;
        document.getElementById('tabWarning').textContent = counts.warning;
        document.getElementById('tabNormal').textContent = counts.normal;
    }

    function getUrgencyLevel(item) {
        const months = Math.max(item.months_since_use || 0, item.months_since_purchase || 0);
        if (months >= 36) return 'critical';
        if (months >= 24) return 'warning';
        return 'normal';
    }

    function setUrgencyTab(urgency) {
        document.querySelectorAll('.urgency-tab').forEach(tab => {
            tab.classList.toggle('active', tab.dataset.urgency === urgency);
        });
        document.getElementById('filterUrgency').value = urgency;
        currentPage = 1;
        renderTable();
    }

    function renderTable() {
        const tbody = document.getElementById('dataTableBody');
        const urgencyFilter = document.getElementById('filterUrgency').value;
        
        let filteredData = allData;
        if (urgencyFilter) {
            filteredData = allData.filter(item => getUrgencyLevel(item) === urgencyFilter);
        }

        if (filteredData.length === 0) {
            tbody.innerHTML = `<tr><td colspan="10"><div class="empty-state"><div class="empty-icon">📦</div><div>해당 조건의 반품 후보가 없습니다</div></div></td></tr>`;
            document.getElementById('pagination').innerHTML = '';
            return;
        }

        const totalPages = Math.ceil(filteredData.length / pageSize);
        const start = (currentPage - 1) * pageSize;
        const end = start + pageSize;
        const pageData = filteredData.slice(start, end);

        tbody.innerHTML = pageData.map(item => {
            const urgency = getUrgencyLevel(item);
            const urgencyClass = urgency === 'critical' ? 'urgent-critical' : urgency === 'warning' ? 'urgent-warning' : '';
            const hasAmount = item.recoverable_amount && item.recoverable_amount > 0;
            
            return `
                <tr class="${urgencyClass}" ondblclick="openPurchaseModal('${item.drug_code}', '${escapeHtml(item.drug_name).replace(/'/g, "\\'")}')">
                    <td>
                        <span class="urgency-badge ${urgency}">
                            ${urgency === 'critical' ? '🔴' : urgency === 'warning' ? '🟠' : '⚪'}
                        </span>
                    </td>
                    <td>
                        <div class="drug-cell">
                            <span class="drug-name">${escapeHtml(item.drug_name)}</span>
                            <span class="drug-code">${item.drug_code}</span>
                        </div>
                    </td>
                    <td class="location-cell">
                        ${item.location 
                            ? `<span class="location-badge" onclick="event.stopPropagation();openLocationModal('${item.drug_code}', '${escapeHtml(item.drug_name).replace(/'/g, "\\'")}', '${escapeHtml(item.location).replace(/'/g, "\\'")}')">${escapeHtml(item.location)}</span>` 
                            : `<span class="location-badge unset" onclick="event.stopPropagation();openLocationModal('${item.drug_code}', '${escapeHtml(item.drug_name).replace(/'/g, "\\'")}', '')">미지정</span>`}
                    </td>
                    <td class="qty-cell">${item.current_stock || 0}</td>
                    <td class="amount-cell ${item.unit_price ? '' : 'zero'}">${formatPrice(item.unit_price)}</td>
                    <td class="amount-cell ${hasAmount ? '' : 'zero'}">${hasAmount ? '₩' + Math.round(item.recoverable_amount).toLocaleString() : '-'}</td>
                    <td class="date-cell">${formatDate(item.last_prescription_date) || '-'}</td>
                    <td class="months-cell ${urgency}">
                        ${item.months_since_use ? item.months_since_use + '개월' : '-'}
                    </td>
                    <td class="date-cell">${formatDate(item.last_purchase_date) || '-'}</td>
                    <td><span class="status-badge ${item.status}">${getStatusLabel(item.status)}</span></td>
                    <td>
                        <button class="action-btn primary" onclick="event.stopPropagation();openStatusModal(${item.id})">상태 변경</button>
                    </td>
                </tr>
            `;
        }).join('');

        renderPagination(totalPages, filteredData.length);
    }

    function renderPagination(totalPages, totalItems) {
        const pagination = document.getElementById('pagination');
        
        if (totalPages <= 1) {
            pagination.innerHTML = `<span class="page-info">총 ${totalItems}건</span>`;
            return;
        }

        let html = `<button class="page-btn" onclick="goToPage(1)" ${currentPage === 1 ? 'disabled' : ''}>«</button>`;
        html += `<button class="page-btn" onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>‹</button>`;
        
        const maxVisible = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
        let endPage = Math.min(totalPages, startPage + maxVisible - 1);
        if (endPage - startPage < maxVisible - 1) startPage = Math.max(1, endPage - maxVisible + 1);

        for (let i = startPage; i <= endPage; i++) {
            html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
        }
        
        html += `<button class="page-btn" onclick="goToPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>›</button>`;
        html += `<button class="page-btn" onclick="goToPage(${totalPages})" ${currentPage === totalPages ? 'disabled' : ''}>»</button>`;
        html += `<span class="page-info" style="margin-left:12px;">총 ${totalItems}건</span>`;
        
        pagination.innerHTML = html;
    }

    function goToPage(page) {
        currentPage = page;
        renderTable();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    function openStatusModal(itemId) {
        currentItemId = itemId;
        const item = allData.find(i => i.id === itemId);
        if (!item) return;

        const hasAmount = item.recoverable_amount && item.recoverable_amount > 0;
        document.getElementById('modalDrugDetail').innerHTML = `
            <div class="drug-detail-name">${escapeHtml(item.drug_name)}</div>
            <div class="drug-detail-info">
                <div class="drug-detail-item">
                    <span class="drug-detail-label">약품코드</span>
                    <span class="drug-detail-value">${item.drug_code}</span>
                </div>
                <div class="drug-detail-item">
                    <span class="drug-detail-label">현재고</span>
                    <span class="drug-detail-value">${item.current_stock || 0}</span>
                </div>
                <div class="drug-detail-item">
                    <span class="drug-detail-label">단가</span>
                    <span class="drug-detail-value">${formatPrice(item.unit_price)}</span>
                </div>
                <div class="drug-detail-item">
                    <span class="drug-detail-label">회수가능금액</span>
                    <span class="drug-detail-value" style="color:var(--accent-gold)">${hasAmount ? '₩' + Math.round(item.recoverable_amount).toLocaleString() : '-'}</span>
                </div>
                <div class="drug-detail-item">
                    <span class="drug-detail-label">마지막 처방</span>
                    <span class="drug-detail-value">${formatDate(item.last_prescription_date) || '-'}</span>
                </div>
                <div class="drug-detail-item">
                    <span class="drug-detail-label">미사용 기간</span>
                    <span class="drug-detail-value">${item.months_since_use ? item.months_since_use + '개월' : '-'}</span>
                </div>
            </div>
        `;

        document.getElementById('modalStatus').value = item.status === 'pending' ? 'reviewed' : item.status;
        document.getElementById('modalReason').value = item.decision_reason || '';
        document.getElementById('statusModal').classList.add('open');
    }

    function closeModal() {
        document.getElementById('statusModal').classList.remove('open');
        currentItemId = null;
    }

    async function submitStatusChange() {
        if (!currentItemId) return;

        const status = document.getElementById('modalStatus').value;
        const reason = document.getElementById('modalReason').value;

        if (status === 'keep' && !reason.trim()) {
            showToast('보류 상태에서는 사유 입력이 필수입니다', 'error');
            return;
        }

        try {
            const res = await fetch(`/api/return-candidates/${currentItemId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ status, reason })
            });

            const data = await res.json();
            
            if (data.success) {
                showToast('상태가 변경되었습니다', 'success');
                closeModal();
                loadData();
            } else {
                showToast('변경 실패: ' + data.error, 'error');
            }
        } catch (err) {
            showToast('서버 오류', 'error');
        }
    }

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function formatDate(dateStr) {
        if (!dateStr) return null;
        if (dateStr.length === 8 && !dateStr.includes('-')) {
            return `${dateStr.slice(0,4)}-${dateStr.slice(4,6)}-${dateStr.slice(6,8)}`;
        }
        return dateStr;
    }

    function getStatusLabel(status) {
        const labels = {
            'pending': '미결정',
            'reviewed': '검토됨',
            'returned': '반품완료',
            'keep': '보류',
            'disposed': '폐기',
            'resolved': '재고소진'
        };
        return labels[status] || status;
    }

    function showToast(message, type = '') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = 'toast show ' + type;
        setTimeout(() => { toast.classList.remove('show'); }, 3000);
    }

    // ══════════════════ 입고이력 모달 ══════════════════
    async function openPurchaseModal(drugCode, drugName) {
        const modal = document.getElementById('purchaseModal');
        const nameEl = document.getElementById('purchaseDrugName');
        const tbody = document.getElementById('purchaseHistoryBody');
        
        nameEl.textContent = drugName || drugCode;
        tbody.innerHTML = '<tr><td colspan="4" class="purchase-empty"><div class="icon">⏳</div><p>입고이력 조회 중...</p></td></tr>';
        modal.classList.add('open');
        
        try {
            const res = await fetch(`/api/drugs/${drugCode}/purchase-history`);
            const data = await res.json();
            
            if (data.success) {
                if (data.history.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="4" class="purchase-empty"><div class="icon">📭</div><p>입고 이력이 없습니다</p></td></tr>';
                } else {
                    tbody.innerHTML = data.history.map(h => `
                        <tr>
                            <td>
                                <div class="supplier-name">${escapeHtml(h.supplier)}</div>
                                ${h.supplier_tel ? `<div class="supplier-tel" onclick="event.stopPropagation();copyToClipboard('${h.supplier_tel}')" title="클릭하여 복사">📞 ${h.supplier_tel}</div>` : ''}
                            </td>
                            <td class="purchase-date">${h.date}</td>
                            <td class="purchase-qty">${h.quantity.toLocaleString()}</td>
                            <td class="purchase-price">${h.unit_price ? formatPrice(h.unit_price) : '-'}</td>
                        </tr>
                    `).join('');
                }
            } else {
                tbody.innerHTML = `<tr><td colspan="4" class="purchase-empty"><div class="icon">⚠️</div><p>조회 실패: ${data.error}</p></td></tr>`;
            }
        } catch (err) {
            tbody.innerHTML = `<tr><td colspan="4" class="purchase-empty"><div class="icon">❌</div><p>오류: ${err.message}</p></td></tr>`;
        }
    }
    
    function closePurchaseModal() {
        document.getElementById('purchaseModal').classList.remove('open');
    }
    
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(() => {
            showToast(`📋 ${text} 복사됨`, 'success');
        }).catch(() => {
            const input = document.createElement('input');
            input.value = text;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            showToast(`📋 ${text} 복사됨`, 'success');
        });
    }
    
    // 모달 외부 클릭 시 닫기
    document.getElementById('purchaseModal').addEventListener('click', function(e) {
        if (e.target === this) closePurchaseModal();
    });

    // ══════════════════ 위치 모달 ══════════════════
    let locModalDrugCode = null;
    let locModalCurrentLocation = null;
    let allLocations = [];

    async function openLocationModal(drugCode, productName, currentLocation) {
        locModalDrugCode = drugCode;
        locModalCurrentLocation = currentLocation;
        
        document.getElementById('locModalProductName').textContent = productName;
        document.getElementById('locModalDrugCode').textContent = drugCode;
        document.getElementById('locationInput').value = currentLocation || '';
        
        // 삭제 버튼 표시 (현재 위치가 있을 때만)
        document.getElementById('locClearBtn').style.display = currentLocation ? 'block' : 'none';
        
        // 위치 목록 로드
        try {
            const res = await fetch('/api/locations');
            const data = await res.json();
            if (data.success) {
                allLocations = data.locations || [];
                const select = document.getElementById('locationSelect');
                select.innerHTML = '<option value="">-- 선택하세요 --</option>' +
                    allLocations.map(loc => 
                        `<option value="${escapeHtml(loc)}" ${loc === currentLocation ? 'selected' : ''}>${escapeHtml(loc)}</option>`
                    ).join('');
            }
        } catch (e) {
            console.error('위치 목록 로드 실패:', e);
        }
        
        document.getElementById('locationModal').classList.add('show');
        document.getElementById('locationInput').focus();
    }

    function closeLocationModal() {
        document.getElementById('locationModal').classList.remove('show');
        locModalDrugCode = null;
        locModalCurrentLocation = null;
    }

    function onLocationSelectChange() {
        const selected = document.getElementById('locationSelect').value;
        if (selected) {
            document.getElementById('locationInput').value = selected;
        }
    }

    async function saveLocation() {
        const newLocation = document.getElementById('locationInput').value.trim();
        
        if (!locModalDrugCode) return;
        
        try {
            const res = await fetch(`/api/drugs/${locModalDrugCode}/location`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ location_name: newLocation })
            });
            const data = await res.json();
            
            if (data.success) {
                showToast(newLocation ? `✅ 위치가 "${newLocation}"(으)로 설정되었습니다` : '✅ 위치가 삭제되었습니다', 'success');
                closeLocationModal();
                loadData(); // 테이블 새로고침
            } else {
                showToast(data.error || '저장 실패', 'error');
            }
        } catch (e) {
            showToast('오류: ' + e.message, 'error');
        }
    }

    async function clearLocation() {
        if (!confirm('위치 정보를 삭제하시겠습니까?')) return;
        document.getElementById('locationInput').value = '';
        await saveLocation();
    }

    // 위치 모달 외부 클릭 시 닫기
    document.getElementById('locationModal')?.addEventListener('click', function(e) {
        if (e.target === this) closeLocationModal();
    });
    </script>
</body>
</html>
