<?php
session_start();
include('script/condb.php'); // your DB connection; used only for API file, page doesn't use it directly

/* ---------- Resolve project ID ---------- */
$PID = $_GET['project_ref'] ?? $_POST['pid'] ?? $_SESSION['pid'] ?? '';
if (!empty($PID)) {
    $_SESSION['pid'] = $PID;
}
?>
<!doctype html>
<html>
<head>
    
<meta charset="UTF-8">
<title>TQ Dashboard</title>
<script src="foundation-duplicate.js"></script>
<link href="css/styles.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>

/* Right content area */
.right-frame2 {
  position: absolute;
  left: 130px;
  top: 0;
  width:95%;
  height: auto;
  padding: 20px;
  display: block;
  overflow-x: hidden; /* ensure no horizontal scroll from right-frame */
}

/* White rounded board wrapper (ADDED) 
.white-board {
  background: #ffffff;
  border-radius: 10px;
  padding: 18px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.08);
  border: 1px solid #d8d8d8;
  min-height: 72vh;
  box-sizing: border-box;
}*/
.white-board {
  margin: 0 auto;
  position: relative;        /* fix it in the viewport */
  top: 0px;              /* distance from top of viewport */
  left: 0px;            /* leave space for sidebar */
  right: 0px;            /* distance from right edge */
  bottom: 20px;           /* distance from bottom */
  background: #ffffff;
  border-radius: 10px;
  padding: 18px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border: 1px solid #d8d8d8;
  display: flex;
  width:89%;
  min-height: auto;
  flex-direction: column;
  overflow: hidden;       /* ensure internal scroll only */
  z-index: 10;
}
/* Dropdown */
.dropdown-container {
  position: relative;
  z-index: 2000;
}
.dropdown-menu {
  display: none;
  background-color: #333;
  border-radius: 0px;
  margin-top: 5px;
  margin-bottom: 10px;
  padding: 10px;
  color: #fff;
  width: auto;
  max-height: 70vh; /* keep vertical scroll */
  overflow-y: auto;
}
.dropdown-menu.show {
  display: block;
}
.group-header {
  font-weight: bold;
  background: #444;
  padding: 8px;
  border-radius: 0px;
  cursor: pointer;
  margin-top: 8px;
}
.group-items {
  display: none;
  padding-left: 0px;
  margin-top: 5px;
}
.group-items label {
  display: block;
  color: #fff;
  font-size: 13px;
  margin: 4px 0;
  cursor: pointer;
}
.group-items input[type="checkbox"] {
  margin-right: 6px;
	margin-top: 3px;
  float: left;
}

/* Editable labels */
.group-items span.editable {
  display: block;
  min-width: auto;
  border-bottom: 1px dashed transparent;
  white-space: nowrap;
  padding-bottom: 5px;
}
.group-items span.editable:hover {
  border-bottom: 1px dashed #aaa;
  cursor: text;
}
.group-items span.editable:focus {
  outline: none;
  background: #555;
  border-radius: 4px;
  padding: 2px 4px;
  color: #fff;
}

/* Accordion Card Style */
#accordionContainer {
  margin-top: 15px;
}
.accordion-section {
  margin-bottom: 15px;
  border-radius: 10px;
  background: #fff;
  box-shadow: 0 0 6px rgba(0,0,0,0.1);
  overflow: hidden;
  border: 1px solid #dcdcdc;
}
.accordion-header {
  padding: 14px 18px;
  background: linear-gradient(90deg, #004a93, #0065c0);
  color: #fff;
  font-weight: bold;
  cursor: pointer;
  border-bottom: 1px solid #004a93;
  font-size: 15px;
  letter-spacing: 0.3px;
}
.accordion-header:hover {
  background: linear-gradient(90deg, #005bb5, #0078e7);
}
.accordion-content {
  display: none;
  background: #fafafa;
  padding: 0;
  border-top: 1px solid #ddd;
}
.accordion-section.open .accordion-content {
  display: block;
}
.accordion-content iframe {
  width: 100%;
  height: 80vh;
  border: none;
}
.logo-main { text-align:center; margin-top:12px; }

/* small control buttons */
.controls {
  display:flex;
  gap:8px;
  margin-bottom:12px;
}
.btn {
  padding:6px 10px;
  border-radius:6px;
  background:#0b6bd3;
  color:#fff;
  cursor:pointer;
  border:none;
}
.btn.danger { background:#d33; }

/* toast */
.toast {
  position: fixed;
  right: 20px;
  bottom: 20px;
  padding: 10px 14px;
  border-radius: 6px;
  color: #fff;
  display: none;
  box-shadow: 0 2px 6px rgba(0,0,0,.2);
  z-index: 9999;
}
.toast.show { display:block; animation: slideUp .3s ease; }
.toast.success { background: #16a34a; }
.toast.error { background: #dc2626; }
.toast.info { background: #2563eb; }
@keyframes slideUp { from { transform: translateY(10px); opacity:0 } to { transform: translateY(0); opacity:1 } }
/* ===== VERTICAL TABS LAYOUT ===== */
.tabs-wrapper {
  display: flex;
  width: 100%;
  height: 70vh;
  overflow-y: auto;   /* <----- MAKE THIS THE SCROLL AREA */
  background: transparent;
  border-radius: 10px;
  gap: 12px;
  position: relative;
}

/* Left tab list */
.tab-list {
  width: 200px; /* reduced width as requested */
  background: #f2f2f2;
  border-right: 1px solid #ddd;
  overflow-y: auto;
  max-height: 70vh;
  box-sizing: border-box;
  border-radius: 6px;
}
/* Make vertical tab list sticky inside the white-board */
.tab-list {
  width: 200px;
  background: #f2f2f2;
  border-right: 1px solid #ddd;
  border-radius: 6px;
  position: sticky;
  top: 0;            /* <----- THIS NOW WORKS */
  flex-shrink: 0;
  max-height: none;
  overflow-y: auto;
  z-index: 10;
}

.tab-item {
  padding: 12px;
  font-size: 14px;
  cursor: pointer;
  border-bottom: 1px solid #ddd;
  background: #fafafa;
  transition: background 0.2s;
}

.tab-item:hover {
  background: #e7e7e7;
}

.tab-item.active {
  background: #004a93;
  color: #fff;
  font-weight: bold;
}

/* Right side content */
..tab-content {
  flex: 1;
  padding: 12px;
  background: transparent;
  overflow-y: visible;   /* <----- REMOVE SCROLL HERE */
}

/* Loading message */
.tab-loading {
  padding: 20px;
  color: #777;
  font-size: 15px;
}

/* iframe content container (if used inside loaded content) */
.tab-iframe {
  width: 100%;
  min-height: 70vh;
  border: none;
}

/* ---------- Horizontal-scroll guard ---------- */
/* Make absolutely sure nothing can cause a page-level horizontal scrollbar */
html, body {
  max-width: 100%;
  overflow-x: hidden !important;
}

/* Ensure iframe or inner content won't force horizontal scroll */
.tab-content, .tab-list, .tabs-wrapper, .right-frame2 {
  overflow-x: hidden !important;
  max-width: 100% !important;
  box-sizing: border-box !important;
}

/* If loaded pages inside tab-content include wide elements, this forces them to wrap */
.tab-content * {
  max-width: 100% !important;
  box-sizing: border-box !important;
  overflow-wrap: break-word !important;
}

/* small visual tweak so tabs column doesn't visually attach to the content */
.tab-list { margin-left: 4px; }

/* END styles */
</style>
<script src="https://cdn.tailwindcss.com"></script>
</head>

<body>
<div class="dashboardpagewrap">
<div class="left-frame2">
  
  
 <a href="lander.php"><div class="navigations-main" ><div><img src="images/home.png" width="48" height="48" alt=""/></div>Dashboard</div></a>
<a href="settings.php"><div class="navigations-main"><div><img src="images/settings-ico.png" width="48" height="48" alt=""/></div>Settings</div></a>

  <!-- Stages of Project Dropdown -->
  <div class="dropdown-container">
    <div class="navigations-main" id="stagesButton">
      <div><img src="images/steps.png" width="48" alt=""/></div>Stages of Project
    </div>

    <div class="dropdown-menu" id="stagesDropdown">

      <!-- Foundation -->
      <div class="group-header" data-group="foundation">Foundation</div>
      <div class="group-items" id="foundation">
        <label>
          <input type="checkbox" data-key="foundation_main" value="Foundation">
          <span class="editable" contenteditable="true">Foundation</span>
        </label>
        <label>
          <input type="checkbox" data-key="foundation_groundbeam" value="Ground Beam with Pads & Raft Walls">
          <span class="editable" contenteditable="true">Ground Beam with Pads & Raft Walls</span>
        </label>
        <label>
          <input type="checkbox" data-key="foundation_copping" value="Foundation Copping">
          <span class="editable" contenteditable="true">Foundation Copping</span>
        </label>
        <label>
          <input type="checkbox" data-key="foundation_sandfilling" value="Foundation Sand Filling & Others">
          <span class="editable" contenteditable="true">Foundation Sand Filling & Others</span>
        </label>
        <label>
          <input type="checkbox" data-key="foundation_oversite" value="Oversite or German Concrete">
          <span class="editable" contenteditable="true">Oversite or German Concrete</span>
        </label>
      </div>

      <!-- Floor Stages -->
      <div class="group-header" data-group="floor">Floor Stages</div>
      <div class="group-items" id="floor">
        <label>
          <input type="checkbox" data-key="floor_dpc_first" value="From DPC to First Floor Slab">
          <span class="editable" contenteditable="true">From DPC to First Floor Slab</span>
        </label>
        <label>
          <input type="checkbox" data-key="floor_first_second" value="First Floor to Second Floor Slab">
          <span class="editable" contenteditable="true">First Floor to Second Floor Slab</span>
        </label>
        <label>
          <input type="checkbox" data-key="floor_second_parapet" value="Second Floor to Parapet Level">
          <span class="editable" contenteditable="true">Second Floor to Parapet Level</span>
        </label>
        <label>
          <input type="checkbox" data-key="floor_third_roofing" value="Third Floor to Roofing Level">
          <span class="editable" contenteditable="true">Third Floor to Roofing Level</span>
        </label>
        <label>
          <input type="checkbox" data-key="floor_parapet" value="Parapet">
          <span class="editable" contenteditable="true">Parapet</span>
        </label>
        <label>
          <input type="checkbox" data-key="floor_kitchen" value="Kitchen Slab">
          <span class="editable" contenteditable="true">Kitchen Slab</span>
        </label>
        <label>
          <input type="checkbox" data-key="floor_gable" value="Gable Walls">
          <span class="editable" contenteditable="true">Gable Walls</span>
        </label>
      </div>

      <!-- Roofing Work -->
      <div class="group-header" data-group="roofing">Roofing Work</div>
      <div class="group-items" id="roofing">
        <label>
          <input type="checkbox" data-key="roof_wood" value="Wood Work & Properties">
          <span class="editable" contenteditable="true">Wood Work & Properties</span>
        </label>
        
      </div>

      <!-- Other Works -->
      <div class="group-header" data-group="other">Other Works</div>
      <div class="group-items" id="other">
          <label>
          <input type="checkbox" data-key="roof_fencing" value="Fencing">
          <span class="editable" contenteditable="true">Fencing</span>
        </label>
        <label>
          <input type="checkbox" data-key="roof_soakaway" value="Soak Away Pit & Septic Tank">
          <span class="editable" contenteditable="true">Soak Away Pit & Septic Tank</span>
        </label>
        <label>
          <input type="checkbox" data-key="other_electrical" value="Electrical Piping">
          <span class="editable" contenteditable="true">Electrical Piping</span>
        </label>
        <label>
          <input type="checkbox" data-key="other_homeauto" value="Home Automation Piping">
          <span class="editable" contenteditable="true">Home Automation Piping</span>
        </label>
        <label>
          <input type="checkbox" data-key="other_cctv" value="CCTV Piping">
          <span class="editable" contenteditable="true">CCTV Piping</span>
        </label>
        <label>
          <input type="checkbox" data-key="other_plumbing" value="Plumbing Piping">
          <span class="editable" contenteditable="true">Plumbing Piping</span>
        </label>
        <label>
          <input type="checkbox" data-key="other_ac" value="AC Line Piping">
          <span class="editable" contenteditable="true">AC Line Piping</span>
        </label>
      </div>

      <!-- Finishing -->
      <div class="group-header" data-group="finishing">Finishing</div>
      <div class="group-items" id="finishing">
        <label>
          <input type="checkbox" data-key="finishing_plastering" value="Plastering">
          <span class="editable" contenteditable="true">Plastering</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_windows" value="Windows & Doors">
          <span class="editable" contenteditable="true">Windows & Doors</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_pop" value="Black POP Work for Windows, Beams & Others">
          <span class="editable" contenteditable="true">Black POP Work for Windows, Beams & Others</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_electrical" value="Electrical Wiring">
          <span class="editable" contenteditable="true">Electrical Wiring</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_homeauto" value="Home Automation Wiring">
          <span class="editable" contenteditable="true">Home Automation Wiring</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_cctv" value="CCTV Wiring">
          <span class="editable" contenteditable="true">CCTV Wiring</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_ceiling" value="Ceiling POP">
          <span class="editable" contenteditable="true">Ceiling POP</span>
        </label>
        <label>
          <input type="checkbox" data-key="finishing_screeding" value="Screeding">
          <span class="editable" contenteditable="true">Screeding</span>
        </label>
      </div>

    </div>
  </div>

  <!-- Other navigation buttons -->
  <a href="#"><div class="navigations-main"><div><img src="images/control.png" width="48" alt=""/></div>Project Control</div></a>
  <a href="constructionEquipment.php"><div class="navigations-main"><div><img src="images/construction.png" width="48" alt=""/></div>Equipment</div></a>
  <a href="materials.php"><div class="navigations-main"><div><img src="images/materials.png" width="48" alt=""/></div>Materials</div></a>
  <a href="labourer.php"><div class="navigations-main"><div><img src="images/labourers.png" width="48" alt=""/></div>Labourers</div></a>
  <a href="foundation21.php?project_ref=<?php echo htmlspecialchars($PID); ?>"><div class="navigations-main"><div><img src="images/materials.png" width="48" alt=""/></div>Cost Estimate</div></a>
  <a href="foundation_report_boq_main.php?project_ref=<?php echo htmlspecialchars($PID); ?>"><div class="navigations-main"><div><img src="images/materials.png" width="48" alt=""/></div>BOQ</div></a>
  <a href="projectinfo_edit.php?project_ref=<?php echo htmlspecialchars($PID); ?>"><div class="navigations-main" ><div><img src="images/home.png" width="48" height="48" alt=""/></div>Edit Projet info</div></a>
</div>

<!-- Right Side -->
<div class="right-frame2">
  <div id="projectDetails"></div>

  <!-- WRAP: white-board starts here (ADDED) -->
  <div class="white-board">

    <div class="controls">
      <button id="saveAllBtn" class="btn">Save all labels</button>
      <button id="clearSelectionsBtn" class="btn danger">Clear selections for this project</button>
    </div>

    <!-- tabs-wrapper remains the same but now sits inside the white board -->
    <div id="tabsContainer" class="tabs-wrapper"></div>

  </div>
  <!-- WRAP: white-board ends here -->

  <!--<div id="accordionContainer"></div>-->
</div>

<!-- toast -->
<div id="toast" class="toast"></div>

<script>
/* ========== FIXED DROPDOWN TOGGLE ========== */

/* ========== FIXED GROUP HEADER EXPAND ========== */
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll(".group-header").forEach(header => {
    header.addEventListener("click", () => {
      const group = document.getElementById(header.dataset.group);
      group.style.display = group.style.display === "none" ? "block" : "none";
    });
  });
});
</script>
<script>
/* Updated script: tabs + drag-reorder + autosave order + label sync
   Paste this replacing your existing <script> block.
*/

const PID = "<?php echo htmlspecialchars($PID); ?>";
const API = 'stages_api.php'; // relative path to your API

/* Toast helper */
const toastEl = document.getElementById('toast');
function showToast(msg, type='success') {
  toastEl.className = 'toast show ' + (type === 'error' ? 'error' : (type === 'info' ? 'info' : 'success'));
  toastEl.textContent = msg;
  setTimeout(() => toastEl.classList.remove('show'), 2600);
}

/* DOM refs */
const dropdown = document.getElementById("stagesDropdown");
const tabsContainer = document.getElementById("tabsContainer");

/* Dropdown Toggle (MISSING BEFORE) */
document.getElementById("stagesButton").addEventListener("click", () => {
  document.getElementById("stagesDropdown").classList.toggle("show");
});


/* create tab layout if not present */
if (!tabsContainer.querySelector('.tab-list')) {
  tabsContainer.innerHTML = `
    <div class="tab-list" id="tabList" aria-label="Project stages"></div>
    <div class="tab-content" id="tabContent"></div>
  `;
}
const tabList = document.getElementById("tabList");
const tabContent = document.getElementById("tabContent");

/* page map (same as before) */
const pageMap = {
  "foundation_main":"foundation_form.php",
  "foundation_groundbeam":"foundation_groundbeam.php",
  "foundation_copping":"foundation_copping_2.php",
  "foundation_sandfilling":"foundation_sandfilling.php",
  "foundation_oversite":"foundation_germanfloor.php",
  "floor_dpc_first":"floor_dpc_first.php",
  "floor_first_second":"floor_first_second.php",
  "floor_second_parapet":"floor_second_parapet.php",
  "floor_third_roofing":"floor_third_roofing.php",
  "floor_parapet":"floor_parapet.php",
  "floor_kitchen":"floor_kitchen.php",
  "floor_gable":"floor_gable.php",
  "roof_wood":"roofing_wood.php",
  "roof_fencing":"roofing_fencing.php",
  "roof_soakaway":"roof_soakaway.php",
  "other_electrical":"other_electrical.php",
  "other_homeauto":"other_homeauto.php",
  "other_cctv":"other_cctv.php",
  "other_plumbing":"other_plumbing.php",
  "other_ac":"other_ac.php",
  "finishing_plastering":"finishing_plastering.php",
  "finishing_windows":"finishing_windows.php",
  "finishing_pop":"finishing_pop.php",
  "finishing_electrical":"finishing_electrical.php",
  "finishing_homeauto":"finishing_homeauto.php",
  "finishing_cctv":"finishing_cctv.php",
  "finishing_ceiling":"finishing_ceiling.php",
  "finishing_screeding":"finishing_screeding.php"
};

/* Solid color theme function (same colors you liked) */
function getTabColor(key) {
  if (key.startsWith("foundation_")) return "#004A93";
  if (key.startsWith("floor_")) return "#15803D";
  if (key.startsWith("roof_")) return "#EA580C";
  if (key.startsWith("other_")) return "#6B7280";
  if (key.startsWith("finishing_")) return "#7C3AED";
  return "#444";
}

/* ------------------- Tab creation / activation / removal ------------------- */
function createTab(key, labelText) {
  let tab = document.getElementById("tab_" + key);
  if (!tab) {
    tab = document.createElement("div");
    tab.id = "tab_" + key;
    tab.className = "tab-item";
    tab.dataset.key = key;
    tab.setAttribute('draggable', 'true');
    tab.innerText = labelText;
    // style
    tab.style.background = getTabColor(key);
    tab.style.color = "#fff";
    tab.style.opacity = "0.9";

    // append
    tabList.appendChild(tab);

    // click handler
    tab.addEventListener("click", () => activateTab(key));

    // keyboard accessibility: Enter/Space to activate
    tab.addEventListener("keydown", (e) => {
      if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activateTab(key); }
    });

    // drag handlers - native HTML5 DnD
    tab.addEventListener('dragstart', onDragStart);
    tab.addEventListener('dragover', onDragOver);
    tab.addEventListener('dragleave', onDragLeave);
    tab.addEventListener('drop', onDrop);
    tab.addEventListener('dragend', onDragEnd);
  } else {
    tab.innerText = labelText;
  }
  return tab;
}

function activateTab(key) {
  document.querySelectorAll(".tab-item").forEach(t => t.classList.remove("active"));
  const tab = document.getElementById("tab_" + key);
  if (tab) tab.classList.add("active");

  tabContent.innerHTML = `<p class="tab-loading">Loading...</p>`;

  const target = pageMap[key];
  if (!target) {
    tabContent.innerHTML = `<p style="color:red">No page mapped for ${key}</p>`;
    return;
  }

  fetch(`${target}?project_ref=${encodeURIComponent(PID)}`)
    .then(r => r.text())
    .then(html => tabContent.innerHTML = html)
    .catch(() => tabContent.innerHTML = `<p style="color:red">Error loading content</p>`);
    
    // VERY IMPORTANT: Reinitialize JS functions from loaded page
        initStageScripts();
    
}

function removeTab(key) {
  const tab = document.getElementById("tab_" + key);
  if (tab) tab.remove();
  if (!document.querySelector(".tab-item.active")) tabContent.innerHTML = '';
}

/* ------------------- Drag & drop for reorder (native) ------------------- */
let dragSrcEl = null;
function onDragStart(e) {
  dragSrcEl = this;
  e.dataTransfer.effectAllowed = 'move';
  // store key for fallback
  e.dataTransfer.setData('text/plain', this.dataset.key);
  this.classList.add('dragging');
}
function onDragOver(e) {
  e.preventDefault();
  e.dataTransfer.dropEffect = 'move';
  this.classList.add('drag-over');
}
function onDragLeave(e) {
  this.classList.remove('drag-over');
}
function onDrop(e) {
  e.preventDefault();
  this.classList.remove('drag-over');
  const src = dragSrcEl;
  const dst = this;
  if (!src || src === dst) return;

  // insert src before dst (or after depending on position)
  const rect = dst.getBoundingClientRect();
  const mid = rect.left + rect.width / 2;
  if (e.clientX < mid) {
    tabList.insertBefore(src, dst);
  } else {
    tabList.insertBefore(src, dst.nextSibling);
  }

  // autosave order after drop
  saveTabOrderToServer();
}
function onDragEnd(e) {
  document.querySelectorAll('.tab-item').forEach(t => {
    t.classList.remove('dragging', 'drag-over');
  });
  dragSrcEl = null;
}

/* collect current tab order and send to API */
function saveTabOrderToServer() {
  const order = Array.from(tabList.querySelectorAll('.tab-item')).map(t => t.dataset.key);
  const body = new URLSearchParams();
  body.append('action', 'save_sort_order');
  body.append('project_ref', PID);
  body.append('order', JSON.stringify(order));

  fetch(API, { method: 'POST', body })
    .then(r => r.json())
    .then(json => {
      if (!json || !json.ok) showToast('Failed to save tab order', 'error');
      else showToast('Tab order saved', 'info');
    })
    .catch(() => showToast('Failed to save tab order', 'error'));
}

/* ------------------- Editable labels: sync to tabs & save single label ------------------- */
function initEditableLabels() {
  dropdown.querySelectorAll("span.editable").forEach(span => {
    // prevent checkbox toggle when editing
    span.addEventListener('click', e => e.stopPropagation());
    span.addEventListener('mousedown', e => e.stopPropagation());

    span.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); span.blur(); } });

    span.addEventListener('input', function() {
      const cb = this.previousElementSibling;
      if (!cb) return;
      const key = cb.dataset.key;
      const newText = this.innerText.trim();
      // live update tab title if exists
      const tab = document.getElementById("tab_" + key);
      if (tab) tab.innerText = newText;
      // keep checkbox value updated
      cb.value = newText;
    });

    span.addEventListener('blur', function() {
      const cb = this.previousElementSibling;
      if (!cb) return;
      const key = cb.dataset.key;
      const label = this.innerText.trim();

      const body = new URLSearchParams();
      body.append('action', 'save_label');
      body.append('project_ref', PID);
      body.append('key', key);
      body.append('label', label);

      fetch(API, { method: 'POST', body })
        .then(r => r.json())
        .then(j => {
          if (j && j.ok) showToast('Label saved');
          else showToast('Label save failed', 'error');
        })
        .catch(() => showToast('Label save failed', 'error'));
    });
  });
}

/* ------------------- Checkbox click behavior: create/remove tab + persist selection ------------------- */
function initCheckboxHandlers() {
  dropdown.querySelectorAll("input[type=checkbox]").forEach(cb => {
    cb.addEventListener('change', function() {
      const key = this.dataset.key;
      const label = (this.nextElementSibling && this.nextElementSibling.innerText) ? this.nextElementSibling.innerText.trim() : this.value;

      // persist selection
      const body = new URLSearchParams();
      body.append('action', 'toggle_selection');
      body.append('project_ref', PID);
      body.append('key', key);
      body.append('checked', this.checked ? '1' : '0');

      fetch(API, { method: 'POST', body })
        .then(r => r.json())
        .then(j => { if (!j || !j.ok) showToast('Failed to save selection', 'error'); })
        .catch(() => showToast('Failed to save selection', 'error'));

      if (this.checked) {
        createTab(key, label);
        activateTab(key);
      } else {
        removeTab(key);
      }
    });
  });
}

/* ------------------- Save all labels button ------------------- */
const saveAllBtn = document.getElementById("saveAllBtn");
if (saveAllBtn) {
  saveAllBtn.addEventListener('click', () => {
    const labels = {};
    dropdown.querySelectorAll('input[type=checkbox]').forEach(cb => {
      const key = cb.dataset.key;
      const span = cb.nextElementSibling;
      if (key && span) labels[key] = span.innerText.trim();
    });
    const body = new URLSearchParams();
    body.append('action', 'save_all_labels');
    body.append('project_ref', PID);
    body.append('labels', JSON.stringify(labels));
    fetch(API, { method: 'POST', body })
      .then(r => r.json())
      .then(j => j && j.ok ? showToast('All labels saved') : showToast('Save all failed','error'))
      .catch(() => showToast('Save all failed','error'));
  });
}

/* ------------------- Clear selections button ------------------- */
const clearBtn = document.getElementById("clearSelectionsBtn");
if (clearBtn) {
  clearBtn.addEventListener('click', () => {
    if (!confirm('Clear all saved selections for this project?')) return;
    const body = new URLSearchParams();
    body.append('action', 'clear_selections');
    body.append('project_ref', PID);
    fetch(API, { method: 'POST', body })
      .then(r => r.json())
      .then(j => {
        if (j && j.ok) {
          dropdown.querySelectorAll('input[type=checkbox]').forEach(cb => cb.checked = false);
          tabList.innerHTML = '';
          tabContent.innerHTML = '';
          showToast('Selections cleared');
        } else showToast('Clear failed','error');
      })
      .catch(() => showToast('Clear failed','error'));
  });
}

/* ------------------- Load saved state (labels + selections + optional order) ------------------- */
(function loadSavedState() {
  const body = new URLSearchParams();
  body.append('action', 'fetch_state');
  body.append('project_ref', PID);

  fetch(API, { method: 'POST', body })
    .then(r => r.json())
    .then(j => {
      if (!j || !j.ok) return;

      // apply labels (if any)
      if (j.labels) {
        Object.keys(j.labels).forEach(k => {
          const el = document.querySelector(`input[data-key="${k}"]`);
          if (el) {
            const span = el.nextElementSibling;
            if (span) {
              span.innerText = j.labels[k] || span.innerText;
              el.value = j.labels[k] || el.value;
            }
          }
        });
      }

      // create tabs for selections
      // if the server returned an 'order' array, respect that order
      const selections = Array.isArray(j.order) && j.order.length ? j.order : (Array.isArray(j.selections) ? j.selections : []);
      // fallback: if only j.selections exists and no j.order, just use that
      (selections.length ? selections : (Array.isArray(j.selections) ? j.selections : [])).forEach(key => {
        const el = document.querySelector(`input[data-key="${key}"]`);
        // if the checkbox exists in DOM, check it visually
        if (el) el.checked = true;
        // get label text (either saved label or current span)
        const labelSpan = el ? el.nextElementSibling : null;
        const labelText = (j.labels && j.labels[key]) ? j.labels[key] : (labelSpan ? labelSpan.innerText.trim() : key);
        createTab(key, labelText);
      });

      // if no explicit order provided, but server gave selections, they are already appended in the loop above.
      // set keyboard focus / activate first tab
      const firstTab = tabList.querySelector('.tab-item');
      if (firstTab) firstTab.click();

      // initialize handlers AFTER tabs created
      initEditableLabels();
      initCheckboxHandlers();

      // ensure tab-list is keyboard navigable
      tabList.querySelectorAll('.tab-item').forEach(t => t.tabIndex = 0);
    })
    .catch(err => {
      console.error('fetch_state error', err);
    });
})();
</script>
<script>
function initStageScripts() {

    /* ============================================================
       REMOVE ROW
    ============================================================ */
    window.removeRow = function(btn) {
        btn.closest('.row, .column-base-row, .column-type-row').remove();
    };

    /* ============================================================
       IMPORTED BARS — DUPLICATE WITHOUT LABELS
    ============================================================ */
    window.addImportedBarRow = function() {
        const container = document.getElementById("importedBarsContainer");
        if (!container) return;

        const lastRow = container.querySelector(".imported-bar-row:last-of-type");
        if (!lastRow) return;

        const newRow = lastRow.cloneNode(true);

        // Remove labels inside duplicates (if any)
        newRow.querySelectorAll("label").forEach(l => l.remove());

        // Duplicate field values
        const oldFields = lastRow.querySelectorAll("input, select");
        const newFields = newRow.querySelectorAll("input, select");

        newFields.forEach((field, i) => {
            field.value = oldFields[i].value;
        });

        // Add remove button if missing
        if (!newRow.querySelector(".removeBtn")) {
            const removeBtn = document.createElement("button");
            removeBtn.className = "removeBtn";
            removeBtn.textContent = "X";
            removeBtn.style.cssText =
                "padding:4px 10px;background:#c0392b;color:white;" +
                "border:none;border-radius:4px;cursor:pointer;";
            removeBtn.onclick = function() { removeRow(this); };
            newRow.appendChild(removeBtn);
        }

        container.appendChild(newRow);
    };


   /* ============================================================
   COLUMN TYPE ROW — DUPLICATE WITHOUT LABELS (FIXED VERSION)
============================================================ */
window.addColumnTypeRow = function () {

    const container = document.getElementById("columnTypeContainer");
    if (!container) return;

    const lastRow = container.querySelector(".column-type-row:last-of-type");
    if (!lastRow) return;

    // Clone entire row
    const newRow = lastRow.cloneNode(true);
    newRow.style.marginBottom = "10px"; // keeps spacing even

    // Remove labels from duplicate rows
    newRow.querySelectorAll("label").forEach(label => label.remove());

    // Duplicate field values
    const oldFields = lastRow.querySelectorAll("input, select");
    const newFields = newRow.querySelectorAll("input, select");

    newFields.forEach((field, i) => {
        field.value = oldFields[i].value;
    });

    // Remove any old removeBtn to avoid duplicates inside the clone
    const oldRemove = newRow.querySelector(".removeBtn");
    if (oldRemove) oldRemove.remove();

    // Create a wrapper div to align X button properly
    const removeWrapper = document.createElement("div");
    removeWrapper.style.display = "flex";
    removeWrapper.style.flexDirection = "column";
    removeWrapper.style.justifyContent = "flex-end"; 
    removeWrapper.style.marginLeft = "6px";

    const removeBtn = document.createElement("button");
    removeBtn.className = "removeBtn";
    removeBtn.innerText = "X";

    removeBtn.style.cssText =
        "width:32px;height:26px;display:flex;align-items:center;justify-content:center;" +
        "background:#c0392b;color:white;border:none;border-radius:4px;cursor:pointer;";

    // Correct row removal
    removeBtn.onclick = function () {
        newRow.remove();
    };

    removeWrapper.appendChild(removeBtn);

    // Append aligned delete button at end of row
    newRow.appendChild(removeWrapper);

    container.appendChild(newRow);
};


    /* ============================================================
       EQUIPMENT — DUPLICATE WITHOUT LABELS
    ============================================================ */
    window.addEquipmentRow = function() {
        const container = document.getElementById("equipmentContainer");
        if (!container) return;

        const lastRow = container.querySelector(".equipment-row:last-of-type");
        if (!lastRow) return;

        const newRow = lastRow.cloneNode(true);

        // Remove labels (if any)
        newRow.querySelectorAll("label").forEach(l => l.remove());

        // Duplicate values
        const oldFields = lastRow.querySelectorAll("input, select");
        const newFields = newRow.querySelectorAll("input, select");

        newFields.forEach((field, i) => {
            field.value = oldFields[i].value;
        });

        // Create remove button if needed
        if (!newRow.querySelector(".removeBtn")) {
            const removeBtn = document.createElement("button");
            removeBtn.className = "removeBtn";
            removeBtn.innerText = "X";
            removeBtn.style.cssText =
                "padding:4px 10px;background:#c0392b;color:white;border:none;" +
                "border-radius:4px;cursor:pointer;";
            removeBtn.onclick = function() { removeRow(this); };
            newRow.appendChild(removeBtn);
        }

        container.appendChild(newRow);
    };


    /* ============================================================
       COLUMN BASE ROW — DUPLICATE WITHOUT LABELS
    ============================================================ */
    window.addColumnBaseRow = function () {
        const container = document.getElementById("columnBaseContainer");
        if (!container) return;

        const firstRow = container.querySelector(".column-base-row:last-of-type");
        if (!firstRow) return;

        const clone = firstRow.cloneNode(true);

        // Remove labels
        clone.querySelectorAll("label").forEach(l => l.remove());

        // Remove old remove button
        const oldRemove = clone.querySelector(".remove-btn");
        if (oldRemove) oldRemove.remove();

        // Duplicate values
        const oldFields = firstRow.querySelectorAll("input, select");
        const newFields = clone.querySelectorAll("input, select");
        newFields.forEach((f, i) => f.value = oldFields[i].value);

        // Add remove button
        const removeBtn = document.createElement("button");
        removeBtn.className = "remove-btn";
        removeBtn.innerText = "X";
        removeBtn.style.cssText =
            "margin-left:6px;padding:4px 10px;background:#c0392b;color:white;" +
            "border:none;border-radius:4px;cursor:pointer;height:32px;";
        removeBtn.onclick = () => clone.remove();
        clone.appendChild(removeBtn);

        container.appendChild(clone);
    };

}

<script>
/* ============================================================
   AFTER EXCAVATION ROW — DUPLICATE WITHOUT LABELS
============================================================ */
window.addAfterExcavationRow = function () {

    const container = document.getElementById("afterExcavationContainer");
    if (!container) return;

    const firstRow = container.querySelector(".after-exc-row:last-of-type");
    if (!firstRow) return;

    const clone = firstRow.cloneNode(true);

    // Reset input values
    clone.querySelectorAll("input").forEach(i => i.value = "");

    // REMOVE any existing remove-btn first
    const oldRemove = clone.querySelector(".remove-btn");
    if (oldRemove) oldRemove.remove();

    // Add new remove button
    const removeBtn = document.createElement("button");
    removeBtn.className = "remove-btn";
    removeBtn.innerText = "X";
    removeBtn.style.cssText =
        "margin-left:6px;padding:4px 10px;background:#c0392b;color:white;" +
        "border:none;border-radius:4px;cursor:pointer;height:32px;";
    removeBtn.onclick = () => clone.remove();
    clone.appendChild(removeBtn);

    // ---- Auto-expanding field setup ----
    const span = clone.querySelector(".autoSpan");
    const input = clone.querySelector(".autoInput");

    input.oninput = () => {
        span.textContent = input.value;
        input.style.width = Math.max(246, span.offsetWidth) + "px";
    };

    container.appendChild(clone);
};
</script>


</script>




</body>
</html>
