<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <meta name="robots" content="noindex, nofollow" />
  <title>NasifyTech後台管理系統</title>
  <script async src="https://www.googletagmanager.com/gtag/js?id=G-286HZQTWFH"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-286HZQTWFH');
  </script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <style>
    *, *::before, *::after {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      --primary-color: #333;
      --secondary-color: #555;
      --accent-color: #ae7d2f;
      --background-color: #f9f9f9;
      --header-height: 70px;
      --transition-speed: 0.3s;
      --font-family-primary: 'Noto Sans TC', sans-serif;
      --font-family-secondary: 'Exo 2', sans-serif;
    }

    body {
      font-family: var(--font-family-primary);
      color: var(--primary-color);
      background-color: #fff;
      line-height: 1.6;
      overflow-x: hidden;
    }

    a {
      color: var(--primary-color);
      text-decoration: none;
      transition: color var(--transition-speed) ease;
    }
    a:hover {
      color: var(--secondary-color);
    }

    img {
      max-width: 100%;
      height: auto;
      display: block;
      margin: 0 auto;
    }

    header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background: rgba(255, 255, 255, 0.95);
      padding: 15px 0;
      z-index: 1000;
      transition: background var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    header.scrolled {
      background: #fff;
      box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    }

    .container {
      width: 90%;
      max-width: 1200px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
    }

    header h1 {
      font-family: var(--font-family-secondary);
      font-size: 1.8em;
      color: var(--primary-color);
      transition: color var(--transition-speed) ease;
    }

    nav ul {
      list-style: none;
      display: flex;
      gap: 20px;
      align-items: center;
    }
    nav ul li a {
      font-size: 1em;
      font-weight: 600;
      position: relative;
      padding: 5px 0;
      color: var(--primary-color);
      display: flex;
      align-items: center;
      gap: 8px;
    }
    nav ul li a::after {
      content: '';
      position: absolute;
      width: 0%;
      height: 2px;
      background: var(--primary-color);
      left: 0;
      bottom: -2px;
      transition: width var(--transition-speed) ease;
    }
    nav ul li a:hover::after {
      width: 100%;
    }

    .menu-toggle {
      display: none;
      flex-direction: column;
      justify-content: space-between;
      width: 25px;
      height: 20px;
      cursor: pointer;
    }
    .menu-toggle div {
      width: 100%;
      height: 3px;
      background: var(--primary-color);
      border-radius: 1.5px;
      transition: all var(--transition-speed) ease;
    }
    .menu-toggle.active div:nth-child(1) {
      transform: rotate(45deg) translate(5px, 5px);
    }
    .menu-toggle.active div:nth-child(2) {
      opacity: 0;
    }
    .menu-toggle.active div:nth-child(3) {
      transform: rotate(-45deg) translate(5px, -5px);
    }

    .admin-content {
      padding-top: 140px;
      width: 90%;
      max-width: 1200px;
      margin: 0 auto;
      overflow-x: auto;
    }

    .section-title {
      margin-bottom: 20px;
    }

    .section-title h2 {
      font-size: 1.5em;
      margin-bottom: 10px;
    }

    .section-title p {
      font-size: 1em;
      color: var(--secondary-color);
    }

    .filters, .toggle-buttons {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }

    .filters input, .filters select {
      padding: 8px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      font-size: 1em;
    }

    .logout-button,
    .export-btn,
    .add-item-btn,
    .delete-btn,
    .edit-btn,
    .toggle-btn,
    .template-btn { /* 包含 template-btn */
      display: inline-block;
      margin: 10px 10px 10px 0;
      padding: 10px 20px;
      border: none;
      background: var(--primary-color);
      color: #fff;
      cursor: pointer;
      border-radius: 4px;
      transition: background var(--transition-speed) ease, transform 0.2s ease;
      font-size: 1em;
    }
    .logout-button:hover,
    .export-btn:hover,
    .add-item-btn:hover,
    .delete-btn:hover,
    .edit-btn:hover,
    .toggle-btn:hover,
    .template-btn:hover { /* 包含 template-btn */
      background: var(--secondary-color);
      transform: scale(1.05);
    }

    .admin-table {
      width: 100%;
      font-size: 0.9em;
      border-collapse: collapse;
      table-layout: fixed;
      min-width: 800px;
    }

    .admin-table th, .admin-table td {
      vertical-align: middle;
      text-align: left;
      padding: 12px 15px;
      border: 1px solid #ddd;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }

    .admin-table th {
      background: #f0f0f0;
      font-weight: 600;
      position: sticky;
      top: 0;
      z-index: 2;
      user-select: none;
    }

    .admin-table th.sortable:hover {
      background: #e0e0e0;
    }

    .admin-table th .sort-indicator {
      margin-left: 5px;
      font-size: 0.8em;
    }

    .admin-table tbody tr:nth-child(even) {
      background-color: #fafafa;
    }

    .admin-table tbody tr:hover {
      background-color: #f1f1f1;
    }

    .admin-table td.actions {
      display: flex;
      gap: 4px;
      min-width: 80px;
      position: sticky;
      right: 0;
      background: inherit;
      z-index: 1;
    }

    .admin-table .edit-btn,
    .admin-table .delete-btn {
      padding: 4px 8px;
      font-size: 0.8em;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background var(--transition-speed) ease, transform 0.2s ease;
    }

    .admin-table .edit-btn {
      background-color: #4CAF50;
      color: #fff;
    }

    .admin-table .edit-btn:hover {
      background-color: #45a049;
      transform: scale(1.05);
    }

    .admin-table .delete-btn {
      background-color: #f44336;
      color: #fff;
    }

    .admin-table .delete-btn:hover {
      background-color: #da190b;
      transform: scale(1.05);
    }

    .status-active {
      background-color: #d0f3d0;
    }
    .status-inactive,
    .status-deleted {
      background-color: #fbdada;
    }
    .status-rejected {
      background-color: #ffe5e5;
    }

    /* 新增批次匯入輸入框的樣式 */
    .batch-import-section {
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      background-color: #f9f9f9;
    }
    .batch-import-section textarea {
      width: 100%;
      height: 100px;
      padding: 8px;
      font-size: 1em;
      border: 1px solid #ccc;
      border-radius: 4px;
      resize: vertical;
    }
    .batch-import-section button {
      margin-top: 10px;
      padding: 10px 20px;
      background-color: #28a745;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background var(--transition-speed) ease, transform 0.2s ease;
      font-size: 1em;
    }
    .batch-import-section button:hover {
      background-color: #218838;
      transform: scale(1.05);
    }

    @media (max-width: 1024px) {
      .menu-toggle {
        display: flex;
      }
      nav ul {
        flex-direction: column;
        align-items: center;
        background: rgba(255, 255, 255, 0.95);
        position: absolute;
        top: var(--header-height);
        right: 0;
        width: 220px;
        display: none;
        padding: 20px 0;
        border-radius: 0 0 8px 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      }
      nav ul.active {
        display: flex;
        max-height: calc(100vh - var(--header-height));
        overflow-y: auto;
      }
    }

    @media (max-width: 768px) {
      .filters, .toggle-buttons {
        flex-direction: column;
      }
      .admin-table th, .admin-table td {
        padding: 8px 10px;
        font-size: 0.85em;
      }
      .logout-button,
      .export-btn,
      .add-item-btn,
      .delete-btn,
      .edit-btn,
      .toggle-btn,
      .template-btn { /* 包含 template-btn */
        width: 100%;
        text-align: center;
      }
    }

    #contentModal {
      display: none;
      position: fixed;
      z-index: 3000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0,0,0,0.5);
    }

    #contentModal .modal-content {
      background-color: #fefefe;
      margin: 10% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 400px;
      border-radius: 8px;
    }

    #contentModal .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    #contentModal .close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    #contentModal .close:hover,
    #contentModal .close:focus {
      color: black;
      text-decoration: none;
    }

    #contentModal .modal-body {
      font-size: 1em;
      word-wrap: break-word;
    }

    .modal {
      display: none;
      position: fixed;
      z-index: 2000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 10% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 600px;
      border-radius: 8px;
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
    }

    .modal form {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .modal form input,
    .modal form select,
    .modal form textarea {
      padding: 8px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      font-size: 1em;
      width: 100%;
    }

    .modal form button {
      padding: 10px;
      border: none;
      background: var(--accent-color);
      color: #fff;
      cursor: pointer;
      border-radius: 4px;
      transition: background var(--transition-speed) ease;
      font-size: 1em;
    }

    .modal form button:hover {
      background: #c89a2f;
    }
    .template-btn {
      background: #007bff;
      color: #fff;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      transition: background var(--transition-speed) ease, transform 0.2s ease;
      font-size: 1em;
    }
    .template-btn:hover {
      background: #0056b3;
      transform: scale(1.05);
    }
    .btn-close {
      background: none;
      border: none;
      font-size: 1.5rem;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <header>
    <div class="container">
      <h1>NasifyTech管理系統</h1>
      <nav>
        <ul>
        </ul>
        <div class="menu-toggle">
          <div></div>
          <div></div>
          <div></div>
        </div>
      </nav>
    </div>
  </header>

  <section class="admin-content" id="adminContent" style="display: none;">
    <div class="section-title">
      <h2 id="pageTitle">客戶資料管理</h2>
      <p>Nasify Tech 客戶資料管理系統</p>
    </div>
    <div class="toggle-buttons">
      <button type="button" class="toggle-btn btn btn-primary" id="toggleCustomerDataBtn">客戶資料</button>
      <button type="button" class="toggle-btn btn btn-secondary" id="toggleOtherDataBtn">其他使用者資料</button>
      <button type="button" class="toggle-btn btn btn-success" id="toggleTTVSUsersBtn">TTVS 測驗系統會員資料</button>
      <button type="button" class="toggle-btn btn btn-danger" id="toggleOfficialContactBtn">官方聯絡表單回覆</button>
    </div>
    <div class="filters" id="customerFilters">
      <div>
        <label>開始日期：</label>
        <input type="date" id="startDate" class="form-control">
      </div>
      <div>
        <label>結束日期：</label>
        <input type="date" id="endDate" class="form-control">
      </div>
      <div>
        <label>關鍵字搜尋：</label>
        <input type="text" id="searchInput" class="form-control" placeholder="輸入任意關鍵字...">
      </div>
      <button type="button" class="export-btn btn btn-info" id="exportCsvBtn">匯出 CSV</button>
      <button type="button" class="template-btn btn btn-warning" id="downloadTemplateBtn">CSV模板</button>
      <button type="button" class="logout-button btn btn-dark" id="logoutBtn">登出</button>
    </div>
    <div class="filters" id="officialContactFilters" style="display: none;">
      <input type="text" id="filterName" class="form-control" placeholder="篩選姓名">
      <input type="text" id="filterSubject" class="form-control" placeholder="篩選主題">
      <input type="text" id="filterEmail" class="form-control" placeholder="篩選 Email">
      <button type="button" class="export-btn btn btn-info" id="exportOfficialContactCsvBtn">匯出 CSV</button>
    </div>
    <div style="overflow-x: auto;" id="customerTableContainer">
      <div class="filters" style="margin-top: 10px;">
        <button type="button" class="add-item-btn btn btn-success" id="addItemBtn">新增資料</button>
      </div>

      <table class="admin-table table table-bordered table-striped" id="dataTable">
        <thead>
          <tr id="tableHeaderRow">
          </tr>
        </thead>
        <tbody id="dataTableBody">
        </tbody>
      </table>
      <div class="batch-import-section" id="batchImportSection" style="display: none;">
        <label for="batchImportInput">批次匯入資料（每筆資料以逗號分隔，每行一筆）：</label>
        <textarea id="batchImportInput" class="form-control" placeholder="例如：example1@example.com,user123,姓名1,已驗證,活躍,2025-01-21&#10;example2@example.com,user124,姓名2,未驗證,已停用,2025-01-22"></textarea>
        <button type="button" class="btn btn-primary" id="batchImportBtn">開始批次匯入</button>
        <div id="batchImportFeedback" class="alert d-none" role="alert"></div>
      </div>
    </div>
    <div style="overflow-x: auto; display: none;" id="officialContactTableContainer">
      <div class="filters" style="margin-top: 10px;">
        <button type="button" class="logout-button btn btn-dark" id="logoutOfficialContactBtn">登出</button>
      </div>

      <table class="admin-table table table-bordered table-striped" id="officialContactTable">
        <thead>
          <tr>
            <th>姓名</th>
            <th>主題</th>
            <th>Email</th>
            <th>訊息</th>
            <th>送出時間</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="officialContactTableBody">
        </tbody>
      </table>
    </div>
    <div id="editModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h2 id="modalTitle">編輯資料</h2>
          <span class="close" id="closeModal">&times;</span>
        </div>
        <form id="editForm">
          <input type="hidden" id="recordKey" name="recordKey">
          <div id="editCustomerFields" style="display: none;">
            <div id="editCustomerIdGroup" style="display: none;">
              <label for="editCustomerId">客戶編號:</label>
              <input type="text" id="editCustomerId" name="editCustomerId" class="form-control" readonly />
            </div>

            <div>
              <label for="editName">姓名:</label>
              <input type="text" id="editName" name="editName" class="form-control">
            </div>

            <div>
              <label for="editPhone">電話:</label>
              <input type="text" id="editPhone" name="editPhone" class="form-control">
            </div>

            <div>
              <label for="editInstagram">Instagram:</label>
              <input type="text" id="editInstagram" name="editInstagram" class="form-control">
            </div>

            <div>
              <label for="editLine">LINE ID:</label>
              <input type="text" id="editLine" name="editLine" class="form-control">
            </div>

            <div>
              <label for="editEmail">EMAIL:</label>
              <input type="email" id="editEmail" name="editEmail" class="form-control">
            </div>

            <div>
              <label for="editIdNo">身分證字號:</label>
              <input type="text" id="editIdNo" name="editIdNo" class="form-control">
            </div>

            <div>
              <label for="editBirthday">生日:</label>
              <input type="date" id="editBirthday" name="editBirthday" class="form-control">
            </div>

            <div>
              <label for="editAddress">住址:</label>
              <input type="text" id="editAddress" name="editAddress" class="form-control">
            </div>

            <div>
              <label for="editNote">附註(或銀行帳戶):</label>
              <textarea id="editNote" name="editNote" class="form-control"></textarea>
            </div>

            <div id="editCustomerStatusGroup" style="display: none;">
              <label for="editCustomerStatus">客戶狀態:</label>
              <select id="editCustomerStatus" name="editCustomerStatus" class="form-control">
                <option value="活躍">活躍</option>
                <option value="非活躍">非活躍</option>
                <option value="拒絕往來戶">拒絕往來戶</option>
              </select>
            </div>
          </div>
          <div id="editOtherUsersFields" style="display: none;">
            <div>
              <label for="editOtherName">姓名:</label>
              <input type="text" id="editOtherName" name="editOtherName" class="form-control">
            </div>

            <div>
              <label for="editOtherPhone">電話:</label>
              <input type="text" id="editOtherPhone" name="editOtherPhone" class="form-control">
            </div>

            <div>
              <label for="editOtherInstagram">Instagram:</label>
              <input type="text" id="editOtherInstagram" name="editOtherInstagram" class="form-control">
            </div>

            <div>
              <label for="editOtherLine">LINE ID:</label>
              <input type="text" id="editOtherLine" name="editOtherLine" class="form-control">
            </div>

            <div>
              <label for="editOtherEmail">EMAIL:</label>
              <input type="email" id="editOtherEmail" name="editOtherEmail" class="form-control">
            </div>

            <div>
              <label for="editOtherIdNo">身分證字號:</label>
              <input type="text" id="editOtherIdNo" name="editOtherIdNo" class="form-control">
            </div>

            <div>
              <label for="editOtherBirthday">生日:</label>
              <input type="date" id="editOtherBirthday" name="editOtherBirthday" class="form-control">
            </div>

            <div>
              <label for="editOtherAddress">住址:</label>
              <input type="text" id="editOtherAddress" name="editOtherAddress" class="form-control">
            </div>

            <div>
              <label for="editOtherNote">附註(銀行帳戶):</label>
              <textarea id="editOtherNote" name="editOtherNote" class="form-control"></textarea>
            </div>
          </div>
          <div id="editTTVSFields" style="display: none;">
            <div>
              <label for="editTTVSEmail">Email:</label>
              <input type="email" id="editTTVSEmail" name="editTTVSEmail" class="form-control">
            </div>
            <div>
              <label for="editTTVSUserId">使用者ID:</label>
              <input type="text" id="editTTVSUserId" name="editTTVSUserId" class="form-control">
            </div>
            <div>
              <label for="editTTVSName">姓名:</label>
              <input type="text" id="editTTVSName" name="editTTVSName" class="form-control">
            </div>
            <div>
              <label for="editTTVSVerificationStatus">驗證狀態:</label>
              <select id="editTTVSVerificationStatus" name="editTTVSVerificationStatus" class="form-control">
                <option value="未驗證">未驗證</option>
                <option value="已驗證">已驗證</option>
              </select>
            </div>
            <div>
              <label for="editTTVSAccountStatus">帳號狀態:</label>
              <select id="editTTVSAccountStatus" name="editTTVSAccountStatus" class="form-control">
                <option value="活躍">活躍</option>
                <option value="已停用">已停用</option>
                <option value="已刪除">已刪除</option>
              </select>
            </div>
            <div id="editTTVSChangeDateGroup">
              <label for="editTTVSChangeDate">更變日期:</label>
              <input type="date" id="editTTVSChangeDate" name="editTTVSChangeDate" class="form-control" readonly>
            </div>
          </div>
          <div id="editOfficialContactFields" style="display: none;">
            <label for="ocName">姓名:</label>
            <input type="text" id="ocName" name="ocName" class="form-control">
            
            <label for="ocSubject">主題:</label>
            <input type="text" id="ocSubject" name="ocSubject" class="form-control">
            
            <label for="ocEmail">Email:</label>
            <input type="email" id="ocEmail" name="ocEmail" class="form-control">
            
            <label for="ocMessage">訊息:</label>
            <textarea id="ocMessage" name="ocMessage" rows="4" class="form-control"></textarea>
          </div>

          <button type="submit" class="btn btn-primary mt-3">保存</button>
        </form>
      </div>
    </div>

    <!-- 內容模態框 -->
    <div id="contentModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>完整內容</h2>
          <span class="close" id="closeContentModal">&times;</span>
        </div>
        <div class="modal-body" id="modalContentBody">
        </div>
      </div>
    </div>
  </section>

  <!-- Firebase 和 Bootstrap JS -->
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-app-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-auth-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-database-compat.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

  <script>
    const firebaseConfig = {
      apiKey: "AIzaSyCknahg0vqFDiFYDQM1YkS4Sa6j4Eth7ro",
      authDomain: "nasirsweb.firebaseapp.com",
      databaseURL: "https://nasirsweb-default-rtdb.firebaseio.com",
      projectId: "nasirsweb",
      storageBucket: "nasirsweb.firebasestorage.app",
      appId: "1:472577461049:web:00b9cab35ce7b7401bf6e8",
      measurementId: "G-7HZ5KWXJGP"
    };
    firebase.initializeApp(firebaseConfig);
    const auth = firebase.auth();
    const db = firebase.database();

    const allowedEmails = ["it@nasify.org", "nasir.lin@msa.hinet.net"];

    const adminContent = document.getElementById('adminContent');
    const logoutBtn = document.getElementById('logoutBtn');
    const exportCsvBtn = document.getElementById('exportCsvBtn');
    const downloadTemplateBtn = document.getElementById('downloadTemplateBtn');

    const toggleCustomerDataBtn = document.getElementById('toggleCustomerDataBtn');
    const toggleOtherDataBtn = document.getElementById('toggleOtherDataBtn');
    const toggleTTVSUsersBtn = document.getElementById('toggleTTVSUsersBtn');
    const toggleOfficialContactBtn = document.getElementById('toggleOfficialContactBtn'); // 新增按鈕

    const pageTitle = document.getElementById('pageTitle');

    const addItemBtn = document.getElementById('addItemBtn');
    const dataTable = document.getElementById('dataTable');
    const tableHeaderRow = document.getElementById('tableHeaderRow');
    const dataTableBody = document.getElementById('dataTableBody');

    const officialContactTable = document.getElementById('officialContactTable');
    const officialContactTableBody = document.getElementById('officialContactTableBody');
    const exportOfficialContactCsvBtn = document.getElementById('exportOfficialContactCsvBtn');

    const editModal = document.getElementById('editModal');
    const closeModal = document.getElementById('closeModal');
    const editForm = document.getElementById('editForm');
    const recordKeyInput = document.getElementById('recordKey');

    const editCustomerFields = document.getElementById('editCustomerFields');
    const editCustomerIdGroup = document.getElementById('editCustomerIdGroup');
    const editCustomerIdInput = document.getElementById('editCustomerId');
    const editNameInput = document.getElementById('editName');
    const editPhoneInput = document.getElementById('editPhone');
    const editInstagramInput = document.getElementById('editInstagram');
    const editLineInput = document.getElementById('editLine');
    const editEmailInput = document.getElementById('editEmail');
    const editIdNoInput = document.getElementById('editIdNo');
    const editBirthdayInput = document.getElementById('editBirthday');
    const editAddressInput = document.getElementById('editAddress');
    const editNoteInput = document.getElementById('editNote');
    const editCustomerStatusGroup = document.getElementById('editCustomerStatusGroup');
    const editCustomerStatusSelect = document.getElementById('editCustomerStatus');

    const editOtherUsersFields = document.getElementById('editOtherUsersFields');
    const editOtherNameInput = document.getElementById('editOtherName');
    const editOtherPhoneInput = document.getElementById('editOtherPhone');
    const editOtherInstagramInput = document.getElementById('editOtherInstagram');
    const editOtherLineInput = document.getElementById('editOtherLine');
    const editOtherEmailInput = document.getElementById('editOtherEmail');
    const editOtherIdNoInput = document.getElementById('editOtherIdNo');
    const editOtherBirthdayInput = document.getElementById('editOtherBirthday');
    const editOtherAddressInput = document.getElementById('editOtherAddress');
    const editOtherNoteInput = document.getElementById('editOtherNote');

    const editTTVSFields = document.getElementById('editTTVSFields');
    const editTTVSEmailInput = document.getElementById('editTTVSEmail');
    const editTTVSUserIdInput = document.getElementById('editTTVSUserId');
    const editTTVSNameInput = document.getElementById('editTTVSName');
    const editTTVSVerificationStatusSelect = document.getElementById('editTTVSVerificationStatus');
    const editTTVSAccountStatusSelect = document.getElementById('editTTVSAccountStatus'); // 新增的帳號狀態選擇
    const editTTVSChangeDateInput = document.getElementById('editTTVSChangeDate'); // 新增的更變日期欄位
    const editTTVSChangeDateGroup = document.getElementById('editTTVSChangeDateGroup'); // 更變日期欄位組

    const officialContactFilters = document.getElementById('officialContactFilters');
    const filterName = document.getElementById('filterName');
    const filterSubject = document.getElementById('filterSubject');
    const filterEmail = document.getElementById('filterEmail');

    let currentView = 'customers'; 

    const customerHeaders = [
      { key: 'customerId', label: '客戶編號' },
      { key: 'name', label: '姓名' },
      { key: 'phone', label: '電話' },
      { key: 'instagram', label: 'Instagram' },
      { key: 'lineId', label: 'LINE ID' },
      { key: 'email', label: 'EMAIL' },
      { key: 'idNo', label: '身分證字號' },
      { key: 'birthday', label: '生日' },
      { key: 'address', label: '住址' },
      { key: 'note', label: '附註' },
      { key: 'customerStatus', label: '客戶狀態' },
      { key: 'timestamp', label: '建立時間' }
    ];

    const otherUserHeaders = [
      { key: 'name', label: '姓名' },
      { key: 'phone', label: '電話' },
      { key: 'instagram', label: 'Instagram' },
      { key: 'lineId', label: 'LINE ID' },
      { key: 'email', label: 'EMAIL' },
      { key: 'idNo', label: '身分證字號' },
      { key: 'birthday', label: '生日' },
      { key: 'address', label: '住址' },
      { key: 'note', label: '附註(銀行帳戶)' },
      { key: 'timestamp', label: '建立時間' }
    ];

    const ttvsUserHeaders = [
      { key: 'email', label: 'Email' },
      { key: 'userId', label: '使用者ID' },
      { key: 'name', label: '姓名' },
      { key: 'verificationStatus', label: '驗證狀態' },
      { key: 'accountStatus', label: '帳號狀態' },
      { key: 'changeDate', label: '更變日期' } 
    ];

    const officialContactHeaders = [
      { key: 'name', label: '姓名' },
      { key: 'subject', label: '主題' },
      { key: 'email', label: 'Email' },
      { key: 'message', label: '訊息' },
      { key: 'timestamp', label: '送出時間' }
    ];

    let customersData = {};
    let otherUsersData = {};
    let ttvsUsersData = {};
    let officialContactsData = {};

    let customerIdCounter = 0;
    let currentSortKey = null;
    let currentSortOrder = 'asc'; 
    auth.onAuthStateChanged(user => {
      if (user && user.email && allowedEmails.includes(user.email.toLowerCase())) {
        adminContent.style.display = 'block';
        loadCustomers();
        loadOtherUsers();
        loadTTVSUsers();
        loadOfficialContacts();
      } else {
        window.location.href = '/404.html'; 
      }
    });
    function loadCustomers() {
      const ref = db.ref('customers');
      ref.on('value', snapshot => {
        customersData = snapshot.val() || {};
        updateCustomerIdCounter(customersData);
        if (currentView === 'customers') {
          renderTable();
        }
      });
    }

    function loadOtherUsers() {
      const ref = db.ref('otherUsers');
      ref.on('value', snapshot => {
        otherUsersData = snapshot.val() || {};
        if (currentView === 'otherUsers') {
          renderTable();
        }
      });
    }

    function loadTTVSUsers() {
      const ref = db.ref('ttvsUsers');
      ref.on('value', snapshot => {
        ttvsUsersData = snapshot.val() || {};
        if (currentView === 'ttvsUsers') {
          renderTable();
        }
      });
    }

    function loadOfficialContacts() {
      const ref = db.ref('officialcontact');
      ref.on('value', snapshot => {
        officialContactsData = snapshot.val() || {};
        if (currentView === 'officialContact') {
          renderOfficialContactTable();
        }
      });
    }

    function updateCustomerIdCounter(data) {
      let maxId = 0;
      Object.values(data).forEach(item => {
        if (item.customerId && !isNaN(item.customerId)) {
          const idNum = parseInt(item.customerId, 10);
          if (idNum > maxId) maxId = idNum;
        }
      });
      customerIdCounter = maxId;
    }
    toggleCustomerDataBtn.addEventListener('click', () => {
      currentView = 'customers';
      pageTitle.textContent = '客戶資料管理';
      resetViews();
      customerFilters.style.display = 'flex';
      customerTableContainer.style.display = 'block';
      officialContactTableContainer.style.display = 'none';
      renderTable();
    });

    toggleOtherDataBtn.addEventListener('click', () => {
      currentView = 'otherUsers';
      pageTitle.textContent = '其他使用者資料管理';
      resetViews();
      customerFilters.style.display = 'flex';
      customerTableContainer.style.display = 'block';
      officialContactTableContainer.style.display = 'none';
      renderTable();
    });

    toggleTTVSUsersBtn.addEventListener('click', () => {
      currentView = 'ttvsUsers';
      pageTitle.textContent = 'TTVS 測驗系統會員資料管理';
      resetViews();
      customerFilters.style.display = 'flex';
      customerTableContainer.style.display = 'block';
      officialContactTableContainer.style.display = 'none';
      renderTable();
    });

    toggleOfficialContactBtn.addEventListener('click', () => {
      currentView = 'officialContact';
      pageTitle.textContent = '官方聯絡表單回覆列表';
      resetViews();
      officialContactFilters.style.display = 'flex';
      customerTableContainer.style.display = 'none';
      officialContactTableContainer.style.display = 'block';
      renderOfficialContactTable();
    });

    function resetViews() {

      customerFilters.style.display = 'none';
      officialContactFilters.style.display = 'none';

      customerTableContainer.style.display = 'none';
      officialContactTableContainer.style.display = 'none';

      editCustomerFields.style.display = 'none';
      editOtherUsersFields.style.display = 'none';
      editTTVSFields.style.display = 'none';
      editOfficialContactFields.style.display = 'none';

      batchImportSection.style.display = 'none';
    }

    function renderTable() {
      tableHeaderRow.innerHTML = '';
      dataTableBody.innerHTML = '';

      let headers;
      let isTTVS = false;
      if (currentView === 'customers') {
        headers = customerHeaders;
      } else if (currentView === 'otherUsers') {
        headers = otherUserHeaders;
      } else if (currentView === 'ttvsUsers') {
        headers = ttvsUserHeaders;
        isTTVS = true;
        const indexTh = document.createElement('th');
        indexTh.textContent = '編號';
        tableHeaderRow.appendChild(indexTh);
      }

      headers.forEach(h => {
        const th = document.createElement('th');
        th.textContent = h.label;
        th.classList.add('sortable');
        th.dataset.key = h.key;

        const sortIndicator = document.createElement('span');
        sortIndicator.classList.add('sort-indicator');
        if (currentSortKey === h.key) {
          sortIndicator.textContent = currentSortOrder === 'asc' ? '▲' : '▼';
        }
        th.appendChild(sortIndicator);
        th.addEventListener('click', () => {
          if (currentSortKey === h.key) {
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
          } else {
            currentSortKey = h.key;
            currentSortOrder = 'asc';
          }
          renderTable();
        });

        tableHeaderRow.appendChild(th);
      });

      const actionTh = document.createElement('th');
      actionTh.textContent = '操作';
      tableHeaderRow.appendChild(actionTh);

      let dataObj;
      if (currentView === 'customers') {
        dataObj = customersData;
      } else if (currentView === 'otherUsers') {
        dataObj = otherUsersData;
      } else if (currentView === 'ttvsUsers') {
        dataObj = ttvsUsersData;
      }

      let dataArray = Object.keys(dataObj).map(key => ({ key, ...dataObj[key] }));
      const searchInput = document.getElementById('searchInput').value.trim().toLowerCase();
      const searchKeywords = searchInput.split(/\s+/).filter(keyword => keyword.length > 0);

      dataArray = dataArray.filter(item => {
        let include = true;

        if (currentView !== 'ttvsUsers') {
          const itemTimestamp = item.timestamp ? parseInt(item.timestamp) : null;
          if (startDate && itemTimestamp && itemTimestamp < startDate) {
            include = false;
          }
          if (endDate && itemTimestamp && itemTimestamp > endDate) {
            include = false;
          }
        }
        if (searchKeywords.length > 0) {
          let allFieldsStr = '';
          if (currentView === 'ttvsUsers') {
            allFieldsStr = (item.email + ' ' + item.userId + ' ' + item.name + ' ' + item.verificationStatus + ' ' + (item.accountStatus || '') + ' ' + (item.changeDate || '')).toLowerCase();
          } else {
            allFieldsStr = Object.values(item).map(v => (v + '').toLowerCase()).join(' ');
          }
          const matchesAnyKeyword = searchKeywords.some(keyword => allFieldsStr.includes(keyword));
          if (!matchesAnyKeyword) {
            include = false;
          }
        }

        return include;
      });
      if (currentSortKey) {
        dataArray.sort((a, b) => {
          let aVal = a[currentSortKey] || '';
          let bVal = b[currentSortKey] || '';
          if (currentSortKey === 'timestamp' || currentSortKey === 'birthday' || currentSortKey === 'changeDate') {
            aVal = currentSortKey === 'timestamp' ? parseInt(aVal) : new Date(aVal).getTime();
            bVal = currentSortKey === 'timestamp' ? parseInt(bVal) : new Date(bVal).getTime();
          } else if (currentSortKey === 'customerId') {
            aVal = parseInt(aVal);
            bVal = parseInt(bVal);
          } else {
            aVal = aVal.toString().toLowerCase();
            bVal = bVal.toString().toLowerCase();
          }

          if (aVal < bVal) return currentSortOrder === 'asc' ? -1 : 1;
          if (aVal > bVal) return currentSortOrder === 'asc' ? 1 : -1;
          return 0;
        });
      }

      if (dataArray.length === 0) {
        dataTableBody.innerHTML = '<tr><td colspan="' + (headers.length + (isTTVS ? 2 : 1)) + '">目前沒有資料</td></tr>';
        return;
      }

      let indexCounter = 1;

      dataArray.forEach(item => {
        const tr = document.createElement('tr');

        if (currentView === 'customers') {
          if (item.customerStatus === '活躍') {
            tr.classList.add('status-active');
          } else if (item.customerStatus === '非活躍') {
            tr.classList.add('status-inactive');
          } else if (item.customerStatus === '拒絕往來戶') {
            tr.classList.add('status-rejected');
          }
        } else if (currentView === 'ttvsUsers') {
          if (item.accountStatus === '已停用' || item.accountStatus === '已刪除') {
            tr.classList.add('status-deleted'); 
          }
        }

        if (isTTVS) {
          const indexTd = document.createElement('td');
          indexTd.textContent = indexCounter++;
          tr.appendChild(indexTd);
        }

        headers.forEach(h => {
          const td = document.createElement('td');
          let textValue = item[h.key] || '';

          if (h.key === 'timestamp' && textValue) {
            textValue = new Date(textValue).toLocaleString();
          }
          if (currentView === 'ttvsUsers' && h.key === 'changeDate' && textValue) {
            textValue = new Date(textValue).toLocaleDateString();
          }
          td.textContent = textValue;
          tr.appendChild(td);
        });

        const actionTd = document.createElement('td');
        actionTd.classList.add('actions');

        const editBtn = document.createElement('button');
        editBtn.textContent = '編輯';
        editBtn.classList.add('edit-btn', 'btn', 'btn-sm', 'btn-primary', 'me-2');
        editBtn.type = 'button'; 
        editBtn.addEventListener('click', () => openEditModal(item.key, item, currentView));
        actionTd.appendChild(editBtn);

        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '刪除';
        deleteBtn.classList.add('delete-btn', 'btn', 'btn-sm', 'btn-danger');
        deleteBtn.type = 'button';
        deleteBtn.addEventListener('click', () => deleteRecord(item.key, currentView));
        actionTd.appendChild(deleteBtn);

        tr.appendChild(actionTd);
        dataTableBody.appendChild(tr);
      });

      if (!dataTableBody.hasChildNodes()) {
        dataTableBody.innerHTML = '<tr><td colspan="' + (headers.length + (isTTVS ? 2 : 1)) + '">沒有符合篩選/搜尋的資料</td></tr>';
      }

      addCellClickEvents();
    }
    function renderOfficialContactTable() {
      officialContactTableBody.innerHTML = '';

      const nameFilterValue = filterName.value.toLowerCase();
      const subjectFilterValue = filterSubject.value.toLowerCase();
      const emailFilterValue = filterEmail.value.toLowerCase();

      let hasData = false;

      Object.keys(officialContactsData).forEach(key => {
        const item = officialContactsData[key];
        const name = item.name || '';
        const subject = item.subject || '';
        const email = item.email || '';
        const message = item.message || '';
        const timestamp = item.timestamp ? new Date(item.timestamp).toLocaleString() : '';

        if (
          name.toLowerCase().includes(nameFilterValue) &&
          subject.toLowerCase().includes(subjectFilterValue) &&
          email.toLowerCase().includes(emailFilterValue)
        ) {
          hasData = true;
          const tr = document.createElement('tr');

          const nameTd = document.createElement('td');
          nameTd.textContent = name || '(無名)';
          tr.appendChild(nameTd);

          const subjectTd = document.createElement('td');
          subjectTd.textContent = subject || '(無主題)';
          tr.appendChild(subjectTd);

          const emailTd = document.createElement('td');
          emailTd.textContent = email || '(無 Email)';
          tr.appendChild(emailTd);

          const messageTd = document.createElement('td');
          messageTd.textContent = message || '(無訊息)';
          tr.appendChild(messageTd);

          const timeTd = document.createElement('td');
          timeTd.textContent = timestamp || '(無時間)';
          tr.appendChild(timeTd);
          const actionsTd = document.createElement('td');
          actionsTd.classList.add('actions');

          const editBtn = document.createElement('button');
          editBtn.textContent = '編輯';
          editBtn.classList.add('edit-btn', 'btn', 'btn-sm', 'btn-primary', 'me-2');
          editBtn.type = 'button'; 
          editBtn.addEventListener('click', () => openEditModal(key, item, 'officialContact'));
          actionsTd.appendChild(editBtn);

          const deleteBtn = document.createElement('button');
          deleteBtn.textContent = '刪除';
          deleteBtn.classList.add('delete-btn', 'btn', 'btn-sm', 'btn-danger');
          deleteBtn.type = 'button';
          deleteBtn.addEventListener('click', () => deleteOfficialContactRecord(key));
          actionsTd.appendChild(deleteBtn);

          tr.appendChild(actionsTd);

          officialContactTableBody.appendChild(tr);
        }
      });

      if (!hasData) {
        officialContactTableBody.innerHTML = '<tr><td colspan="6">目前沒有資料</td></tr>';
      }
    }
    addItemBtn.addEventListener('click', () => {
      openEditModal(null, null, currentView);
    });
    function openEditModal(key, item, view) {
      recordKeyInput.value = key || '';
      editForm.reset();
      editCustomerFields.style.display = 'none';
      editOtherUsersFields.style.display = 'none';
      editTTVSFields.style.display = 'none';
      editOfficialContactFields.style.display = 'none';
      batchImportSection.style.display = 'none';

      if (view === 'customers') {
        editCustomerFields.style.display = 'block';
        if (!key) {
          editCustomerIdGroup.style.display = 'none';
        } else {
          editCustomerIdGroup.style.display = 'block';
        }
        editCustomerStatusGroup.style.display = 'block';
      } else if (view === 'otherUsers') {
        editOtherUsersFields.style.display = 'block';
      } else if (view === 'ttvsUsers') {
        editTTVSFields.style.display = 'block';
        if (!key) {
          editTTVSChangeDateGroup.style.display = 'none';
          batchImportSection.style.display = 'block';
        } else {
          editTTVSChangeDateGroup.style.display = 'block';
        }
      } else if (view === 'officialContact') {
        editOfficialContactFields.style.display = 'block';
      }

      if (key && item) {
        if (view === 'customers') {
          editCustomerIdInput.value = item.customerId || '';
          editCustomerStatusSelect.value = item.customerStatus || '活躍';
          editNameInput.value = item.name || '';
          editPhoneInput.value = item.phone || '';
          editInstagramInput.value = item.instagram || '';
          editLineInput.value = item.lineId || '';
          editEmailInput.value = item.email || '';
          editIdNoInput.value = item.idNo || '';
          editBirthdayInput.value = item.birthday || '';
          editAddressInput.value = item.address || '';
          editNoteInput.value = item.note || '';
        } else if (view === 'otherUsers') {
          editOtherNameInput.value = item.name || '';
          editOtherPhoneInput.value = item.phone || '';
          editOtherInstagramInput.value = item.instagram || '';
          editOtherLineInput.value = item.lineId || '';
          editOtherEmailInput.value = item.email || '';
          editOtherIdNoInput.value = item.idNo || '';
          editOtherBirthdayInput.value = item.birthday || '';
          editOtherAddressInput.value = item.address || '';
          editOtherNoteInput.value = item.note || '';
        } else if (view === 'ttvsUsers') {
          editTTVSEmailInput.value = item.email || '';
          editTTVSUserIdInput.value = item.userId || '';
          editTTVSNameInput.value = item.name || '';
          editTTVSVerificationStatusSelect.value = item.verificationStatus || '未驗證';
          editTTVSAccountStatusSelect.value = item.accountStatus || '活躍';
          editTTVSChangeDateInput.value = item.changeDate || '';
        } else if (view === 'officialContact') {
          document.getElementById('ocName').value = item.name || '';
          document.getElementById('ocSubject').value = item.subject || '';
          document.getElementById('ocEmail').value = item.email || '';
          document.getElementById('ocMessage').value = item.message || '';
        }
      }

      editModal.style.display = 'block';
    }

    closeModal.addEventListener('click', () => {
      editModal.style.display = 'none';
    });
    window.addEventListener('click', (event) => {
      if (event.target == editModal) {
        editModal.style.display = 'none';
      }
    });

    editForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const key = recordKeyInput.value;
      const isNew = !key;

      const nowTimestamp = Date.now();
      let updatedData = {};

      if (currentView === 'customers') {
        if (!isNew) {
          updatedData.customerId = editCustomerIdInput.value;
        }
        updatedData.customerStatus = editCustomerStatusSelect.value;

        updatedData.name = editNameInput.value.trim();
        updatedData.phone = editPhoneInput.value.trim();
        updatedData.instagram = editInstagramInput.value.trim();
        updatedData.lineId = editLineInput.value.trim();
        updatedData.email = editEmailInput.value.trim();
        updatedData.idNo = editIdNoInput.value.trim();
        updatedData.birthday = editBirthdayInput.value;
        updatedData.address = editAddressInput.value.trim();
        updatedData.note = editNoteInput.value.trim();
      } else if (currentView === 'otherUsers') {
        updatedData.name = editOtherNameInput.value.trim();
        updatedData.phone = editOtherPhoneInput.value.trim();
        updatedData.instagram = editOtherInstagramInput.value.trim();
        updatedData.lineId = editOtherLineInput.value.trim();
        updatedData.email = editOtherEmailInput.value.trim();
        updatedData.idNo = editOtherIdNoInput.value.trim();
        updatedData.birthday = editOtherBirthdayInput.value;
        updatedData.address = editOtherAddressInput.value.trim();
        updatedData.note = editOtherNoteInput.value.trim();
        updatedData.timestamp = nowTimestamp;
      } else if (currentView === 'ttvsUsers') {
        const ttvsEmail = editTTVSEmailInput.value.trim().toLowerCase();
        const ttvsUserId = editTTVSUserIdInput.value.trim();
        const ttvsName = editTTVSNameInput.value.trim();
        const ttvsVerificationStatus = editTTVSVerificationStatusSelect.value;
        const ttvsAccountStatus = editTTVSAccountStatusSelect.value; 
        let ttvsChangeDate = editTTVSChangeDateInput.value;
        const emailExists = Object.entries(ttvsUsersData).some(([k, user]) => user.email.toLowerCase() === ttvsEmail && k !== key);
        if (emailExists) {
          alert('此 Email 已存在，請使用不同的 Email。');
          return;
        }

        if (!isNew && itemHasChangedAccountStatus(key, ttvsAccountStatus)) {
          ttvsChangeDate = new Date().toISOString().split('T')[0];
        } else if (isNew) {
          ttvsChangeDate = ''; 
        }

        updatedData.email = ttvsEmail;
        updatedData.userId = ttvsUserId;
        updatedData.name = ttvsName;
        updatedData.verificationStatus = ttvsVerificationStatus;
        updatedData.accountStatus = ttvsAccountStatus; 
        updatedData.changeDate = ttvsChangeDate; 
        updatedData.timestamp = nowTimestamp;
      } else if (currentView === 'officialContact') {
        updatedData.name = document.getElementById('ocName').value.trim();
        updatedData.subject = document.getElementById('ocSubject').value.trim();
        updatedData.email = document.getElementById('ocEmail').value.trim();
        updatedData.message = document.getElementById('ocMessage').value.trim();
        updatedData.timestamp = nowTimestamp;
      }

      console.log('Saving data:', { currentView, key, isNew, updatedData });

      try {
        if (isNew) {
          if (currentView === 'customers') {
            updatedData.timestamp = nowTimestamp;
            customerIdCounter++;
            updatedData.customerId = customerIdCounter.toString();
            const ref = db.ref('customers').push();
            await ref.set(updatedData);
            alert('新增成功');
          } else if (currentView === 'otherUsers') {
            updatedData.timestamp = nowTimestamp;
            const ref = db.ref('otherUsers').push();
            await ref.set(updatedData);
            alert('新增成功');
          } else if (currentView === 'ttvsUsers') {
            const ref = db.ref('ttvsUsers').push();
            await ref.set(updatedData);
            alert('新增成功');
          } else if (currentView === 'officialContact') {
            const ref = db.ref('officialcontact').push();
            await ref.set(updatedData);
            alert('新增成功');
          }
        } else {
          if (currentView === 'customers') {
            updatedData.timestamp = nowTimestamp;
            await db.ref(`customers/${key}`).update(updatedData);
            alert('更新成功');
          } else if (currentView === 'otherUsers') {
            updatedData.timestamp = nowTimestamp;
            await db.ref(`otherUsers/${key}`).update(updatedData);
            alert('更新成功');
          } else if (currentView === 'ttvsUsers') {
            await db.ref(`ttvsUsers/${key}`).update(updatedData);
            alert('更新成功');
          } else if (currentView === 'officialContact') {
            await db.ref(`officialcontact/${key}`).update(updatedData);
            alert('更新成功');
          }
        }
        editModal.style.display = 'none';
      } catch (err) {
        console.error('保存失敗:', err);
        alert('操作失敗，請稍後再試');
      }
    });
    function itemHasChangedAccountStatus(key, newStatus) {
      const item = ttvsUsersData[key];
      if (!item) return false;
      return item.accountStatus !== newStatus;
    }
    function deleteRecord(key, view) {
      if (!confirm('確定要刪除此資料嗎？')) return;

      if (view === 'customers') {
        db.ref(`customers/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(err => {
            console.error(err);
            alert('刪除失敗');
          });
      } else if (view === 'otherUsers') {
        db.ref(`otherUsers/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(err => {
            console.error(err);
            alert('刪除失敗');
          });
      } else if (view === 'ttvsUsers') {
        db.ref(`ttvsUsers/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(err => {
            console.error(err);
            alert('刪除失敗');
          });
      } else if (view === 'officialContact') {
        db.ref(`officialcontact/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(err => {
            console.error(err);
            alert('刪除失敗');
          });
      }
    }
    function deleteOfficialContactRecord(key) {
      if (!confirm('您確定要刪除此記錄嗎？')) return;

      db.ref('officialcontact/' + key).remove()
        .then(() => {
          alert('刪除成功');
        })
        .catch(error => {
          console.error('刪除失敗:', error);
          alert('刪除失敗，請稍後再試');
        });
    }
    exportCsvBtn.addEventListener('click', () => {
      let dataObj;
      let headers;
      let filename;
      let isTTVS = false;
      let isOfficialContact = false;

      if (currentView === 'customers') {
        dataObj = customersData;
        headers = customerHeaders;
        filename = '客戶資料.csv';
      } else if (currentView === 'otherUsers') {
        dataObj = otherUsersData;
        headers = otherUserHeaders;
        filename = '其他使用者資料.csv';
      } else if (currentView === 'ttvsUsers') {
        dataObj = ttvsUsersData;
        headers = ttvsUserHeaders;
        filename = 'TTVS_測驗系統會員資料.csv';
        isTTVS = true;
      } else if (currentView === 'officialContact') {
        dataObj = officialContactsData;
        headers = officialContactHeaders;
        filename = '官方聯絡表單回覆.csv';
        isOfficialContact = true;
      }

      const csvRows = [];
      const headerLabels = headers.map(h => h.label);
      if (isTTVS) {
        headerLabels.unshift('編號');
      }
      csvRows.push(headerLabels.join(','));

      let dataArray = Object.keys(dataObj).map(key => ({ key, ...dataObj[key] }));
      const searchInput = document.getElementById('searchInput').value.trim().toLowerCase();
      const searchKeywords = searchInput.split(/\s+/).filter(keyword => keyword.length > 0);

      dataArray = dataArray.filter(item => {
        let include = true;

        if (currentView !== 'ttvsUsers' && currentView !== 'officialContact') {
          const itemTimestamp = item.timestamp ? parseInt(item.timestamp) : null;
          if (startDate && itemTimestamp && itemTimestamp < startDate) {
            include = false;
          }
          if (endDate && itemTimestamp && itemTimestamp > endDate) {
            include = false;
          }
        }
        if (searchKeywords.length > 0) {
          let allFieldsStr = '';
          if (currentView === 'ttvsUsers') {
            allFieldsStr = (item.email + ' ' + item.userId + ' ' + item.name + ' ' + item.verificationStatus + ' ' + (item.accountStatus || '') + ' ' + (item.changeDate || '')).toLowerCase();
          } else if (currentView === 'officialContact') {
            allFieldsStr = (item.name + ' ' + item.subject + ' ' + item.email + ' ' + item.message).toLowerCase();
          } else {
            allFieldsStr = Object.values(item).map(v => (v + '').toLowerCase()).join(' ');
          }
          const matchesAnyKeyword = searchKeywords.some(keyword => allFieldsStr.includes(keyword));
          if (!matchesAnyKeyword) {
            include = false;
          }
        }

        return include;
      });
      if (currentSortKey) {
        dataArray.sort((a, b) => {
          let aVal = a[currentSortKey] || '';
          let bVal = b[currentSortKey] || '';
          if (currentSortKey === 'timestamp' || currentSortKey === 'birthday' || currentSortKey === 'changeDate') {
            aVal = currentSortKey === 'timestamp' ? parseInt(aVal) : new Date(aVal).getTime();
            bVal = currentSortKey === 'timestamp' ? parseInt(bVal) : new Date(bVal).getTime();
          } else if (currentSortKey === 'customerId') {
            aVal = parseInt(aVal);
            bVal = parseInt(bVal);
          } else {
            aVal = aVal.toString().toLowerCase();
            bVal = bVal.toString().toLowerCase();
          }

          if (aVal < bVal) return currentSortOrder === 'asc' ? -1 : 1;
          if (aVal > bVal) return currentSortOrder === 'asc' ? 1 : -1;
          return 0;
        });
      }

      if (dataArray.length === 0) {
        alert('沒有符合條件的資料可匯出。');
        return;
      }

      dataArray.forEach((item, index) => {
        const row = [];
        if (isTTVS) {
          row.push(index + 1);
        }
        headers.forEach(h => {
          let val = item[h.key] || '';
          if (h.key === 'timestamp' && val) {
            val = new Date(val).toLocaleString();
          }
          if (currentView === 'ttvsUsers' && h.key === 'changeDate' && val) {
            val = new Date(val).toLocaleDateString();
          }
          if (isOfficialContact && h.key === 'timestamp' && val) {
            val = new Date(val).toLocaleString();
          }
          val = val.toString().replace(/"/g, '""');
          row.push(`"${val}"`);
        });
        csvRows.push(row.join(','));
      });

      const csvContent = "\uFEFF" + csvRows.join('\n');
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
    exportOfficialContactCsvBtn.addEventListener('click', () => {
      const csvRows = [];
      const headers = officialContactHeaders.map(h => h.label);
      csvRows.push(headers.join(','));

      Object.keys(officialContactsData).forEach(key => {
        const item = officialContactsData[key];
        const row = [
          `"${item.name ? item.name.replace(/"/g, '""') : ''}"`,
          `"${item.subject ? item.subject.replace(/"/g, '""') : ''}"`,
          `"${item.email ? item.email.replace(/"/g, '""') : ''}"`,
          `"${item.message ? item.message.replace(/"/g, '""') : ''}"`,
          `"${item.timestamp ? new Date(item.timestamp).toLocaleString() : ''}"`
        ];
        csvRows.push(row.join(','));
      });

      const csvContent = "\uFEFF" + csvRows.join('\n'); 
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', 'official_contact_data.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
    const batchImportBtn = document.getElementById('batchImportBtn');
    batchImportBtn.addEventListener('click', async () => {
      const input = document.getElementById('batchImportInput').value.trim();
      if (!input) {
        showBatchImportFeedback('請輸入批次匯入的資料。', 'danger');
        return;
      }

      const lines = input.split('\n');
      let importCount = 0;
      let errorCount = 0;
      const importPromises = lines.map(async (line, index) => {
        const fields = line.split(',').map(field => field.trim());
        if (fields.length < 6) { 
          errorCount++;
          return;
        }

        const [email, userId, name, verificationStatus, accountStatus, changeDate] = fields;

        if (!email || !userId || !name) { 
          errorCount++;
          return;
        }
        const emailExists = Object.entries(ttvsUsersData).some(([k, user]) => user.email.toLowerCase() === email.toLowerCase());
        if (emailExists) {
          errorCount++;
          return;
        }

        const newUser = {
          email: email.toLowerCase(),
          userId,
          name,
          verificationStatus: verificationStatus || '未驗證',
          accountStatus: accountStatus || '活躍',
          changeDate: changeDate || '' 
        };

        try {
          await db.ref('ttvsUsers').push().set(newUser);
          importCount++;
        } catch (err) {
          console.error(err);
          errorCount++;
        }
      });
      await Promise.allSettled(importPromises);

      showBatchImportFeedback(`匯入完成。成功匯入 ${importCount} 筆資料，失敗 ${errorCount} 筆資料。`, errorCount > 0 ? 'warning' : 'success');
      document.getElementById('batchImportInput').value = '';
      loadTTVSUsers(); 
    });

    function showBatchImportFeedback(message, type) {
      const feedback = document.getElementById('batchImportFeedback');
      feedback.textContent = message;
      feedback.className = `alert alert-${type}`;
      feedback.classList.remove('d-none');

      setTimeout(() => {
        feedback.classList.add('d-none');
      }, 7000);
    }
    const logoutOfficialContactBtn = document.getElementById('logoutOfficialContactBtn');
    logoutOfficialContactBtn.addEventListener('click', async () => {
      await auth.signOut();
    });

    const menuToggle = document.querySelector('.menu-toggle');
    const navUl = document.querySelector('nav ul');

    menuToggle.addEventListener('click', () => {
      menuToggle.classList.toggle('active');
      navUl.classList.toggle('active');
    });

    const customerFilters = document.getElementById('customerFilters');
    const customerTableContainer = document.getElementById('customerTableContainer');
    [filterName, filterSubject, filterEmail].forEach(input => {
      input.addEventListener('input', () => {
        if (currentView === 'officialContact') {
          renderOfficialContactTable();
        }
      });
    });
    const contentModal = document.getElementById('contentModal');
    const closeContentModal = document.getElementById('closeContentModal');
    const modalContentBody = document.getElementById('modalContentBody');

    closeContentModal.addEventListener('click', () => {
      contentModal.style.display = 'none';
    });
    window.addEventListener('click', (event) => {
      if (event.target == contentModal) {
        contentModal.style.display = 'none';
      }
    });
    function isTextTruncated(element) {
      return element.scrollWidth > element.clientWidth;
    }
    function addCellClickEvents() {
      const cells = dataTableBody.querySelectorAll('td:not(.actions)');
      cells.forEach(cell => {
        cell.removeEventListener('click', cellClickHandler);
        cell.addEventListener('click', cellClickHandler);
      });

      const officialContactCells = officialContactTableBody.querySelectorAll('td:not(.actions)');
      officialContactCells.forEach(cell => {
        cell.removeEventListener('click', cellClickHandler);
        cell.addEventListener('click', cellClickHandler);
      });
    }

    function cellClickHandler(event) {
      const cell = event.currentTarget;
      if (isTextTruncated(cell)) {
        const content = cell.textContent.trim();
        modalContentBody.textContent = content;
        contentModal.style.display = 'block';
      }
    }
    let debounceTimeout;
    document.getElementById('searchInput').addEventListener('input', () => {
      clearTimeout(debounceTimeout);
      debounceTimeout = setTimeout(() => {
        renderTable();
      }, 300); 
    });

  </script>
</body>
</html>
