{% extends "base.html" %}

{% block content %}
<div class="container-fluid py-4">



  {# 헤더 섹션 #}
  <div class="row mb-4">
    <div class="col">
      <h2 class="fw-bold mb-1">
        <i class="bi bi-server text-primary me-2"></i>
        서버 관리 대시보드
      </h2>
      <p class="text-muted mb-0">IP 처리 및 파일 관리를 위한 통합 관리 도구</p>
    </div>
  </div>

  {# 메인 작업 영역 #}
  <div class="row g-4 mb-4">
    {# IP 처리 카드 #}
    <div class="col-lg-6">
      <div class="card border shadow-sm h-100">
        <div class="card-header bg-light border-0 py-2">
          <h6 class="mb-0">
            <i class="bi bi-hdd-network me-2"></i>
            IP 처리
          </h6>
        </div>
        <div class="card-body p-4 h-100 d-flex flex-column">
          <form id="ipForm" method="post" action="{{ url_for('main.process_ips') }}" class="h-100 d-flex flex-column">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

            {# 작업 유형 선택 #}
            <div class="mb-3">
              <label for="job_type" class="form-label d-flex justify-content-between">
                <span>작업 유형</span>
                <a href="{{ url_for('script_manager.index') }}" class="text-decoration-none small">
                  <i class="bi bi-gear-fill me-1"></i>프로파일 관리
                </a>
              </label>
              <select id="job_type" name="job_type" class="form-select" required>
                <option value="" disabled selected>작업을 선택하세요</option>
                <option value="mac">MAC 주소 수집</option>
                <option value="server_info">서버 정보 수집</option>
                <option value="guid">GUID 수집</option>
                <option value="gpu">GPU 시리얼 수집</option>
                <option value="legacy">기존 스크립트 사용 (Legacy)</option>
              </select>
            </div>

            {# 프로파일 선택 (동적) #}
            <div class="mb-3" id="profileGroup" style="display:none;">
              <label for="profile" class="form-label">프로파일 선택</label>
              <select id="profile" name="profile" class="form-select">
                <option value="">프로파일을 선택하세요</option>
              </select>
              <div class="form-text small" id="profileDesc"></div>
            </div>

            {# 기존 스크립트 선택 (Legacy) #}
            <div class="mb-3" id="legacyScriptGroup" style="display:none;">
              <label for="script" class="form-label">스크립트 선택</label>
              <select id="script" name="script" class="form-select" autocomplete="off">
                <option value="">스크립트를 선택하세요</option>
                {% if grouped_scripts %}
                {% for category, s_list in grouped_scripts.items() %}
                <optgroup label="{{ category }}">
                  {% for script in s_list %}
                  <option value="{{ script }}">{{ script }}</option>
                  {% endfor %}
                </optgroup>
                {% endfor %}
                {% else %}
                {# 만약 grouped_scripts가 없는 경우(하위 호환) #}
                {% for script in scripts %}
                <option value="{{ script }}">{{ script }}</option>
                {% endfor %}
                {% endif %}
              </select>
            </div>

            {# XML 파일 선택 (조건부) #}
            <div class="mb-3" id="xmlFileGroup" style="display:none;">
              <select id="xmlFile" name="xmlFile" class="form-select">
                <option value="">XML 파일 선택</option>
                {% for xml_file in xml_files %}
                <option value="{{ xml_file }}">{{ xml_file }}</option>
                {% endfor %}
              </select>
            </div>

            {# IP 주소 입력 #}
            <div class="mb-3 flex-grow-1 d-flex flex-column">
              <label for="ips" class="form-label w-100 d-flex justify-content-between align-items-end mb-2">
                <span class="mb-1">
                  IP 주소
                  <span class="badge bg-secondary ms-1" id="ipLineCount">0</span>
                </span>
                <div class="d-flex align-items-center gap-1">
                  <button type="button" class="btn btn-sm btn-outline-secondary px-2 py-1" id="btnClearIps"
                    title="입력 내용 지우기" style="font-size: 0.75rem;">
                    <i class="bi bi-trash me-1"></i>지우기
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-primary px-2 py-1" id="btnStartScan"
                    title="10.10.0.1 ~ 255 자동 스캔" style="font-size: 0.75rem;">
                    <i class="bi bi-search me-1"></i>IP 스캔
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-secondary px-2 py-1" id="btnCopyIps"
                    title="IP 목록 복사" style="font-size: 0.75rem;" disabled>
                    <i class="bi bi-clipboard me-1"></i>복사
                  </button>
                </div>
              </label>
              <textarea id="ips" name="ips" class="form-control font-monospace flex-grow-1"
                placeholder="iDRAC IP 정보를 입력하세요&#10;10.10.0.2&#10;10.10.0.3" required style="resize: none;"></textarea>
            </div>

            <div class="mt-auto">
              <button type="submit"
                class="btn btn-white bg-white border shadow-sm w-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move">
                <div class="rounded-circle bg-primary bg-opacity-10 text-primary p-1">
                  <i class="bi bi-play-circle-fill fs-6"></i>
                </div>
                <span class="fw-medium text-dark" style="font-size: 0.75rem;">처리 시작</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    {# 공유 작업 카드 #}
    <div class="col-lg-6">
      <div class="card border shadow-sm h-100">
        <div class="card-header bg-light border-0 py-2">
          <h6 class="mb-0">
            <i class="bi bi-share me-2"></i>
            공유 작업
          </h6>
        </div>
        <div class="card-body p-4">
          <form id="sharedForm" method="post">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

            <div class="mb-3">
              <label for="server_list_content" class="form-label">
                서버 리스트 (덮어쓰기)
                <span class="badge bg-secondary ms-2" id="serverLineCount">0 대설정</span>
              </label>
              <textarea id="server_list_content" name="server_list_content" rows="8" class="form-control font-monospace"
                style="font-size: 0.95rem;" placeholder="서버 리스트를 입력하세요..."></textarea>
            </div>

            <div class="row g-2">
              <div class="col-4">
                <button type="submit" formaction="{{ url_for('utils.update_server_list') }}"
                  class="btn btn-white bg-white border shadow-sm w-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move h-100">
                  <div class="rounded-circle bg-primary bg-opacity-10 text-primary p-1">
                    <i class="bi bi-file-earmark-spreadsheet fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.75rem;">MAC to Excel</span>
                </button>
              </div>
              <div class="col-4">
                <button type="button" data-bs-toggle="modal" data-bs-target="#slotPriorityModal"
                  class="btn btn-white bg-white border shadow-sm w-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move h-100">
                  <div class="rounded-circle bg-success bg-opacity-10 text-success p-1">
                    <i class="bi bi-file-earmark-excel fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.75rem;">GUID to Excel</span>
                </button>
              </div>
              <div class="col-4">
                <button type="submit" formaction="{{ url_for('utils.update_gpu_list') }}"
                  class="btn btn-white bg-white border shadow-sm w-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move h-100">
                  <div class="rounded-circle bg-danger bg-opacity-10 text-danger p-1">
                    <i class="bi bi-gpu-card fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.75rem;">GPU to Excel</span>
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  {# 시스템 제어 패널 #}
  <div class="row mb-4">
    <div class="col">
      <div class="card border shadow-sm">
        <div class="card-header bg-light border-0 py-2 d-flex justify-content-between align-items-center">
          <h6 class="mb-0">
            <i class="bi bi-terminal me-2"></i>
            시스템 제어 (System Control)
            <small class="text-muted ms-2 fw-normal">- 위 "IP 주소" 입력란의 대상을 제어합니다.</small>
          </h6>
          <div class="d-flex align-items-center gap-2">
            <small id="systemControlHint" class="text-primary fw-bold"
              style="font-size: 0.75rem; cursor: pointer;">(클릭하여 열기)</small>
            <button class="btn btn-sm btn-link text-secondary p-0 text-decoration-none" type="button"
              data-bs-toggle="collapse" data-bs-target="#systemControlPanel" aria-expanded="false"
              aria-controls="systemControlPanel">
              <i class="bi bi-chevron-down"></i>
            </button>
          </div>
        </div>
        <div id="systemControlPanel" class="collapse">
          <div class="card-body p-4">
            <div class="row g-2">
              <!-- Power ON -->
              <div class="col-md-2">
                <button
                  class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                  onclick="runControl('power_on')">
                  <div class="rounded-circle bg-success bg-opacity-10 text-success p-1">
                    <i class="bi bi-power fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.7rem;">Power ON</span>
                </button>
              </div>
              <!-- Power OFF -->
              <div class="col-md-2">
                <button
                  class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                  onclick="runControl('power_off')">
                  <div class="rounded-circle bg-danger bg-opacity-10 text-danger p-1">
                    <i class="bi bi-person-x fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.7rem;">Power OFF</span>
                </button>
              </div>
              <!-- Log Clear -->
              <div class="col-md-2">
                <button
                  class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                  onclick="runControl('log_clear')">
                  <div class="rounded-circle bg-warning bg-opacity-10 text-warning p-1">
                    <i class="bi bi-eraser fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.7rem;">Log Clear</span>
                </button>
              </div>
              <!-- Job Delete -->
              <div class="col-md-2">
                <button
                  class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                  onclick="runControl('job_delete')">
                  <div class="rounded-circle bg-secondary bg-opacity-10 text-secondary p-1">
                    <i class="bi bi-trash fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.7rem;">Job Delete</span>
                </button>
              </div>
              <!-- TSR Collect -->
              <div class="col-md-2">
                <button
                  class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                  onclick="runControl('tsr_collect')">
                  <div class="rounded-circle bg-info bg-opacity-10 text-info p-1">
                    <i class="bi bi-collection fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.7rem;">TSR Collect</span>
                </button>
              </div>
              <!-- TSR Save -->
              <div class="col-md-2">
                <button
                  class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                  onclick="runControl('tsr_save')">
                  <div class="rounded-circle bg-primary bg-opacity-10 text-primary p-1">
                    <i class="bi bi-save fs-6"></i>
                  </div>
                  <span class="fw-medium text-dark" style="font-size: 0.7rem;">TSR Save</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  {# 진행바 #}
  <div class="row mb-4" id="progressSection" style="display: none;">
    <div class="col">
      <div class="card border-0 shadow-sm">
        <div class="card-body p-3">
          <div class="d-flex align-items-center mb-2">
            <i class="bi bi-activity text-primary me-2"></i>
            <span class="fw-semibold">처리 진행률</span>
          </div>
          <div class="progress" style="height: 25px;">
            <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-success"
              role="progressbar" style="width:0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
              <span class="fw-semibold">0%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  {# 파일 관리 도구 #}
  <div class="row mb-4">
    <div class="col">
      <div class="card shadow-sm tool-zone-card">
        <div class="card-header bg-transparent border-0 px-4 pt-4 pb-2">
          <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3">
            <div>
              <div class="tool-zone-caption text-primary fw-semibold mb-2">Action Tools</div>
              <h5 class="mb-1 fw-bold">
                <i class="bi bi-tools me-2"></i>파일 관리 도구
              </h5>
            </div>
            <div class="d-flex align-items-center gap-3">
              <span class="badge rounded-pill text-bg-light border px-3 py-2">작업 실행 영역</span>
              <div class="d-flex align-items-center gap-2">
                <small id="fileToolsHint" class="text-primary fw-bold"
                  style="font-size: 0.75rem; cursor: pointer;">(클릭하여 열기)</small>
                <button class="btn btn-sm btn-link text-secondary p-0 text-decoration-none" type="button"
                  data-bs-toggle="collapse" data-bs-target="#fileToolsPanel" aria-expanded="false"
                  aria-controls="fileToolsPanel">
                  <i class="bi bi-chevron-down"></i>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div id="fileToolsPanel" class="collapse">
          <div class="card-body p-4 file-tools">
            <div class="d-flex flex-column gap-3">

              <!-- 상단: 입력형 도구 (다운로드/백업) -->
              <div class="row g-2">
                <!-- ZIP 다운로드 -->
                <div class="col-6">
                  <div class="card h-100 border-primary-subtle bg-primary-subtle bg-opacity-10">
                    <div class="card-body p-2 d-flex flex-column justify-content-center">
                      <h6 class="card-title fw-bold text-primary mb-1 small" style="font-size: 0.75rem;">
                        <i class="bi bi-file-earmark-zip me-1"></i>ZIP
                      </h6>
                      <form method="post" action="{{ url_for('main.download_zip') }}">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <div class="input-group input-group-sm">
                          <input type="text" class="form-control border-primary-subtle form-control-sm"
                            name="zip_filename" placeholder="파일명 또는 백업폴더명" required
                            style="font-size: 0.75rem; padding: 0.2rem 0.5rem;">
                          <button class="btn btn-primary btn-sm px-2" type="submit">
                            <i class="bi bi-download" style="font-size: 0.75rem;"></i>
                          </button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>

                <!-- 파일 백업 -->
                <div class="col-6">
                  <div class="card h-100 border-success-subtle bg-success-subtle bg-opacity-10">
                    <div class="card-body p-2 d-flex flex-column justify-content-center">
                      <h6 class="card-title fw-bold text-success mb-1 small" style="font-size: 0.75rem;">
                        <i class="bi bi-hdd-network me-1"></i>백업
                      </h6>
                      <form method="post" action="{{ url_for('main.backup_files') }}" id="backupFilesForm">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <div class="input-group input-group-sm">
                          <select class="form-select form-select-sm border-success-subtle" name="backup_target_folder"
                            id="backupTargetFolder" aria-label="백업 대상 폴더 선택"
                            style="font-size: 0.75rem; padding: 0.2rem 0.5rem; max-width: 42%;">
                            <option value="__new__" selected>새 폴더 만들기</option>
                            {% for folder_name in backup_folder_names %}
                            <option value="{{ folder_name }}">{{ folder_name }}</option>
                            {% endfor %}
                          </select>
                          <input type="text" class="form-control border-success-subtle form-control-sm"
                            id="backupPrefixInput" name="backup_prefix" placeholder="PO로 시작하는 새 폴더명"
                            style="font-size: 0.75rem; padding: 0.2rem 0.5rem;">
                          <button class="btn btn-success btn-sm px-2" type="submit" title="선택한 폴더로 백업">
                            <i class="bi bi-save" style="font-size: 0.75rem;"></i>
                          </button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 하단: 원클릭 액션 (파일 정리) -->
              <div class="card bg-light border-0">
                <div class="card-body p-3">
                  <small class="text-muted fw-bold text-uppercase mb-2 d-block">
                    <i class="bi bi-folder-symlink me-1"></i>파일 정리 (Quick Move)
                  </small>
                  <div class="row g-2">
                    <!-- MAC Move -->
                    <div class="col-4">
                      <form id="macMoveForm" method="post" action="{{ url_for('utils.move_mac_files') }}" class="h-100">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button
                          class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                          type="submit">
                          <div class="rounded-circle bg-primary bg-opacity-10 text-primary p-1">
                            <i class="bi bi-cpu fs-6"></i>
                          </div>
                          <span class="fw-medium text-dark" style="font-size: 0.75rem;">MAC</span>
                        </button>
                      </form>
                    </div>

                    <!-- GUID Move -->
                    <div class="col-4">
                      <form id="guidMoveForm" method="post" action="{{ url_for('utils.move_guid_files') }}" class="h-100">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button
                          class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                          type="submit">
                          <div class="rounded-circle bg-success bg-opacity-10 text-success p-1">
                            <i class="bi bi-fingerprint fs-6"></i>
                          </div>
                          <span class="fw-medium text-dark" style="font-size: 0.75rem;">GUID</span>
                        </button>
                      </form>
                    </div>

                    <div class="col-4">
                      <form id="gpuMoveForm" method="post" action="{{ url_for('utils.move_gpu_files') }}" class="h-100">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button
                          class="btn btn-white bg-white border shadow-sm w-100 h-100 py-1 d-flex flex-column align-items-center justify-content-center gap-1 btn-quick-move"
                          type="submit">
                          <div class="rounded-circle bg-danger bg-opacity-10 text-danger p-1">
                            <i class="bi bi-gpu-card fs-6"></i>
                          </div>
                          <span class="fw-medium text-dark" style="font-size: 0.75rem;">GPU</span>
                        </button>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  {# 통합 파일 관리 섹션 (탭 인터페이스) #}
  <style>
    .tool-zone-card {
      border-color: rgba(33, 37, 41, 0.08);
      background: linear-gradient(180deg, #ffffff 0%, #fbfcfe 100%);
    }

    .tool-zone-caption {
      font-size: 0.78rem;
      letter-spacing: 0.08em;
      text-transform: uppercase;
    }

    .file-dashboard-card {
      background:
        radial-gradient(circle at top right, rgba(13, 110, 253, 0.07), transparent 32%),
        linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
    }

    #fileTabs .nav-link {
      color: #495057 !important;
      font-weight: 600;
      border: 1px solid transparent;
      border-radius: 999px;
      background-color: transparent;
      padding: 0.7rem 1rem;
    }

    #fileTabs .nav-link.active {
      color: #0d6efd !important;
      background-color: #eef5ff !important;
      border-color: #cfe2ff !important;
      box-shadow: inset 0 0 0 1px rgba(13, 110, 253, 0.08);
    }

    .workspace-topbar {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 1rem;
      flex-wrap: wrap;
    }

    .file-kpi-strip {
      display: flex;
      justify-content: flex-end;
      gap: 0.5rem;
      flex-wrap: nowrap;
      margin-left: auto;
    }

    .file-kpi-card {
      border: 1px solid rgba(13, 110, 253, 0.08);
      border-radius: 1rem;
      background: rgba(255, 255, 255, 0.88);
      padding: 1rem 1.1rem;
      height: 100%;
    }

    .file-kpi-button {
      width: 100%;
      text-align: left;
      cursor: pointer;
      transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease, background-color 0.18s ease;
    }

    .file-kpi-button:hover {
      transform: translateY(-2px);
      border-color: rgba(13, 110, 253, 0.22);
      box-shadow: 0 0.65rem 1.4rem rgba(13, 110, 253, 0.08);
    }

    .file-kpi-button.is-active {
      border-color: rgba(13, 110, 253, 0.35);
      box-shadow: inset 0 0 0 1px rgba(13, 110, 253, 0.12);
      background: linear-gradient(180deg, #ffffff 0%, #eef5ff 100%);
    }

    .file-kpi-card--compact {
      min-width: 112px;
      padding: 0.55rem 0.7rem;
      border-radius: 0.9rem;
    }

    .file-kpi-card--compact .file-kpi-icon {
      width: 1.7rem;
      height: 1.7rem;
      border-radius: 0.6rem;
      font-size: 0.82rem;
    }

    .file-kpi-card--compact .file-kpi-label {
      font-size: 0.7rem;
      line-height: 1.1;
      white-space: nowrap;
    }

    .file-kpi-card--compact .file-kpi-value {
      font-size: 1.05rem;
      line-height: 1;
      margin-left: 0.35rem;
    }

    .file-kpi-card--compact .file-kpi-link {
      display: none;
    }

    .file-kpi-card--compact .file-kpi-meta {
      display: flex;
      align-items: baseline;
      white-space: nowrap;
    }

    .file-kpi-icon {
      width: 2.5rem;
      height: 2.5rem;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border-radius: 0.85rem;
      font-size: 1.05rem;
    }

    .file-toolbar-shell {
      border: 1px solid rgba(13, 110, 253, 0.08);
      border-radius: 1rem;
      background: rgba(255, 255, 255, 0.9);
      padding: 1rem 1.1rem;
    }

    .file-filter-caption {
      font-size: 0.78rem;
      letter-spacing: 0.06em;
      text-transform: uppercase;
    }

    .file-search-box {
      width: min(100%, 320px);
    }

    .search-scope-text {
      font-size: 0.78rem;
    }

    #repoTabs .nav-link {
      color: #495057 !important;
      font-weight: 600;
      background-color: #fff;
      border: 1px solid #dee2e6;
      border-radius: 999px;
      padding: 0.55rem 0.9rem;
      transition: color 0.18s ease, background-color 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease;
    }

    #repoTabs .nav-link.active {
      color: #fff !important;
      border-color: transparent !important;
      box-shadow: 0 0.55rem 1.1rem rgba(13, 110, 253, 0.2);
      transform: translateY(-1px);
    }

    #subpanel-backup-tab.active,
    #subpanel-mac-tab.active {
      background-color: #0d6efd !important;
    }

    #subpanel-guid-tab.active {
      background-color: #198754 !important;
      box-shadow: 0 0.55rem 1.1rem rgba(25, 135, 84, 0.2);
    }

    #subpanel-gpu-tab.active {
      background-color: #dc3545 !important;
      box-shadow: 0 0.55rem 1.1rem rgba(220, 53, 69, 0.2);
    }

    #repoTabs .nav-link .badge,
    #repoTabs .nav-link i {
      transition: inherit;
    }

    #repoTabs .nav-link.active .badge {
      background-color: rgba(255, 255, 255, 0.18) !important;
      color: #fff !important;
    }

    #repoTabs .nav-link.active i {
      color: #fff !important;
    }

    .table-shell {
      border: 1px solid rgba(33, 37, 41, 0.08);
      border-radius: 1rem;
      overflow: hidden;
      background-color: #fff;
    }

    .table-shell .table thead th {
      background-color: #f8f9fa;
      border-bottom: 1px solid rgba(33, 37, 41, 0.08);
      font-size: 0.85rem;
      text-transform: uppercase;
      letter-spacing: 0.02em;
    }

    .empty-state-card {
      border: 1px dashed #cbd5e1;
      border-radius: 1rem;
      background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
      padding: 2.5rem 1.5rem;
      text-align: center;
    }

    .empty-state-card .empty-state-icon {
      width: 3.5rem;
      height: 3.5rem;
      margin: 0 auto 1rem;
      border-radius: 1rem;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background-color: #eef5ff;
      color: #0d6efd;
      font-size: 1.35rem;
    }

    .empty-state-card p {
      max-width: 28rem;
      margin: 0 auto 1rem;
    }

    .section-caption {
      font-size: 0.78rem;
      letter-spacing: 0.08em;
      text-transform: uppercase;
    }

    .backup-search-empty {
      display: none;
    }

    .backup-search-empty.show {
      display: block;
    }

    .workspace-action-row {
      align-items: center;
      flex-wrap: wrap;
    }

    .workspace-action-row form {
      display: inline-flex !important;
      align-items: center;
      margin: 0;
    }

    .workspace-upload-form {
      display: inline-flex;
      margin: 0;
    }

    .workspace-upload-form .btn {
      line-height: 1.4;
    }

    .workspace-icon-button {
      width: 2rem;
      height: 2rem;
      padding: 0 !important;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      line-height: 1 !important;
      vertical-align: top;
    }

    .backup-file-item.match-hidden {
      display: none;
    }

    .backup-file-item {
      transition: background-color 0.18s ease, box-shadow 0.18s ease;
    }

    .backup-file-item.selected td {
      background-color: #e7f1ff !important;
      box-shadow: inset 0 -1px 0 rgba(13, 110, 253, 0.08), inset 0 1px 0 rgba(13, 110, 253, 0.08);
    }

    .backup-drag-handle {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 1.75rem;
      height: 1.75rem;
      border-radius: 0.5rem;
      cursor: grab;
      transition: background-color 0.18s ease, color 0.18s ease;
    }

    .backup-drag-handle:hover {
      background-color: #eef5ff;
      color: #0d6efd !important;
    }

    .backup-drag-handle:active {
      cursor: grabbing;
    }

    .custom-tab-panel {
      display: none !important;
    }

    .custom-tab-panel.custom-active {
      display: block !important;
    }

    /* 커스텀 서브 탭 패널 가시성 제어 */
    .custom-sub-panel {
      display: none !important;
    }

    .custom-sub-panel.custom-sub-active {
      display: block !important;
    }

    @media (max-width: 991.98px) {
      #fileTabs {
        width: 100%;
      }

      #fileTabs .nav-item,
      #fileTabs .nav-link {
        width: 100%;
      }

      .file-search-box {
        width: 100%;
      }

      .workspace-topbar {
        flex-direction: column;
        align-items: stretch;
      }

      .file-kpi-strip {
        width: 100%;
        margin-left: 0;
        justify-content: stretch;
        flex-wrap: wrap;
      }

      .file-kpi-strip .file-kpi-button {
        flex: 1 1 0;
        min-width: 0;
      }
    }
  </style>
  <div class="row mb-5">
    <div class="col">
      <div class="card border shadow-sm file-dashboard-card">
        <div class="card-header bg-transparent border-0 pt-4 px-4 pb-3">
          <div class="d-flex flex-column gap-4">
            <div>
              <div class="section-caption text-primary fw-semibold mb-2">Results Workspace</div>
              <h5 class="mb-1 fw-bold">결과 확인 워크스페이스</h5>
            </div>

            <div class="workspace-topbar">
              <ul class="nav nav-tabs border-0 gap-2 align-self-start mb-0" id="fileTabs" role="tablist">
                <li class="nav-item" role="presentation">
                  <button class="nav-link active" id="processed-tab" data-custom-toggle="tab" data-bs-target="#processed"
                    type="button" role="tab" aria-controls="processed" aria-selected="true">
                    <i class="bi bi-check-circle-fill text-success me-2"></i>처리된 파일
                    {% if files_to_display %}
                    <span class="badge bg-secondary-subtle text-secondary-emphasis ms-2 rounded-pill">{{ files_to_display|length }}</span>
                    {% endif %}
                  </button>
                </li>
                <li class="nav-item" role="presentation">
                  <button class="nav-link" id="repository-tab" data-custom-toggle="tab" data-bs-target="#repository-panel"
                    type="button" role="tab" aria-controls="repository-panel" aria-selected="false">
                    <i class="bi bi-archive-fill text-primary me-2"></i>백업 및 저장소
                  </button>
                </li>
              </ul>

              <div class="file-kpi-strip">
                <button type="button" class="file-kpi-card file-kpi-button file-kpi-card--compact" data-kpi-target="subpanel-mac-tab">
                  <div class="d-flex align-items-center justify-content-between">
                    <div class="file-kpi-meta">
                      <span class="file-kpi-label text-muted">MAC 파일</span>
                      <span class="file-kpi-value fw-bold">{{ mac_files|length }}</span>
                    </div>
                    <div class="file-kpi-icon bg-primary-subtle text-primary">
                      <i class="bi bi-cpu"></i>
                    </div>
                  </div>
                </button>
                <button type="button" class="file-kpi-card file-kpi-button file-kpi-card--compact" data-kpi-target="subpanel-guid-tab">
                  <div class="d-flex align-items-center justify-content-between">
                    <div class="file-kpi-meta">
                      <span class="file-kpi-label text-muted">GUID 파일</span>
                      <span class="file-kpi-value fw-bold">{{ guid_files|length }}</span>
                    </div>
                    <div class="file-kpi-icon bg-success-subtle text-success">
                      <i class="bi bi-fingerprint"></i>
                    </div>
                  </div>
                </button>
                <button type="button" class="file-kpi-card file-kpi-button file-kpi-card--compact" data-kpi-target="subpanel-gpu-tab">
                  <div class="d-flex align-items-center justify-content-between">
                    <div class="file-kpi-meta">
                      <span class="file-kpi-label text-muted">GPU 파일</span>
                      <span class="file-kpi-value fw-bold">{{ gpu_files|length }}</span>
                    </div>
                    <div class="file-kpi-icon bg-danger-subtle text-danger">
                      <i class="bi bi-gpu-card"></i>
                    </div>
                  </div>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="card-body p-4 pt-0">
          <div class="file-toolbar-shell mb-4">
            <div class="d-flex flex-column flex-xl-row justify-content-between align-items-xl-center gap-3">
              <div class="flex-grow-1">
                <div class="d-flex align-items-center flex-wrap gap-2 mb-3 mb-xl-2">
                  <span class="badge rounded-pill text-bg-light border" id="activeFileModeBadge">처리된 파일</span>
                </div>

                <ul class="nav nav-pills gap-2 flex-wrap" id="repoTabs" role="tablist">
                  <li class="nav-item" role="presentation">
                    <button class="nav-link active btn-sm" id="subpanel-backup-tab" data-custom-toggle="pill"
                      data-bs-target="#subpanel-backup" type="button" role="tab" aria-selected="true">
                      <i class="bi bi-hdd-server me-1"></i>서버 정보
                      <span class="badge bg-light text-dark ms-1">{{ server_info_files|length if server_info_files else 0 }}</span>
                    </button>
                  </li>
                  <li class="nav-item" role="presentation">
                    <button class="nav-link btn-sm" id="subpanel-mac-tab" data-custom-toggle="pill"
                      data-bs-target="#subpanel-mac" type="button" role="tab" aria-selected="false">
                      <i class="bi bi-cpu me-1"></i>MAC
                      <span class="badge bg-light text-dark ms-1">{{ mac_files|length }}</span>
                    </button>
                  </li>
                  <li class="nav-item" role="presentation">
                    <button class="nav-link btn-sm" id="subpanel-guid-tab" data-custom-toggle="pill"
                      data-bs-target="#subpanel-guid" type="button" role="tab" aria-selected="false">
                      <i class="bi bi-fingerprint me-1"></i>GUID
                      <span class="badge bg-light text-dark ms-1">{{ guid_files|length }}</span>
                    </button>
                  </li>
                  <li class="nav-item" role="presentation">
                    <button class="nav-link btn-sm" id="subpanel-gpu-tab" data-custom-toggle="pill"
                      data-bs-target="#subpanel-gpu" type="button" role="tab" aria-selected="false">
                      <i class="bi bi-gpu-card me-1"></i>GPU
                      <span class="badge bg-light text-dark ms-1">{{ gpu_files|length }}</span>
                    </button>
                  </li>
                </ul>
              </div>

              <div class="d-flex align-items-center gap-2">
                <button type="button" class="btn btn-outline-primary btn-sm text-nowrap"
                  data-bs-toggle="modal" data-bs-target="#serviceTagZipModal"
                  title="서비스태그로 파일 검색 후 ZIP 다운로드">
                  <i class="bi bi-file-earmark-zip me-1"></i>서버 정보 저장
                </button>
                <div class="file-search-box">
                  <div class="input-group">
                    <span class="input-group-text bg-white border-end-0"><i class="bi bi-search"></i></span>
                    <input type="text" class="form-control border-start-0" id="globalFileSearch"
                      placeholder="파일명을 검색하세요">
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="custom-tabs-container" id="fileTabsContent">

            {# ===================== [TAB 1] 처리된 파일 ===================== #}
            <div class="custom-tab-panel custom-active" id="processed" role="tabpanel" aria-labelledby="processed-tab">
              {% if files_to_display and files_to_display|length > 0 %}
              <div class="table-shell">
                <div class="table-responsive bg-white">
                <table class="table table-hover align-middle mb-0" id="tableProcessed">
                  <thead class="bg-light">
                    <tr>
                      <th class="ps-3" style="cursor:pointer;" onclick="sortTable('tableProcessed', 0)">파일명 <i
                          class="bi bi-arrow-down-up small text-muted"></i></th>
                      <th style="width: 150px;">작업</th>
                    </tr>
                  </thead>
                  <tbody>
                    {% for file_info in files_to_display %}
                    <tr>
                      <td class="ps-3">
                        <div class="d-flex align-items-center">
                          <i class="bi bi-file-earmark-text text-secondary fs-5 me-3"></i>
                          <div>
                            <a href="{{ url_for('main.download_file', filename=file_info.file) }}"
                              class="text-decoration-none fw-semibold text-dark" download>
                              {{ file_info.name or file_info.file }}
                            </a>
                          </div>
                        </div>
                      </td>
                      <td>
                        <div class="d-flex gap-2">
                          <button type="button" class="btn btn-sm btn-light text-primary bg-primary-subtle border-0"
                            data-bs-toggle="modal" data-bs-target="#fileViewModal" data-folder="idrac_info"
                            data-filename="{{ file_info.file }}" title="내용 보기">
                            <i class="bi bi-eye-fill"></i>
                          </button>
                          <form action="{{ url_for('main.delete_file', filename=file_info.file) }}" method="post"
                            class="d-inline">
                            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                            <button type="submit" class="btn btn-sm btn-light text-danger bg-danger-subtle border-0"
                              onclick="return confirm('이 파일을 삭제하시겠습니까?');" title="삭제">
                              <i class="bi bi-trash-fill"></i>
                            </button>
                          </form>
                        </div>
                      </td>
                    </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
              </div>
              {% else %}
              <div class="empty-state-card">
                <div class="empty-state-icon">
                  <i class="bi bi-inbox"></i>
                </div>
                <h6 class="fw-bold mb-2">아직 처리된 파일이 없습니다</h6>
              </div>
              {% endif %}

              {# 페이지네이션 (기존 로직 유지) #}
              {% if files_to_display and files_to_display|length > 0 and total_pages > 1 %}
              <nav aria-label="Processed files pagination" class="mt-4">
                <ul class="pagination justify-content-center mb-0 pagination-sm">
                  {% if page > 1 %}
                  <li class="page-item">
                    <a class="page-link" href="{{ url_for('main.index', page=page-1) }}"><i
                        class="bi bi-chevron-left"></i></a>
                  </li>
                  {% else %}
                  <li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-left"></i></span></li>
                  {% endif %}
                  {% set start_page = ((page - 1) // 10) * 10 + 1 %}
                  {% set end_page = [start_page + 9, total_pages]|min %}
                  {% for p in range(start_page, end_page + 1) %}
                  <li class="page-item {% if p == page %}active{% endif %}">
                    <a class="page-link" href="{{ url_for('main.index', page=p) }}">{{ p }}</a>
                  </li>
                  {% endfor %}
                  {% if page < total_pages %} <li class="page-item"><a class="page-link"
                      href="{{ url_for('main.index', page=page+1) }}"><i class="bi bi-chevron-right"></i></a></li>
                    {% else %}
                    <li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-right"></i></span>
                    </li>
                    {% endif %}
                </ul>
              </nav>
              {% endif %}
            </div>

            {# ===================== [TAB 2] 백업 및 저장소 ===================== #}
            <div class="custom-tab-panel" id="repository-panel" role="tabpanel" aria-labelledby="repository-tab"
              style="display: none !important;">
              <div class="custom-sub-tabs-container" id="repoTabsContent">

                {# ----- 서브탭 1: 일별 백업 (기존 아코디언 스타일 유지 + 파일 목록 테이블화) ----- #}
                <div class="custom-sub-panel" id="subpanel-backup" role="tabpanel">
                  {% if server_info_files and server_info_files|length > 0 %}
                  <div class="accordion" id="backupAccordion">
                    {% for folder_name, info in server_info_files.items() %}
                    <div class="accordion-item mb-2 border rounded overflow-hidden">
                      <h2 class="accordion-header" id="heading-{{ loop.index }}">
                        <div class="d-flex align-items-center bg-light w-100 px-0">
                          <button class="accordion-button collapsed bg-light py-2 shadow-none border-0" type="button"
                            data-bs-toggle="collapse" data-bs-target="#collapse-{{ loop.index }}" aria-expanded="false"
                            style="width: auto; flex-grow: 1;">
                            <div class="d-flex align-items-center">
                              <i class="bi bi-hdd-server text-primary me-2"></i>
                              <span class="fw-semibold me-3">{{ folder_name
                                }}</span>
                              <span class="badge bg-secondary rounded-pill">{{ info.count }} 파일</span>
                            </div>
                          </button>

                          {# 폴더 액션 버튼 (버튼 밖으로 이동하여 HTML 표준 준수) #}
                          <div class="d-flex gap-1 pe-3 me-4 workspace-action-row">
                            <form action="{{ url_for('main.archive_backup_folder', folder_name=folder_name) }}"
                              method="post" class="d-inline">
                              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                              <button type="submit" class="btn btn-outline-secondary workspace-icon-button"
                                title="아카이브로 이동"
                                onclick="return confirm('아카이브하시겠습니까?');">
                                <i class="bi bi-archive"></i>
                              </button>
                            </form>
                            <form action="{{ url_for('main.download_zip') }}" method="post" class="d-inline">
                              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                              <input type="hidden" name="zip_filename" value="{{ folder_name }}">
                              <button type="submit" class="btn btn-outline-primary workspace-icon-button"
                                title="{{ folder_name }}.zip 다운로드">
                                <i class="bi bi-file-earmark-zip"></i>
                              </button>
                            </form>
                            <form action="{{ url_for('main.upload_workspace_files', target_type='server_info') }}"
                              method="post" enctype="multipart/form-data" class="workspace-upload-form">
                              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                              <input type="hidden" name="folder_name" value="{{ folder_name }}">
                              <input type="hidden" name="duplicate_policy" value="rename">
                              <label class="btn btn-outline-success mb-0 workspace-icon-button"
                                title="이 서버 정보 폴더에 파일 업로드">
                                <i class="bi bi-upload"></i>
                                <input type="file" name="files" class="d-none workspace-file-upload-input" multiple
                                  data-existing-files='{{ info.files|tojson }}'>
                              </label>
                            </form>
                            <form action="{{ url_for('main.delete_backup_folder', folder_name=folder_name) }}"
                              method="post" class="d-inline">
                              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                              <button type="submit" class="btn btn-outline-danger workspace-icon-button"
                                title="폴더 삭제"
                                onclick="return confirm('영구 삭제하시겠습니까?');">
                                <i class="bi bi-trash"></i>
                              </button>
                            </form>
                          </div>
                        </div>
                      </h2>
                      <div id="collapse-{{ loop.index }}" class="accordion-collapse collapse">
                        <div class="accordion-body p-0">
                          {# 백업 파일 테이블 (내부 검색/정렬은 생략하거나 필요시 추가) #}
                          <div class="table-responsive" style="max-height: 400px;">
                            <table class="table table-sm table-hover mb-0 font-monospace" style="font-size: 0.9rem;">
                              <thead class="bg-light sticky-top">
                                <tr>
                                  <th class="text-center" style="width: 44px;">이동</th>
                                  <th class="ps-3">파일명</th>
                                  <th class="text-end pe-3" style="width: 100px;">보기</th>
                                </tr>
                              </thead>
                              <tbody class="backup-files-container" data-folder="{{ folder_name }}">
                                {% for file in info.files %}
                                <tr class="backup-file-item" data-filename="{{ file }}">
                                  <td class="text-center align-middle">
                                    <span class="backup-drag-handle text-muted" title="드래그하여 다른 폴더로 이동">
                                      <i class="bi bi-grip-vertical"></i>
                                    </span>
                                  </td>
                                  <td class="ps-3 align-middle">
                                    <a href="{{ url_for('main.download_backup_file', date=folder_name, filename=file) }}"
                                      class="text-decoration-none text-dark d-block text-truncate" download>
                                      {{ file }}
                                    </a>
                                  </td>
                                  <td class="text-end pe-3">
                                    <button type="button" class="btn btn-xs btn-link text-secondary p-0 btn-view-backup"
                                      data-bs-toggle="modal" data-bs-target="#fileViewModal" data-folder="server_info"
                                      data-date="{{ folder_name }}" data-filename="{{ file }}">
                                      <i class="bi bi-eye"></i>
                                    </button>
                                  </td>
                                </tr>
                                {% endfor %}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    {% endfor %}
                  </div>
                  <div class="empty-state-card backup-search-empty mt-3" id="backupSearchEmpty">
                    <div class="empty-state-icon">
                      <i class="bi bi-search"></i>
                    </div>
                    <h6 class="fw-bold mb-2">현재 조건과 일치하는 서버 정보가 없습니다</h6>
                    <p class="text-muted">검색어를 지우거나 다른 키워드로 다시 확인해 주세요.</p>
                    <button type="button" class="btn btn-outline-secondary btn-sm" id="btnClearFileSearch">
                      <i class="bi bi-arrow-counterclockwise me-1"></i>검색어 지우기
                    </button>
                  </div>

                  {# 백업 페이지네이션 #}
                  {% if total_backup_pages > 1 %}
                  <nav class="mt-3">
                    <ul class="pagination pagination-sm justify-content-center">
                      {% if backup_page > 1 %}
                      <li class="page-item"><a class="page-link"
                          href="{{ url_for('main.index', backup_page=backup_page-1, page=page) }}"><i
                            class="bi bi-chevron-left"></i></a></li>
                      {% endif %}
                      {% set start_b = ((backup_page - 1) // 10) * 10 + 1 %}
                      {% set end_b = [start_b + 9, total_backup_pages]|min %}
                      {% for p in range(start_b, end_b + 1) %}
                      <li class="page-item {% if p == backup_page %}active{% endif %}"><a class="page-link"
                          href="{{ url_for('main.index', backup_page=p, page=page) }}">{{ p }}</a></li>
                      {% endfor %}
                      {% if backup_page < total_backup_pages %} <li class="page-item"><a class="page-link"
                          href="{{ url_for('main.index', backup_page=backup_page+1, page=page) }}"><i
                            class="bi bi-chevron-right"></i></a></li>
                        {% endif %}
                    </ul>
                  </nav>
                  {% endif %}

                  {% else %}
                  <div class="empty-state-card">
                    <div class="empty-state-icon">
                      <i class="bi bi-hdd-stack"></i>
                    </div>
                    <h6 class="fw-bold mb-2">백업된 서버 정보가 아직 없습니다</h6>
                    <p class="text-muted">서버 정보 수집 작업을 실행하면 날짜별 백업 폴더가 이 영역에 생성됩니다.</p>
                    <a href="#ipForm" class="btn btn-outline-primary btn-sm">
                      <i class="bi bi-play-circle me-1"></i>서버 정보 수집 시작
                    </a>
                  </div>
                  {% endif %}
                </div>

                {# ----- 서브탭 2: MAC ----- #}
                <div class="custom-sub-panel d-none" id="subpanel-mac" role="tabpanel">
                  {% with table_id="tableMac", files=mac_files, folder="mac", empty_msg="MAC 파일이 없습니다." %}
                  {% include "snippets/repo_file_table.html" %}
                  {% endwith %}
                </div>

                {# ----- 서브탭 3: GUID ----- #}
                <div class="custom-sub-panel d-none" id="subpanel-guid" role="tabpanel">
                  {% with table_id="tableGuid", files=guid_files, folder="guid", empty_msg="GUID 파일이 없습니다." %}
                  {% include "snippets/repo_file_table.html" %}
                  {% endwith %}
                </div>

                {# ----- 서브탭 4: GPU ----- #}
                <div class="custom-sub-panel d-none" id="subpanel-gpu" role="tabpanel">
                  {% with table_id="tableGpu", files=gpu_files, folder="gpu", empty_msg="GPU 파일이 없습니다." %}
                  {% include "snippets/repo_file_table.html" %}
                  {% endwith %}
                </div>

              </div>
            </div> <!-- End Tab 2 -->

          </div>
        </div>
      </div>
    </div>
  </div>


</div>

{# 서비스태그 ZIP 다운로드 모달 #}
<div class="modal fade" id="serviceTagZipModal" tabindex="-1" aria-labelledby="serviceTagZipModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="serviceTagZipModalLabel">
          <i class="bi bi-file-earmark-zip me-2 text-primary"></i>서비스태그로 파일 검색 &amp; ZIP 다운로드
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
      </div>
      <div class="modal-body">
        <p class="text-muted small mb-3">
          서비스태그를 입력하면 백업 폴더 및 저장소에서 <code>&lt;서비스태그&gt;.txt</code> 파일을 찾아 ZIP으로 묶어 다운로드합니다.
        </p>

        {# 입력 방식 선택 카드 #}
        <div class="row g-2 mb-3">
          <div class="col-6">
            <input type="radio" class="btn-check" name="stInputMode" id="stModeManual" value="manual" autocomplete="off" checked>
            <label class="btn w-100 h-100 border stab-mode-label text-start p-3" for="stModeManual"
              style="border-radius: 0.5rem; cursor: pointer;">
              <div class="d-flex align-items-center gap-2">
                <div class="rounded-circle p-2 stab-icon-wrap">
                  <i class="bi bi-keyboard fs-5"></i>
                </div>
                <div>
                  <div class="fw-semibold" style="font-size: 0.9rem;">직접 입력</div>
                  <div class="text-muted" style="font-size: 0.75rem;">태그를 직접 붙여넣기</div>
                </div>
              </div>
            </label>
          </div>
          <div class="col-6">
            <input type="radio" class="btn-check" name="stInputMode" id="stModeFile" value="file" autocomplete="off">
            <label class="btn w-100 h-100 border stab-mode-label text-start p-3" for="stModeFile"
              style="border-radius: 0.5rem; cursor: pointer;">
              <div class="d-flex align-items-center gap-2">
                <div class="rounded-circle p-2 stab-icon-wrap">
                  <i class="bi bi-file-earmark-text fs-5"></i>
                </div>
                <div>
                  <div class="fw-semibold" style="font-size: 0.9rem;">파일 업로드</div>
                  <div class="text-muted" style="font-size: 0.75rem;">.txt 파일로 가져오기</div>
                </div>
              </div>
            </label>
          </div>
        </div>
        <style>
          .stab-mode-label { transition: border-color 0.15s, background 0.15s; }
          .btn-check:checked + .stab-mode-label {
            border-color: #0d6efd !important;
            background: #f0f5ff;
          }
          .btn-check:checked + .stab-mode-label .stab-icon-wrap {
            background: #0d6efd;
            color: #fff;
          }
          .stab-icon-wrap { background: #e9ecef; color: #6c757d; transition: background 0.15s, color 0.15s; }
        </style>

        {# 직접 입력 패널 #}
        <div id="stab-manual">
          <div class="mb-1 d-flex justify-content-between align-items-center">
            <label for="serviceTagsInput" class="form-label mb-0 small fw-semibold">서비스태그 목록</label>
            <span class="badge bg-secondary" id="serviceTagLineCount">0개</span>
          </div>
          <textarea id="serviceTagsInput" class="form-control font-monospace"
            rows="10" placeholder="서비스태그를 한 줄씩 입력하세요&#10;예)&#10;ABC1234&#10;DEF5678&#10;GHI9012"
            style="font-size: 0.85rem; resize: vertical;"></textarea>
        </div>

        {# 파일 업로드 패널 #}
        <div id="stab-file" class="d-none">
          <div class="mb-2">
            <label for="serviceTagsFile" class="form-label small fw-semibold">서비스태그 목록 파일 (.txt)</label>
            <input type="file" class="form-control" id="serviceTagsFile" accept=".txt">
            <div class="form-text">서비스태그가 한 줄씩 작성된 <code>.txt</code> 파일을 선택하세요.</div>
          </div>
          <div id="filePreviewArea" class="d-none">
            <div class="d-flex justify-content-between align-items-center mb-1">
              <small class="text-muted fw-semibold">파일 미리보기</small>
              <span class="badge bg-secondary" id="fileTagCount">0개</span>
            </div>
            <pre id="filePreviewContent" class="bg-light border rounded p-2 font-monospace"
              style="font-size: 0.8rem; max-height: 200px; overflow-y: auto; white-space: pre-wrap;"></pre>
          </div>
        </div>

        {# 저장 파일명 입력 #}
        <div class="mt-3">
          <label for="serviceTagZipName" class="form-label small fw-semibold">저장 파일명</label>
          <div class="input-group">
            <span class="input-group-text bg-light"><i class="bi bi-file-earmark-zip text-primary"></i></span>
            <input type="text" class="form-control" id="serviceTagZipName"
              placeholder="파일명을 입력하세요 (예: PO-20260409_판교_R6615)"
              style="font-size: 0.9rem;">
            <span class="input-group-text bg-light text-muted">.zip</span>
          </div>
        </div>

        {# 결과 영역 #}
        <div id="serviceTagResult" class="mt-3 d-none">
          <hr class="my-2">
          <div id="serviceTagResultContent"></div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="bi bi-x-circle me-1"></i>닫기
        </button>
        <button type="button" class="btn btn-primary" id="btnDoServiceTagZip">
          <i class="bi bi-file-earmark-zip me-1"></i>ZIP 다운로드
        </button>
      </div>
    </div>
  </div>
</div>

{# 파일 보기 모달 #}
<div class="modal fade" id="fileViewModal" tabindex="-1" aria-labelledby="fileViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="fileViewModalLabel">
          <i class="bi bi-file-text me-2"></i>
          파일 보기
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
      </div>
      <div class="modal-body bg-light">
        <pre id="fileViewContent" class="mb-0 p-3 bg-white border rounded font-monospace"
          style="white-space:pre-wrap;word-break:break-word;max-height:70vh;">불러오는 중...</pre>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="bi bi-x-circle me-1"></i>닫기
        </button>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_css %}
<!-- Tom Select CSS (Bootstrap 5 theme) -->
<link href="{{ url_for('static', filename='vendor/tom-select/css/tom-select.bootstrap5.min.css') }}" rel="stylesheet">
{% endblock %}

{% block scripts %}
{{ super() }}

<!-- Tom Select JS -->
<script src="{{ url_for('static', filename='vendor/tom-select/js/tom-select.complete.min.js') }}"></script>



<script>
  window.APP_CONFIG = {
    moveBackupUrl: "{{ url_for('main.move_backup_files') }}",
    csrfToken: "{{ csrf_token() }}",
    downloadBaseUrl: "{{ url_for('main.download_backup_file', date='PLACEHOLDER_DATE', filename='PLACEHOLDER_FILE') }}",
    systemControlUrl: "{{ url_for('utils.system_control') }}",
    exportServiceTagUrl: "{{ url_for('utils.export_by_service_tag') }}"
  };
</script>
<script src="{{ url_for('static', filename='js/dashboard.js') }}?v={{ range(1, 100000) | random }}"></script>
<script src="{{ url_for('static', filename='vendor/axios/axios.min.js') }}"></script>
<script>
  (function () {
    const backupForm = document.getElementById('backupFilesForm');
    const folderSelect = document.getElementById('backupTargetFolder');
    const folderInput = document.getElementById('backupPrefixInput');
    if (!folderSelect || !folderInput) return;

    function syncBackupFolderInput() {
      const isNewFolder = folderSelect.value === '__new__';
      folderInput.disabled = !isNewFolder;
      folderInput.placeholder = isNewFolder ? 'PO로 시작하는 새 폴더명' : '선택한 기존 폴더에 저장됩니다';
      if (!isNewFolder) folderInput.value = '';
    }

    folderSelect.addEventListener('change', syncBackupFolderInput);
    if (backupForm) {
      backupForm.addEventListener('submit', function (event) {
        if (folderSelect.value !== '__new__') return;

        const folderName = folderInput.value.trim();
        if (!folderName.startsWith('PO')) {
          event.preventDefault();
          alert('새 백업 폴더명은 PO로 시작해야 합니다.');
          folderInput.focus();
        }
      });
    }
    syncBackupFolderInput();
  })();

  // ── 서비스태그 ZIP 다운로드 모달 ──────────────────────────────────
  (function () {
    const modal = document.getElementById('serviceTagZipModal');
    if (!modal) return;

    // 직접 입력 라인 카운트
    const tagsInput = document.getElementById('serviceTagsInput');
    const lineCountBadge = document.getElementById('serviceTagLineCount');
    tagsInput.addEventListener('input', function () {
      const count = this.value.split('\n').filter(l => l.trim()).length;
      lineCountBadge.textContent = count + '개';
    });

    // 파일 선택 → 미리보기
    const fileInput = document.getElementById('serviceTagsFile');
    fileInput.addEventListener('change', function () {
      const file = this.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = function (e) {
        const content = e.target.result;
        const lines = content.split('\n').filter(l => l.trim());
        document.getElementById('fileTagCount').textContent = lines.length + '개';
        document.getElementById('filePreviewContent').textContent = content.slice(0, 2000);
        document.getElementById('filePreviewArea').classList.remove('d-none');
      };
      reader.readAsText(file, 'utf-8');
    });

    // 라디오 → 패널 전환
    document.querySelectorAll('input[name="stInputMode"]').forEach(function (radio) {
      radio.addEventListener('change', function () {
        document.getElementById('stab-manual').classList.toggle('d-none', this.value !== 'manual');
        document.getElementById('stab-file').classList.toggle('d-none', this.value !== 'file');
      });
    });

    // 모달 열릴 때 초기화
    modal.addEventListener('show.bs.modal', function () {
      document.getElementById('serviceTagResult').classList.add('d-none');
      document.getElementById('serviceTagResultContent').innerHTML = '';
      document.getElementById('serviceTagZipName').value = '';
      document.getElementById('stModeManual').checked = true;
      document.getElementById('stab-manual').classList.remove('d-none');
      document.getElementById('stab-file').classList.add('d-none');
    });

    // ZIP 다운로드 버튼
    document.getElementById('btnDoServiceTagZip').addEventListener('click', async function () {
      const isFileMode = document.getElementById('stModeFile').checked;

      // 파일명 검증
      const zipNameRaw = document.getElementById('serviceTagZipName').value.trim();
      if (!zipNameRaw) {
        document.getElementById('serviceTagZipName').focus();
        document.getElementById('serviceTagZipName').classList.add('is-invalid');
        return;
      }
      document.getElementById('serviceTagZipName').classList.remove('is-invalid');
      // 파일명에 사용 불가 문자 제거
      const zipName = zipNameRaw.replace(/[\\/:*?"<>|]/g, '_');

      const formData = new FormData();
      formData.append('csrf_token', window.APP_CONFIG.csrfToken);
      formData.append('zip_name', zipName);

      if (isFileMode) {
        const file = fileInput.files[0];
        if (!file) { alert('파일을 선택하세요.'); return; }
        formData.append('tag_file', file);
      } else {
        const text = tagsInput.value.trim();
        if (!text) { alert('서비스태그를 입력하세요.'); return; }
        formData.append('service_tags', text);
      }

      const btn = this;
      const origHTML = btn.innerHTML;
      btn.disabled = true;
      btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>검색 중...';

      const resultArea = document.getElementById('serviceTagResult');
      const resultContent = document.getElementById('serviceTagResultContent');
      resultArea.classList.add('d-none');

      try {
        const resp = await fetch(window.APP_CONFIG.exportServiceTagUrl, {
          method: 'POST',
          body: formData
        });

        if (resp.ok) {
          // 헤더에서 결과 정보 추출
          const foundCount = resp.headers.get('X-Found-Count') || '?';
          const notFoundCount = resp.headers.get('X-Not-Found-Count') || '0';
          const notFoundTags = resp.headers.get('X-Not-Found-Tags') || '';

          // Blob 다운로드 (사용자 입력 파일명 사용)
          const blob = await resp.blob();
          const downloadFilename = zipName.endsWith('.zip') ? zipName : zipName + '.zip';

          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = downloadFilename;
          document.body.appendChild(a);
          a.click();
          a.remove();
          URL.revokeObjectURL(url);

          // 결과 표시
          let html = `<div class="alert alert-success mb-2 py-2">
            <i class="bi bi-check-circle me-1"></i>
            <strong>${foundCount}개</strong> 파일이 ZIP에 포함되었습니다.
          </div>`;
          if (notFoundTags) {
            const tagList = notFoundTags.split(',').map(t => `<code class="me-1">${t}</code>`).join('');
            html += `<div class="alert alert-warning mb-0 py-2" style="font-size:0.85rem;">
              <i class="bi bi-exclamation-triangle me-1"></i>
              <strong>${notFoundCount}개</strong> 태그를 찾지 못했습니다: ${tagList}
            </div>`;
          }
          resultContent.innerHTML = html;
          resultArea.classList.remove('d-none');

        } else {
          // JSON 오류 응답
          let errMsg = '알 수 없는 오류';
          try {
            const data = await resp.json();
            errMsg = data.error || errMsg;
            if (data.not_found && data.not_found.length) {
              errMsg += '\n\n없는 태그: ' + data.not_found.join(', ');
            }
          } catch (_) {}
          resultContent.innerHTML = `<div class="alert alert-danger mb-0 py-2">
            <i class="bi bi-x-circle me-1"></i>${errMsg.replace(/\n/g, '<br>')}
          </div>`;
          resultArea.classList.remove('d-none');
        }
      } catch (e) {
        resultContent.innerHTML = `<div class="alert alert-danger mb-0 py-2">
          <i class="bi bi-x-circle me-1"></i>요청 오류: ${e.message}
        </div>`;
        resultArea.classList.remove('d-none');
      } finally {
        btn.disabled = false;
        btn.innerHTML = origHTML;
      }
    });
  })();
  // ──────────────────────────────────────────────────────────────────

  async function runControl(action) {
    // 메인 IP 입력란('ips')에서 값을 가져옴
    const ipText = document.getElementById("ips").value.trim();
    if (!ipText) {
      alert("IP 처리에 입력된 IP 주소가 없습니다.\n먼저 'IP 처리' 카드에 IP를 입력해주세요.");
      document.getElementById("ips").focus();
      return;
    }

    if (!confirm(`정말로 ${action} 작업을 진행하시겠습니까?`)) return;

    // Simple loading indicator (can be improved)
    const btn = event.target.closest('button');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 처리중...';

    try {
      const response = await axios.post(window.APP_CONFIG.systemControlUrl, {
        action: action,
        ips: ipText.split("\n").filter(ip => ip.trim() !== "")
      }, {
        headers: {
          'X-CSRFToken': window.APP_CONFIG.csrfToken
        }
      });

      if (response.data.success) {
        alert("작업 완료: " + response.data.message);
      } else {
        alert("오류 발생: " + response.data.error);
      }
    } catch (error) {
      alert("서버 통신 오류: " + (error.response?.data?.error || error.message));
    } finally {
      btn.disabled = false;
      btn.innerHTML = originalText;
    }
  }
</script>

<!-- SortableJS for Drag and Drop -->
<script src="{{ url_for('static', filename='vendor/sortablejs/Sortable.min.js') }}"></script>

<!-- 슬롯 우선순위 설정 모달 (Premium Design) -->
<div class="modal fade" id="slotPriorityModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered modal-xl">
    <div class="modal-content border-0 shadow-lg" style="border-radius: 1rem; overflow: hidden;">

      <!-- 헤더: 깔끔한 모던 스타일 -->
      <div class="modal-header border-bottom p-4 bg-white">
        <div>
          <h5 class="modal-title fw-bold text-dark mb-1">
            <i class="bi bi-layers text-primary me-2"></i>GUID 슬롯 우선순위 설정
          </h5>
          <p class="mb-0 text-muted" style="font-size: 0.85rem;">
            엑셀 변환 시 적용될 슬롯의 순서를 설정합니다.
          </p>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
      </div>

      <div class="modal-body p-0 bg-light">
        <form id="slotPriorityForm" action="{{ url_for('utils.update_guid_list') }}" method="post">
          <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
          <input type="hidden" name="server_list_content" id="modal_server_list_content">
          <input type="hidden" name="slot_priority" id="slot_priority_input">

          <div class="row g-0">
            <!-- 왼쪽: 입력 및 프리셋 -->
            <div class="col-lg-5 border-end bg-white p-4 d-flex flex-column">
              <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="fw-bold text-dark mb-0 small text-uppercase">
                  <i class="bi bi-keyboard me-1"></i>슬롯 번호 입력
                </h6>
              </div>

              <div class="position-relative flex-grow-1">
                <textarea id="slotNumbersInput"
                  class="form-control bg-light border-0 font-monospace p-3 text-dark h-100"
                  style="resize: none; font-size: 0.9rem; min-height: 200px;"
                  placeholder="슬롯 번호를 입력하세요.&#10;구분자: 쉼표(,) 공백( ) 줄바꿈&#10;&#10;예시: 38, 39, 37"></textarea>

                <div class="position-absolute bottom-0 end-0 p-2">
                  <button type="button" id="btnClearSlots" class="btn btn-sm btn-link text-decoration-none text-muted"
                    style="font-size: 0.75rem;">
                    <i class="bi bi-x-circle me-1"></i>지우기
                  </button>
                </div>
              </div>

              <!-- 미니멀한 프리셋 설정 (숫자 입력) -->
              <div class="mt-3 pt-3 border-top border-light d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center">
                  <span class="small text-muted me-2" style="font-size: 0.75rem;">카드 개수 설정:</span>
                  <div class="input-group input-group-sm" style="width: 120px;">
                    <span class="input-group-text bg-white border-end-0 text-muted"
                      style="font-size: 0.75rem;">개수</span>
                    <input type="number" id="presetCountInput" class="form-control border-start-0 text-center"
                      value="10" min="1" max="10" style="font-size: 0.8rem;">
                  </div>
                </div>
                <button type="button" id="btnApplyPreset" class="btn btn-sm btn-outline-primary rounded-pill px-3"
                  style="font-size: 0.75rem;">
                  적용
                </button>
              </div>
            </div>

            <!-- 오른쪽: 시각화 및 확인 -->
            <div class="col-lg-7 p-4 bg-light d-flex flex-column">
              <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="fw-bold text-secondary mb-0 small text-uppercase">
                  <i class="bi bi-sort-numeric-down me-1"></i>적용 순서
                </h6>
                <span class="badge bg-white text-dark border rounded-pill px-3 py-1" id="slotCountDisplay">0개</span>
              </div>

              <!-- 미리보기 영역 -->
              <div class="flex-grow-1 bg-white border rounded-3 p-4 shadow-sm mb-4 position-relative"
                style="min-height: 250px; max-height: 400px; overflow-y: auto;">
                <div id="slotPreview" class="d-flex flex-wrap gap-2 align-content-start h-100">
                  <!-- Empty State -->
                  <div
                    class="d-flex flex-column align-items-center justify-content-center w-100 h-100 text-muted opacity-50">
                    <i class="bi bi-layers fs-1 mb-2"></i>
                    <span class="small">프리셋을 선택하거나 번호를 입력하세요.</span>
                  </div>
                </div>
              </div>

              <div class="mt-auto">
                <div class="d-flex align-items-center mb-3">
                  <i class="bi bi-info-circle text-primary me-2"></i>
                  <span class="small text-muted">입력된 순서대로 <strong>GUID 컬럼</strong>과 <strong>슬롯 데이터</strong>가
                    정렬됩니다.</span>
                </div>

                <button type="submit" class="btn btn-primary w-100 py-2 fw-semibold shadow-sm">
                  설정 확인 및 변환
                </button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- 중복 파일 확인 모달 -->
<div class="modal fade" id="duplicateCheckModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header border-bottom-0 pb-0">
        <h5 class="modal-title fw-bold text-warning">
          <i class="bi bi-exclamation-triangle-fill me-2"></i>중복 파일 발견
        </h5>
      </div>
      <div class="modal-body pt-3">
        <p class="text-secondary mb-3">
          대상 폴더에 이미 동일한 이름의 파일이 <strong id="dupCount" class="text-dark">0</strong>개 존재합니다.<br>
          덮어쓰시겠습니까?
        </p>
        <div class="bg-light rounded p-3 mb-3 border font-monospace text-muted small"
          style="max-height: 150px; overflow-y: auto;">
          <ul id="dupList" class="list-unstyled mb-0">
            <!-- JS로 주입됨 -->
          </ul>
          <div id="dupMore" class="text-center mt-2 fst-italic display-none" style="display:none;">...외 <span
              id="dupMoreCount">0</span>개</div>
        </div>
        <p class="small text-muted mb-0">
          <i class="bi bi-info-circle me-1"></i>덮어쓰기를 선택하면 기존 파일은 삭제됩니다.
        </p>
      </div>
      <div class="modal-footer border-top-0 pt-0">
        <button type="button" class="btn btn-light" data-bs-dismiss="modal">취소</button>
        <button type="button" class="btn btn-warning text-white fw-bold" id="btnConfirmOverwrite">
          <i class="bi bi-arrow-repeat me-1"></i>덮어쓰기 (Overwrite)
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Styles moved to index_custom.css -->

<!-- Scripts moved to index_custom.js -->
{% endblock %}
