<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>{{ share_name }} 파일탐색기</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />

    <style>
        body { background: #f2f5fa; }
        .main-card {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.04);
            max-width: 950px;
            margin: 32px auto 0 auto;
            padding: 28px 32px 24px 32px;
            transition: background-color 0.3s ease;
        }
        .explorer-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 12px;
        }
        .explorer-header h3 {
            margin: 0;
            font-size: 1.25rem;
            color: #375abb;
            font-weight: bold;
        }
        .btn-toolbar-group .btn {
            margin-left: 4px;
            margin-bottom: 4px;
        }
        .breadcrumb {
            margin-bottom: 16px;
            background: #f7fafd;
            border-radius: 8px;
            padding: 6px 14px;
            font-size: 0.98rem;
        }
        .table-box {
            background: #fafbfc;
            border-radius: 10px;
            box-shadow: 0 1px 6px rgba(0,0,0,0.02);
            padding: 10px 10px 2px 10px;
        }
        .table thead th {
            background: #f5f8fc;
            color: #466cb1;
            font-size: 0.97rem;
            border-bottom: 2px solid #e6e9f0;
            font-weight: 600;
            cursor: pointer;
            user-select: none;
        }
        .table thead th.noclick {
            cursor: default;
        }
        .table tbody tr:hover {
            background-color: #e9f3ff;
            transition: background 0.14s;
        }
        .icon-folder { color: #4078c1; }
        .icon-file { color: #9098a2; }
        .icon-zip { color: #dcb200; }
        .custom-check { margin-top: 0.18em; }
        .file-link {
            color: #222;
            text-decoration: none;
        }
        .file-link:hover {
            text-decoration: underline;
            color: #0d6efd;
        }
        .form-inline-sm input[type="text"] {
            width: 120px;
            margin-right: 4px;
        }
        @media (max-width: 900px) {
            .main-card {
                padding: 14px 4vw 16px 4vw;
            }
        }
        @media (max-width: 600px) {
            .main-card {
                padding: 4vw 2vw;
            }
            .explorer-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }
            .btn-toolbar-group {
                width: 100%;
            }
            .btn-toolbar-group .btn {
                width: 100%;
                margin: 3px 0;
            }
        }
        .sort-indicator {
            margin-left: 4px;
            color: #3496ff;
            font-size: 0.92em;
        }
        /* 업로드 진행률 바 */
        #upload-progress {
            width: 150px;
            height: 8px;
            background: #eee;
            border-radius: 4px;
            overflow: hidden;
            margin-left: 10px;
            display: none;
        }
        #upload-bar {
            height: 100%;
            background: #007bff;
            width: 0;
            transition: width 0.2s ease;
        }
    </style>
</head>
<body>
<div class="main-card" id="main-card" 
     ondragover="event.preventDefault(); this.style.backgroundColor='#e0e7ff';" 
     ondragleave="event.preventDefault(); this.style.backgroundColor='#fff';" 
     ondrop="event.preventDefault(); this.style.backgroundColor='#fff'; handleDrop(event);">
     
     <div class="explorer-header">
        <h3><i class="fa-solid fa-folder-open icon-folder"></i> {{ share_name }}/RealNAS</h3>
        <div class="btn-toolbar-group d-flex flex-wrap align-items-center gap-2">
            <form
                method="post"
                enctype="multipart/form-data"
                id="tool-form"
                class="d-flex flex-wrap align-items-center gap-2"
                style="margin:0;"
            >
<input
    type="file"
    id="upload-file"
    name="file"
    class="form-control form-control-sm"
    style="width:150px; min-width:100px;"
    multiple
/>
<button
    type="button"
    id="upload-btn"
    class="btn btn-primary btn-sm"
    title="파일 업로드"
>
    <i class="fa-solid fa-upload"></i> 업로드
</button>

<div id="upload-progress" style="display:none; margin-top:5px; width:150px; border:1px solid #ccc; height:20px; position:relative;">
    <div id="upload-bar" style="width:0%; height:100%; background:#007bff;"></div>
    <span id="upload-time-left" style="position:absolute; right:5px; top:0; line-height:20px; font-size:12px; color:#000;">0초 남음</span>
</div>


                <input
                    type="text"
                    name="foldername"
                    class="form-control form-control-sm"
                    placeholder="새 폴더명"
                />
                <button
                    class="btn btn-success btn-sm"
                    type="submit"
                    name="mkdir"
                    value="1"
                >
                    <i class="fa-solid fa-folder-plus"></i> 폴더생성
                </button>

                <button
                    class="btn btn-danger btn-sm"
                    type="submit"
                    name="delete"
                    value="1"
                    onclick="return confirm('정말 삭제더할까요?')"
                >
                    <i class="fa-solid fa-trash"></i> 삭제
                </button>

                <input
                    type="text"
                    name="zipname"
                    class="form-control form-control-sm"
                    value=""
                    style="width:110px;"
                />
                <button
                    class="btn btn-warning btn-sm"
                    type="submit"
                    name="zip"
                    value="1"
                >
                    <i class="fa-solid fa-file-zipper"></i> 압축
                </button>
                <button
                    class="btn btn-info btn-sm"
                    type="submit"
                    name="unzip"
                    value="1"
                >
                    <i class="fa-solid fa-file-zipper"></i> 압축풀기
                </button>
                <button
                    class="btn btn-secondary btn-sm"
                    type="submit"
                    name="download"
                    value="1"
                >
                    <i class="fa-solid fa-download"></i> 다운로드
                </button>

                <!-- 복사/붙여넣기 버튼 -->
                <button
                    type="button"
                    id="copy-btn"
                    class="btn btn-outline-primary btn-sm"
                    title="복사"
                >
                    <i class="fa-regular fa-copy"></i> 복사
                </button>
                <button
                    type="button"
                    id="paste-btn"
                    class="btn btn-outline-success btn-sm"
                    title="붙여넣기"
                >
                    <i class="fa-solid fa-paste"></i> 붙여넣기
                </button>
                <button
    type="button"
    id="rename-btn"
    class="btn btn-outline-secondary btn-sm"
    title="이름 변경"
>
    <i class="fa-solid fa-pen-to-square"></i> 이름변경
</button>

                <!-- 선택된 파일/폴더 이름 전송용 -->
                <input
                    type="hidden"
                    id="selected_items"
                    name="selected_items"
                    value=""
                />
            </form>
        </div>
<div style="display: flex; flex-direction: column; align-items: flex-end; gap: 4px;">
  <span style="
    font-weight: 600; 
    color: #000; 
    background-color: #f0f0f0; 
    padding: 4px 8px; 
    border-radius: 6px; 
    box-shadow: 0 0 4px rgba(0,0,0,0.1);
    ">
    아이디: <strong>{{ session.get('username') }}</strong>
  </span>
  <a href="{{ url_for('logout') }}" class="btn btn-danger btn-sm" style="min-width: 100px;">
    <i class="fa-solid fa-right-from-bracket"></i> 로그아웃
  </a>
</div>


    </div>

<!-- 공유폴더 목록 화면 -->
{% if share_name == '공유폴더 목록' %}
  <!-- 공유폴더 목록 전용 UI : 간단 리스트 형태 -->
  <div style="padding: 16px; background-color: #e9f7fe; border-radius: 8px; margin-bottom: 20px;">
    <strong>접근 가능한 공유폴더 목록입니다.</strong><br>
    원하는 공유폴더명을 클릭해 내부 파일 탐색을 시작하세요.
  </div>
  <div style="padding-left: 10px;">
  {% for folder in folders %}
    <div style="margin-bottom: 8px;">
      <a href="{{ url_for('share_browse', share_name=folder.name) }}" style="font-size: 1.1rem; color: #0d6efd;">
        <i class="fa-solid fa-folder icon-folder"></i> {{ folder.name }}
      </a>
    </div>
  {% endfor %}
  </div>
{% else %}

{% if disk_usage %}
<div class="disk-usage" style="margin-bottom:15px; font-weight:600; color:#1976d2;">
    디스크 여유 공간: {{ "%.2f"|format(disk_usage.free_gb) }} GB / 총 {{ "%.2f"|format(disk_usage.total_gb) }} GB ({{ "%.1f"|format(disk_usage.percent_used) }}%)
</div>
{% endif %}

{% set parts = [] %}
{% if path %}
  {% set parts = path.split('/') %}
{% endif %}

<ol class="breadcrumb mb-2 py-2 px-2">
  <li class="breadcrumb-item">
      <a href="{{ url_for('share_browse', share_name='공유폴더 목록', path='') }}">홈</a>
  </li>

  {% set acc = [share_name] %}
  <li class="breadcrumb-item">
    <a href="{{ url_for('share_browse', share_name=share_name, path=share_name) }}">{{ share_name }}</a>
  </li>

  {% for part in parts %}
    {% if part and part != share_name %}
      {% set _ = acc.append(part) %}
      <li class="breadcrumb-item">
        <a href="{{ url_for('share_browse', share_name=share_name, path='/'.join(acc[1:])) }}">{{ part }}</a>
      </li>
    {% endif %}
  {% endfor %}
</ol>





{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for cat, msg in messages %}
<div class="alert alert-{{ cat if cat != 'message' else 'info' }} py-2">
    {{ msg }}
</div>
{% endfor %}
{% endif %}
{% endwith %}

<div class="table-box">
    <table class="table table-sm table-hover mb-2" id="explorer-table">
        <thead>
            <tr>
                <th class="noclick" style="width: 26px;">
                    <input
                        type="checkbox"
                        id="chk_all"
                        class="custom-check"
                        title="전체선택"
                    />
                </th>
                <th id="sort-name">
                    이름
                    <span class="sort-indicator" id="sort-name-indicator"></span>
                </th>
                <th id="sort-kind">
                    종류
                    <span class="sort-indicator" id="sort-kind-indicator"></span>
                </th>
                <th id="sort-size" style="width: 80px;">
                    크기
                    <span class="sort-indicator" id="sort-size-indicator"></span>
                </th>
                <th id="sort-mtime" style="width: 140px;">
                    수정일
                    <span class="sort-indicator" id="sort-mtime-indicator"></span>
                </th>
            </tr>
        </thead>
        <tbody>
            {% for folder in folders %}
            <tr
                class="folder-row"
                data-kind="폴더"
                data-name="{{ folder.name }}"
                data-mtime="{{ folder.mtime or '' }}"
                data-size="0"
            >
                <td>
                    <input
                        type="checkbox"
                        name="selected"
                        value="{{ folder.name }}"
                        class="custom-check"
                    />
                </td>
                <td>
                    <i class="fa-solid fa-folder icon-folder"></i>
                    <a
                        class="file-link"
                        href="{{ url_for('share_browse', share_name=share_name, path=(path ~ '/' ~ folder.name if path else folder.name)) }}"
                    >
                        {{ folder.name }}
                    </a>
                </td>
                <td>폴더</td>
                <td>-</td>
                <td>{{ folder.mtime or '-' }}</td>
            </tr>
            {% endfor %}
            {% for file in files %}
            <tr
                class="file-row"
                data-kind="{{ file.ext|default('파일') }}"
                data-name="{{ file.name }}"
                data-mtime="{{ file.mtime or '' }}"
                data-size="{{ file.size or 0 }}"
            >
                <td>
                    <input
                        type="checkbox"
                        name="selected"
                        value="{{ file.name }}"
                        class="custom-check"
                    />
                </td>
                <td>
                    {% if file.name.endswith('.zip') %}
                    <i class="fa-solid fa-file-zipper icon-zip"></i>
                    {% else %}
                    <i class="fa-solid fa-file icon-file"></i>
                    {% endif %}
                    <a
                        class="file-link"
                        href="{{ url_for('file_download', share=share_name, path=(path ~ '/' ~ file.name if path else file.name)) }}"
                    >
                        {{ file.name }}
                    </a>
                </td>
                <td>{{ file.ext|default('파일') }}</td>
                <td>{{ (file.size // 1024) or 1 }} KB</td>
                <td>{{ file.mtime or '-' }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div class="mt-2 mb-1 text-secondary small">
    <i class="fa-regular fa-circle-check"></i> 체크박스: 전체/개별/폴더/파일 &nbsp;|&nbsp; 폴더 클릭: 진입 &nbsp;|&nbsp; 파일 클릭: 다운로드
</div>
{% endif %}
</div>
<script>
    // 전체선택 체크박스
    document.getElementById('chk_all').addEventListener('change', function () {
        let boxes = document.querySelectorAll('.custom-check[name="selected"]');
        boxes.forEach((box) => (box.checked = this.checked));
    });

    // 폼 제출 시 선택된 항목 hidden input에 넣기
    document.getElementById('tool-form').addEventListener('submit', function (event) {
        if (event.submitter && ['delete', 'zip', 'unzip', 'download'].includes(event.submitter.name)) {
            let selected = [];
            document.querySelectorAll('.custom-check[name="selected"]:checked').forEach((cb) => {
                selected.push(cb.value);
            });
            if (selected.length === 0) {
                alert('항목을 선택하세요.');
                event.preventDefault();
                return false;
            }
            document.getElementById('selected_items').value = selected.join(',');
        }
    });

    // 테이블 정렬 함수
    function tableSort(col, type) {
        let table = document.getElementById('explorer-table').getElementsByTagName('tbody')[0];
        let rows = Array.from(table.rows);
        let ascKey = 'sort_' + col + '_asc';
        if (!window[ascKey]) window[ascKey] = true;
        let asc = window[ascKey];

        rows.sort(function (a, b) {
            let va = a.getAttribute('data-' + col) || '';
            let vb = b.getAttribute('data-' + col) || '';
            if (type === 'num') {
                va = parseInt(va) || 0;
                vb = parseInt(vb) || 0;
            } else if (type === 'date') {
                va = va.replace(/[- :]/g, '');
                vb = vb.replace(/[- :]/g, '');
            } else {
                va = va.toLowerCase();
                vb = vb.toLowerCase();
            }
            if (a.getAttribute('data-kind') === '폴더' && b.getAttribute('data-kind') !== '폴더')
                return -1 * (asc ? 1 : -1);
            if (a.getAttribute('data-kind') !== '폴더' && b.getAttribute('data-kind') === '폴더')
                return 1 * (asc ? 1 : -1);
            if (va < vb) return asc ? -1 : 1;
            if (va > vb) return asc ? 1 : -1;
            return 0;
        });
        rows.forEach((r) => table.appendChild(r));
        window[ascKey] = !asc;

        ['name', 'kind', 'size', 'mtime'].forEach(function (field) {
            let elem = document.getElementById('sort-' + field + '-indicator');
            if (elem) elem.textContent = '';
        });
        let cur = document.getElementById('sort-' + col + '-indicator');
        if (cur) cur.textContent = asc ? '▲' : '▼';
    }

    ['name', 'kind', 'size', 'mtime'].forEach(field => {
        document.getElementById('sort-' + field).addEventListener('click', function () {
            let type = 'str';
            if (field === 'size') type = 'num';
            else if (field === 'mtime') type = 'date';
            tableSort(field, type);
        });
    });

    // 업로드 관련 요소
const uploadBtn = document.getElementById('upload-btn');
const uploadFile = document.getElementById('upload-file');
const uploadProgress = document.getElementById('upload-progress');
const uploadBar = document.getElementById('upload-bar');
const uploadTimeLeft = document.getElementById('upload-time-left');
uploadBtn.addEventListener('click', () => {
    if (!uploadFile.files.length) {
        alert('파일을 선택하세요.');
        return;
    }

    const formData = new FormData();

    for (let i = 0; i < uploadFile.files.length; i++) {
        formData.append('file', uploadFile.files[i]);
    }

    formData.append('upload', '1');

    const xhr = new XMLHttpRequest();
    xhr.open('POST', window.location.href);

    let startTime = Date.now();

    xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            let percent = (e.loaded / e.total) * 100;
            uploadBar.style.width = percent + '%';
            uploadProgress.style.display = 'block';

            let elapsedTime = (Date.now() - startTime) / 1000;
            if (elapsedTime < 0.1) elapsedTime = 0.1;

            let uploadSpeed = e.loaded / elapsedTime;
            let remainingBytes = e.total - e.loaded;
            let remainingTimeSec = remainingBytes / uploadSpeed;

            uploadTimeLeft.textContent = formatTime(remainingTimeSec);
        }
    };

    xhr.onload = function () {
        if (xhr.status === 200 || xhr.status === 302) {
            location.reload();
        } else {
            alert('업로드 실패');
        }
        uploadBar.style.width = '0%';
        uploadProgress.style.display = 'none';
        uploadTimeLeft.textContent = '';
    };

    xhr.onerror = function () {
        alert('업로드 중 오류 발생');
        uploadBar.style.width = '0%';
        uploadProgress.style.display = 'none';
        uploadTimeLeft.textContent = '';
    };

    xhr.send(formData);
});

function formatTime(seconds) {
    if (seconds < 0) seconds = 0;
    if (seconds < 60) {
        return `${Math.round(seconds)}초 남음`;
    } else {
        const min = Math.floor(seconds / 60);
        const sec = Math.round(seconds % 60);
        return `${min}분 ${sec}초 남음`;
    }
}


    // 복사 버튼 - localStorage에 share_name, path, items 저장
    document.getElementById('copy-btn').addEventListener('click', () => {
        let clipboard = {
            share_name: '{{ share_name }}',
            path: '{{ path|default("") }}',
            items: []
        };
        const checkedBoxes = document.querySelectorAll('.custom-check[name="selected"]:checked');
        checkedBoxes.forEach(cb => {
            clipboard.items.push(cb.value);
        });
        if (clipboard.items.length === 0) {
            alert('복사할 항목을 선택하세요.');
            return;
        }
        localStorage.setItem('file_explorer_clipboard', JSON.stringify(clipboard));
        alert(`${clipboard.items.length}개 항목이 복사되었습니다.`);
    });

    // 붙여넣기 버튼 - localStorage에서 읽고 서버에 POST (복사원본/대상 공유폴더 포함)
    document.getElementById('paste-btn').addEventListener('click', () => {
        const clipboardStr = localStorage.getItem('file_explorer_clipboard');
        if (!clipboardStr) {
            alert('복사된 항목이 없습니다.');
            return;
        }
        let clipboard;유
        try {
            clipboard = JSON.parse(clipboardStr);
        } catch {
            alert('복사된 항목 데이터가 손상되었습니다.');
            localStorage.removeItem('file_explorer_clipboard');
            return;
        }
        if (!clipboard.items || clipboard.items.length === 0) {
            alert('복사된 항목이 없습니다.');
            return;
        }
        if (!confirm('선택한 항목을 현재 경로에 붙여넣기 하시겠습니까?')) return;

        fetch(window.location.href, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                paste: true,
                items: clipboard.items,
                source_share: clipboard.share_name,
                source_path: clipboard.path,
                target_share: '{{ share_name }}',
                target_path: '{{ path|default("") }}'
            })
        })
        .then(resp => resp.json())
        .then(data => {
            if (data.success) {
                alert('붙여넣기 완료');
                localStorage.removeItem('file_explorer_clipboard');
                location.reload();
            } else {
                alert('붙여넣기 실패: ' + (data.message || '알 수 없는 오류'));
            }
        })
        .catch(() => alert('서버 통신 오류'));
    });

    // 드래그앤드롭 업로드 함수
function handleDrop(e) {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (!files.length) {
        alert('업로드할 파일을 드래그하세요.');
        return;
    }

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        formData.append('file', files[i]);
    }
    formData.append('upload', '1');

    const xhr = new XMLHttpRequest();
    xhr.open('POST', window.location.href);

    uploadProgress.style.display = 'block';

    let startTime = Date.now();

    xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            let percent = (e.loaded / e.total) * 100;
            uploadBar.style.width = percent + '%';

            let elapsedTime = (Date.now() - startTime) / 1000;
            if (elapsedTime < 0.1) elapsedTime = 0.1; // 0으로 나누기 방지

            let uploadSpeed = e.loaded / elapsedTime;
            let remainingBytes = e.total - e.loaded;
            let remainingTimeSec = remainingBytes / uploadSpeed;

            uploadTimeLeft.textContent = formatTime(remainingTimeSec);
        }
    };

    xhr.onload = function () {
        if (xhr.status === 200 || xhr.status === 302) {
            location.reload();
        } else {
            alert('업로드 실패');
        }
        uploadBar.style.width = '0%';
        uploadProgress.style.display = 'none';
        uploadTimeLeft.textContent = '';
    };

    xhr.onerror = function () {
        alert('업로드 중 오류 발생');
        uploadBar.style.width = '0%';
        uploadProgress.style.display = 'none';
        uploadTimeLeft.textContent = '';
    };

    xhr.send(formData);
}

function formatTime(seconds) {
    if (seconds < 0) seconds = 0;
    if (seconds < 60) {
        return `${Math.round(seconds)}초 남음`;
    } else {
        const min = Math.floor(seconds / 60);
        const sec = Math.round(seconds % 60);
        return `${min}분 ${sec}초 남음`;
    }
}



    const renameBtn = document.getElementById('rename-btn');

renameBtn.addEventListener('click', () => {
    const checkedBoxes = document.querySelectorAll('.custom-check[name="selected"]:checked');
    if (checkedBoxes.length === 0) {
        alert('이름을 변경할 항목을 선택하세요.');
        return;
    }
    if (checkedBoxes.length > 1) {
        alert('이름 변경은 한 번에 한 항목만 가능합니다.');
        return;
    }

    // 편집 대상 체크박스의 행 찾기
    const checkbox = checkedBoxes[0];
    const row = checkbox.closest('tr');
    const nameCell = row.querySelector('td:nth-child(2)'); // 이름 있는 셀

    // 이미 편집 중인지 확인
    if (nameCell.querySelector('input.name-edit')) {
        alert('이미 편집 중입니다.');
        return;
    }

    const currentName = nameCell.textContent.trim();

    // 기존 이름 텍스트 숨기기
    nameCell.dataset.oldName = currentName;
    nameCell.innerHTML = '';

    // input 생성
    const input = document.createElement('input');
    input.type = 'text';
    input.value = currentName;
    input.className = 'form-control form-control-sm name-edit';
    input.style.maxWidth = '200px';
    nameCell.appendChild(input);

    // 버튼 생성: 저장, 취소
    const saveBtn = document.createElement('button');
    saveBtn.textContent = '저장';
    saveBtn.className = 'btn btn-success btn-sm ms-2';
    nameCell.appendChild(saveBtn);

    const cancelBtn = document.createElement('button');
    cancelBtn.textContent = '취소';
    cancelBtn.className = 'btn btn-secondary btn-sm ms-1';
    nameCell.appendChild(cancelBtn);

    // 저장 클릭 이벤트
    saveBtn.addEventListener('click', () => {
        const newName = input.value.trim();
        if (!newName) {
            alert('새 이름을 입력하세요.');
            return;
        }
        if (newName === currentName) {
            alert('이름이 변경되지 않았습니다.');
            return;
        }

        // 폼 만들어서 POST 전송
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';

        const oldInput = document.createElement('input');
        oldInput.name = 'old_name';
        oldInput.value = currentName;
        form.appendChild(oldInput);

        const newInput = document.createElement('input');
        newInput.name = 'new_name';
        newInput.value = newName;
        form.appendChild(newInput);

        const renameInput = document.createElement('input');
        renameInput.name = 'rename';
        renameInput.value = '1';
        form.appendChild(renameInput);

        document.body.appendChild(form);
        form.submit();
    });

    // 취소 클릭 이벤트
    cancelBtn.addEventListener('click', () => {
        nameCell.innerHTML = currentName;
    });
});
 // 체크박스 선택 시 zipname input 자동 변경
  const zipnameInput = document.querySelector('input[name="zipname"]');
  const selectedCheckboxes = document.querySelectorAll('.custom-check[name="selected"]');

  selectedCheckboxes.forEach(cb => {
    cb.addEventListener('change', () => {
      const checked = Array.from(selectedCheckboxes).filter(c => c.checked);
      if (checked.length === 1) {
        let name = checked[0].value;
        // 폴더면 그대로 이름, 파일이면 확장자 제거
        if (name.includes('.')) {
          name = name.substring(0, name.lastIndexOf('.'));
        }
        zipnameInput.value = name + '.zip';
      } else if (checked.length > 1) {
        zipnameInput.value = 'archive.zip';
      } else {
        zipnameInput.value = '';
      }
    });
  });
</script>
</body>
</html>
