<?php
// index.php

// Start the session with secure settings
session_start([
    'cookie_lifetime' => 0,
    'cookie_secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', // Ensure HTTPS is on
    'cookie_httponly' => true,
    'cookie_samesite' => 'Strict'
]);

// CSRF Token Generation
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');

    // CSRF Token Validation
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token']);
        exit();
    }

    switch ($_POST['action']) {
        case 'saveState':
            // Validate class and student
            if (!isset($_POST['class']) || !isset($_POST['student'])) {
                echo json_encode(['status' => 'error', 'message' => 'Missing class or student identifier']);
                exit();
            }
            $class = htmlspecialchars($_POST['class'], ENT_QUOTES, 'UTF-8');
            $student = htmlspecialchars($_POST['student'], ENT_QUOTES, 'UTF-8');

            // Validate JSON
            $data = json_decode($_POST['data'], true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
                exit();
            }
            // Sanitize and store data per student
            $_SESSION['students'][$class][$student] = htmlspecialchars($_POST['data'], ENT_QUOTES, 'UTF-8');
            echo json_encode(['status' => 'success']);
            exit();

        case 'loadState':
            // Validate class and student
            if (!isset($_POST['class']) || !isset($_POST['student'])) {
                echo json_encode(['status' => 'error', 'message' => 'Missing class or student identifier']);
                exit();
            }
            $class = htmlspecialchars($_POST['class'], ENT_QUOTES, 'UTF-8');
            $student = htmlspecialchars($_POST['student'], ENT_QUOTES, 'UTF-8');

            if (isset($_SESSION['students'][$class][$student])) {
                echo json_encode(['status' => 'success', 'data' => json_decode($_SESSION['students'][$class][$student], true)]);
            } else {
                echo json_encode(['status' => 'empty']);
            }
            exit();

        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
            exit();
    }
}
?>

<!DOCTYPE html>

<html lang="sv">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lärares Strategijournal</title>

  <!-- Quill CSS -->

  <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

  <style>
    /* Basic Reset */
    *, *::before, *::after {
      box-sizing: border-box;
    }
    body {
      display: flex;
      height: 100vh;
      background: linear-gradient(135deg, #f8f9fa 25%, #e9ecef 100%);
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      color: #343a40;
      overflow: hidden;
    }

    /* Sidebar Menu */
    .sidebar {
      width: 350px;
      background-color: #343a40;
      padding: 20px;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      gap: 15px;
      transition: transform 0.3s ease;
      position: relative;
    }

    .sidebar.back {
      transform: translateX(-100%);
    }

    .sidebar.slide-in {
      transform: translateX(0);
    }

    .sidebar h2 {
      color: #ffffff;
      margin-bottom: 10px;
      font-size: 24px;
      text-align: center;
      cursor: pointer;
    }

    /* Class Title */
    .sidebar .current-title {
      color: #ffffff;
      margin-bottom: 10px;
      font-size: 24px;
      text-align: center;
      cursor: pointer;
    }

    /* Search Bar */
    .search-bar {
      position: relative;
      margin-bottom: 15px;
    }

    .search-bar input {
      width: 100%;
      padding: 8px 35px 8px 35px; /* Adjusted padding for clear button */
      border: none;
      border-radius: 6px;
      font-size: 14px;
      outline: none;
      transition: box-shadow 0.3s ease;
    }

    .search-bar input:focus {
      box-shadow: 0 0 5px rgba(23, 162, 184, 0.5);
    }

    .search-bar::before {
      content: '🔍';
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      pointer-events: none;
    }

    /* Clear Search Button */
    .search-bar .clear-search {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      background: transparent;
      border: none;
      font-size: 18px;
      color: #adb5bd;
      cursor: pointer;
      display: none; /* Hidden by default */
      padding: 0;
    }

    .search-bar .clear-search.visible {
      display: block;
    }

    .search-bar .clear-search:hover {
      color: #ffffff;
    }

    /* Category Styles */
    .category {
      color: #adb5bd;
      cursor: pointer;
      padding: 12px 15px;
      background-color: #495057;
      border-radius: 8px;
      position: relative;
      transition: background-color 0.3s ease, color 0.3s ease;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
    }

    .category:hover, .category.expanded {
      background-color: #6c757d;
      color: #ffffff;
    }

    .category .arrow {
      transition: transform 0.3s ease;
      font-size: 12px;
    }

    .category.expanded .arrow {
      transform: rotate(90deg);
    }

    .subcategory-list {
      display: none;
      flex-direction: column;
      margin-top: 8px;
      gap: 6px;
      padding-left: 20px;
    }

    .subcategory-list.expanded {
      display: flex;
    }

    .subcategory {
      background-color: #495057;
      padding: 10px 15px;
      border-radius: 6px;
      cursor: pointer;
      color: #ced4da;
      transition: background-color 0.3s ease, color 0.3s ease;
      font-size: 14px;
    }

    .subcategory:hover, .subcategory.selected {
      background-color: #6c757d;
      color: #ffffff;
    }

    /* Highlight search results */
    .subcategory.highlight {
      background-color: #17a2b8;
      color: #ffffff;
    }

    /* Main Content with Journey Path and Tool Menu */
    .main-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 20px;
      overflow: auto;
      position: relative;
    }

    /* Tool Menu */
    .tool-menu {
      margin-top: 25px;
      width: 100%;
      max-width: 700px;
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 30px;
      flex-wrap: wrap;
    }

    .tool-menu label {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      color: #343a40;
    }

    /* Toggle Switch */
    .switch {
      position: relative;
      display: inline-block;
      width: 50px;
      height: 24px;
    }

    .switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }

    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ccc;
      transition: background-color 0.4s;
      border-radius: 24px;
    }

    .slider:before {
      position: absolute;
      content: "";
      height: 18px;
      width: 18px;
      left: 3px;
      bottom: 3px;
      background-color: white;
      transition: transform 0.4s;
      border-radius: 50%;
    }

    input:checked + .slider {
      background-color: #28a745;
    }

    input:checked + .slider:before {
      transform: translateX(26px);
    }

    /* Journey Path Container */
    .journey-path {
      display: flex;
      flex-wrap: wrap; /* Allow wrapping to new lines */
      align-items: center;
      position: relative;
      padding: 20px 0;
      width: 100%;
      max-width: 1600px;
      gap: 40px; /* Space between steps */
    }

    /* Horizontal Connection Lines */
    .journey-line {
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 4px;
      background-color: #dee2e6;
      z-index: 1;
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    /* Dividing Vertical Lines */
    .dividing-line {
      position: absolute;
      width: 4px;
      background-color: #adb5bd;
      z-index: 1;
      transition: background-color 0.3s ease;
    }

    /* Journey Steps */
    .journey-step {
      position: relative;
      z-index: 2;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 180px; /* Increased width */
      height: 220px; /* Increased height to accommodate name and title */
      flex-shrink: 0; /* Prevent steps from shrinking */
      transition: transform 0.3s ease;
    }

    .journey-step:hover {
      transform: scale(1.05);
    }

    /* Drop Zones */
    .drop-zone {
      width: 140px; /* Increased width */
      height: 140px; /* Increased height */
      border: 2px dashed #ced4da;
      border-radius: 12px; /* More rounded corners */
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      transition: border-color 0.3s ease, background-color 0.3s ease;
      background-color: #f8f9fa;
    }

    .drop-zone.over {
      border-color: #17a2b8;
      background-color: rgba(23, 162, 184, 0.1);
    }

    /* Connectors */
    .journey-step::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 100%;
      width: 60px; /* Increased connector length */
      height: 4px;
      background-color: #dee2e6;
      transform: translateY(-50%);
      z-index: -1;
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    .journey-step.last-in-row::after {
      display: none; /* Remove horizontal connector if it's marked as last in row */
    }

    /* Dividing Lines Between Rows */
    .journey-step.last-in-row::before {
      content: '';
      position: absolute;
      top: 100%;
      left: 50%;
      width: 4px;
      height: 60px; /* Increased height */
      background-color: #adb5bd;
      transform: translateX(-50%);
      z-index: -1;
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    /* Hide Dividing Lines When Only One Row */
    .single-row .journey-line {
      display: none;
    }

    /* Grid Items (Rectangles) */
    .rectangle {
      background: linear-gradient(145deg, #6c5ce7, #a29bfe);
      color: #ffffff;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      font-size: 14px;
      border-radius: 12px; /* More rounded corners */
      cursor: grab;
      transition: box-shadow 0.3s ease, transform 0.3s ease, background 0.5s ease, opacity 0.3s ease;
      width: 140px;        /* Increased width */
      height: 140px;       /* Increased height */
      user-select: none;
      padding: 20px 5px 5px 5px;       /* Adjusted padding to make space for checkmark */
      overflow: visible;    /* Allow checkmark to be visible outside */
      position: relative;
      box-sizing: border-box; /* Include padding within dimensions */
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* Soft shadow */
    }

    .rectangle:hover {
      box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2);
      transform: translateY(-5px);
    }

    /* Checkmark Styles */
    .checkmark {
      position: absolute;
      top: -10px; /* Position above the rectangle */
      left: -10px; /* Position to the left of the rectangle */
      width: 20px;
      height: 20px;
      background-color: #ffffff;
      border: 2px solid #343a40;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 10;
    }

    .checkmark::after {
      content: '';
      display: none;
      width: 6px;
      height: 12px;
      border: solid #343a40;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
    }

    /* Show the checkmark when checked */
    .rectangle.checked .checkmark::after {
      display: block;
    }

    /* Dimmed state for checked rectangles */
    .rectangle.dimmed {
      opacity: 0.5;
      transition: opacity 0.3s ease;
    }

    /* Rectangle Name */
    .rectangle-name {
      font-weight: 600;
      margin-bottom: 6px; /* Increased margin for better separation */
      font-size: 14px;
      text-align: center;
      width: 100%;
      word-wrap: break-word;
      border-bottom: 1px solid rgba(255, 255, 255, 0.3); /* Separator line */
      padding-bottom: 4px;
    }

    /* Rectangle Title */
    .rectangle-title {
      font-size: 13px;
      text-align: center;
      word-wrap: break-word;
      word-break: break-word;
      flex-grow: 0;               /* Prevents stretching */
      margin-top: 6px;            /* Provides space above the title */
      padding: 5px;               /* Adds 5px padding inside the title container */
      white-space: normal;        /* Allows text to wrap normally */
      overflow: hidden;           /* Hides any overflowing text */
      text-overflow: ellipsis;    /* Adds ellipsis if text is too long */
      box-sizing: border-box;     /* Ensures padding is included within the element's total width */
      width: 100%;                /* Ensures the title takes the full width of the container */
    }

    /* Inner Text Container */
    .rectangle-text {
      display: none; /* Hide original text container */
    }

    /* Specific Rectangle Types */
    .rectangle.differentiated-instruction { background: linear-gradient(145deg, #ff9a9e, #fad0c4); }
    .rectangle.collaborative-learning { background: linear-gradient(145deg, #a18cd1, #fbc2eb); }
    .rectangle.positive-reinforcement { background: linear-gradient(145deg, #fbc2eb, #a6c1ee); }
    .rectangle.behavior-modeling { background: linear-gradient(145deg, #84fab0, #8fd3f4); }
    .rectangle.individual-tutoring { background: linear-gradient(145deg, #fccb90, #d57eeb); }
    .rectangle.mentoring-programs { background: linear-gradient(145deg, #ffecd2, #fcb69f); }
    .rectangle.feedback-sessions { background: linear-gradient(145deg, #f6d365, #fda085); }
    .rectangle.learning-games { background: linear-gradient(145deg, #cfd9df, #e2ebf0); }
    .rectangle.student-reflections { background: linear-gradient(145deg, #f093fb, #f5576c); }
    /* Additional Rectangle Types */
    .rectangle.observations { background: linear-gradient(145deg, #d4fc79, #96e6a1); }
    .rectangle.specific-adjustments { background: linear-gradient(145deg, #fbc2eb, #a6c1ee); }
    .rectangle.individual-conversations { background: linear-gradient(145deg, #84fab0, #8fd3f4); }
    .rectangle.group-activities { background: linear-gradient(145deg, #f6d365, #fda085); }
    .rectangle.behavior-charts { background: linear-gradient(145deg, #cfd9df, #e2ebf0); }
    .rectangle.self-reflection { background: linear-gradient(145deg, #fbc2eb, #a6c1ee); }
    .rectangle.peer-feedback { background: linear-gradient(145deg, #d4fc79, #96e6a1); }
    .rectangle.classroom-observation { background: linear-gradient(145deg, #f093fb, #f5576c); }

    /* Dragging Styles */
    .rectangle.dragging {
      cursor: grabbing;
      box-shadow: 0 15px 25px rgba(0, 0, 0, 0.3);
      transform: scale(1.1);
      z-index: 1000;
    }

    .dragging-ghost {
      position: absolute;
      pointer-events: none;
      background-color: rgba(23, 162, 184, 0.8);
      color: #ffffff;
      font-size: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 140px; /* Match rectangle width */
      height: 140px; /* Match rectangle height */
      border-radius: 12px;
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
      transform: scale(1.1);
      z-index: 1000;
    }

    /* Remove Button Styles */
    .remove-button {
      position: absolute;
      top: 6px;
      right: 6px;
      background: rgba(0, 0, 0, 0.6);
      color: #ffffff;
      border: none;
      border-radius: 50%;
      width: 22px;
      height: 22px;
      font-size: 16px;
      line-height: 18px;
      text-align: center;
      cursor: pointer;
      opacity: 0.9;
      transition: opacity 0.2s ease, background-color 0.2s ease;
    }

    .remove-button:hover {
      opacity: 1;
      background-color: rgba(0, 0, 0, 0.8);
    }

    /* Hide remove buttons when deletion is disabled */
    .delete-disabled .remove-button {
      display: none;
    }

    /* Tooltip Styles */
    /* Removed tooltip from entire rectangle to comply with user request */

    /* Tooltips for specific elements */
    .remove-button .tooltip,
    .checkmark .tooltip {
      position: absolute;
      bottom: 125%;
      left: 50%;
      transform: translateX(-50%);
      background-color: #343a40;
      color: #ffffff;
      padding: 5px 8px;
      border-radius: 4px;
      font-size: 12px;
      white-space: nowrap;
      opacity: 0;
      pointer-events: none; /* Allows mouse events to pass through */
      transition: opacity 0.3s ease;
      z-index: 10;
    }

    .remove-button:hover .tooltip,
    .checkmark:hover .tooltip {
      opacity: 1;
    }

    /* Toast Notification */
    .toast {
      visibility: hidden;
      min-width: 250px;
      background-color: #333;
      color: #fff;
      text-align: center;
      border-radius: 4px;
      padding: 16px;
      position: fixed;
      z-index: 1000;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);
      opacity: 0;
      transition: opacity 0.5s, bottom 0.5s;
    }

    .toast.show {
      visibility: visible;
      opacity: 1;
      bottom: 50px;
    }

    /* Popup Styles */
    .popup-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 2000;
    }

    .popup {
      background: #ffffff;
      padding: 0;
      border-radius: 12px; /* More rounded corners */
      width: 90%;
      max-width: 700px; /* Increased max-width for better space */
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
      animation: fadeIn 0.3s ease;
      display: flex;
      flex-direction: column;
      max-height: 80vh; /* Changed from fixed height */
      height: auto; /* Allow height to adjust based on content */
      overflow: hidden; /* Hide overflow to manage internal scrolling */
      transition: max-height 0.3s ease, height 0.3s ease; /* Smooth transitions */
    }

    .popup-header {
      padding: 20px;
      background-color: #343a40;
      color: #ffffff;
      position: sticky;
      top: 0;
      z-index: 2;
      border-top-left-radius: 12px;
      border-top-right-radius: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .popup-header h3 {
      margin: 0;
      font-size: 24px;
      text-align: center;
      flex-grow: 1;
    }

    /* Close Button in Popup */
    .popup-header .close-popup-btn {
      background: transparent;
      border: none;
      color: #ffffff;
      font-size: 24px;
      cursor: pointer;
      line-height: 1;
      padding: 0;
      margin-left: 10px;
      transition: color 0.3s ease;
    }

    .popup-header .close-popup-btn:hover {
      color: #adb5bd;
    }

    .popup-content {
      padding: 20px;
      overflow-y: auto; /* Enable vertical scrolling */
      flex-grow: 1;
      max-height: calc(80vh - 160px); /* Adjust based on popup's max-height minus header and footer */
    }

    .popup-footer {
      padding: 10px 20px;
      background-color: #f8f9fa;
      border-bottom-left-radius: 12px;
      border-bottom-right-radius: 12px;
      position: sticky;
      bottom: 0;
      z-index: 2;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      border-top: 1px solid #dee2e6;
    }

    /* Buttons in Popup */
    .buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }

    .buttons .save-btn {
      background-color: #28a745;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .buttons .save-btn:hover {
      background-color: #218838;
    }

    .buttons .cancel-btn {
      background-color: #dc3545;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .buttons .cancel-btn:hover {
      background-color: #c82333;
    }

    /* View Popup Styles */
    .view-popup-overlay {
      position: fixed; /* Changed to fixed for consistency */
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 2500;
    }

    .view-popup {
      background: #ffffff;
      padding: 0;
      border-radius: 12px;
      width: 90%;
      max-width: 500px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
      animation: fadeIn 0.3s ease;
      display: flex;
      flex-direction: column;
      max-height: 80vh; /* Changed from fixed height */
      height: auto; /* Allow height to adjust based on content */
      overflow: hidden; /* Hide overflow to manage internal scrolling */
      transition: max-height 0.3s ease, height 0.3s ease; /* Smooth transitions */
    }

    .view-popup-header {
      padding: 20px;
      background-color: #343a40;
      color: #ffffff;
      position: sticky;
      top: 0;
      z-index: 2;
      border-top-left-radius: 12px;
      border-top-right-radius: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .view-popup-header h3 {
      margin: 0;
      font-size: 24px;
      text-align: center;
      flex-grow: 1;
    }

    /* Close Button in View Popup */
    .view-popup-header .close-view-popup-btn {
      background: transparent;
      border: none;
      color: #ffffff;
      font-size: 24px;
      cursor: pointer;
      line-height: 1;
      padding: 0;
      margin-left: 10px;
      transition: color 0.3s ease;
    }

    .view-popup-header .close-view-popup-btn:hover {
      color: #adb5bd;
    }

    .view-popup-content {
      padding: 20px;
      overflow-y: auto; /* Enable vertical scrolling */
      flex-grow: 1;
      max-height: calc(80vh - 160px); /* Adjust based on popup's max-height minus header and footer */
    }

    .view-popup-footer {
      padding: 10px 20px;
      background-color: #f8f9fa;
      border-bottom-left-radius: 12px;
      border-bottom-right-radius: 12px;
      position: sticky;
      bottom: 0;
      z-index: 2;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      border-top: 1px solid #dee2e6;
    }

    .view-popup .close-btn {
      background-color: #6c757d;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .view-popup .close-btn:hover {
      background-color: #5a6268;
    }
    /* ==================== End of New View Popup Styles ==================== */

    /* Responsive Design */
    @media (max-width: 1600px) {
      .journey-step {
        width: 160px;
        height: 200px;
      }

      .drop-zone {
        width: 130px;
        height: 130px;
      }

      .rectangle, .dragging-ghost, .placeholder {
        width: 130px; /* Increased width */
        height: 130px; /* Increased height */
      }

      .rectangle-name {
        font-size: 13px;
        margin-bottom: 8px;
      }

      .tool-menu {
        max-width: 600px;
      }

      /* Adjust Remove Button Size */
      .remove-button {
        width: 20px;
        height: 20px;
      }

      /* Adjust Dividing Line */
      .journey-step.last-in-row::before {
        height: 35px;
      }

      /* New Styles for Full-Width Title Input with Padding */
      .popup input#popup-title {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ced4da;
        border-radius: 6px;
        font-size: 16px;
        outline: none;
        transition: box-shadow 0.3s ease, border-color 0.3s ease;
      }

      .popup input#popup-title:focus {
        border-color: #17a2b8;
        box-shadow: 0 0 5px rgba(23, 162, 184, 0.5);
      }

      /* Optional: Adjust the label to align with the input field */
      .popup label[for="popup-title"] {
        margin-bottom: 5px;
        display: block;
      }

      /* Add 5px margin-bottom to title container for spacing */
      .popup-content > div:first-child {
        margin-bottom: 15px; /* Increased spacing between title and notering */
      }

      /* Add 5px margin-top to notering-section */
      .notering-section {
        margin-top: 5px; /* Added 5px distance */
      }

      /* Set default height of the note-field to 200px */
      .note-field {
        height: 200px; /* Set default height to 200px */
        min-height: 200px; /* Ensure it doesn't shrink below 200px */
        overflow: auto; /* Allow scrolling if content exceeds */
      }
    }

    @media (max-width: 1400px) {
      .journey-path {
        max-width: 1400px;
      }
    }

    @media (max-width: 1200px) {
      .journey-path {
        max-width: 1000px;
      }
    }

    @media (max-width: 768px) {
      body {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        flex-direction: row;
        overflow-x: auto;
        padding: 15px 10px;
      }

      .sidebar.back {
        transform: translateX(-100%);
      }

      .sidebar.slide-in {
        transform: translateX(0);
      }

      .current-title {
        font-size: 20px;
      }

      .search-bar {
        width: 80%;
      }

      .category {
        flex-direction: column;
        align-items: flex-start;
        position: relative;
      }

      .subcategory-list {
        position: absolute;
        top: 100%;
        left: 0;
        background-color: #495057;
        width: 100%;
        border-radius: 0 0 6px 6px;
        z-index: 100;
      }

      .journey-path {
        flex-direction: row; /* Maintain row direction with wrapping */
        align-items: center;
        min-width: 100%;
        padding: 15px 0;
        gap: 30px; /* Adjust gap for smaller screens */
      }

      .journey-line {
        top: 50%;
        left: 0;
        right: 0;
        height: 4px;
      }

      .journey-step {
        width: 140px;
        height: 180px;
      }

      .journey-step::after {
        width: 4px;
        height: 40px;
        top: 50%;
        left: 100%;
        transform: translateY(-50%);
      }

      .drop-zone {
        width: 100px;
        height: 100px;
      }

      .rectangle, .dragging-ghost, .placeholder {
        width: 100px;
        height: 100px;
      }

      .rectangle {
        font-size: 12px; /* Further reduce font size for small rectangles */
      }

      .rectangle-name,
      .rectangle-title {
        font-size: 11px;
      }

      .tool-menu {
        max-width: 300px;
      }

      .switch {
        width: 40px;
        height: 20px;
      }

      .slider:before {
        height: 16px;
        width: 16px;
        left: 2px;
        bottom: 2px;
      }

      input:checked + .slider:before {
        transform: translateX(20px);
      }

      /* Adjust Remove Button Size */
      .remove-button {
        width: 18px;
        height: 18px;
        font-size: 14px;
      }

      /* Adjust Dividing Line */
      .journey-step.last-in-row::before {
        height: 30px;
      }

      /* Toolbar Adjustments for Small Screens */
      .toolbar-container {
        gap: 4px; /* Reduce gap between label and toolbar */
      }

      #toolbar {
        /* Adjust toolbar layout if necessary */
      }

      /* Ensure the note field adjusts height on smaller screens */
      .note-field {
        height: 200px; /* Consistent height across devices */
      }

      /* Add 5px margin-bottom to title container for spacing */
      .popup-content > div:first-child {
        margin-bottom: 15px; /* Increased spacing between title and notering */
      }

      /* Add 5px margin-top to notering-section */
      .notering-section {
        margin-top: 5px; /* Added 5px distance */
      }

      /* Set default height of the note-field to 200px */
      .note-field {
        height: 200px; /* Set default height to 200px */
        min-height: 200px; /* Ensure it doesn't shrink below 200px */
        overflow: auto; /* Allow scrolling if content exceeds */
      }
    }

    /* Responsive Toolbar */
    @media (max-width: 768px) {
      #toolbar {
        flex-wrap: wrap;
      }
    }

    /* Hover Popup Styles */
    .hover-popup {
      position: absolute;
      background-color: #ffffff;
      border: 1px solid #ced4da;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      z-index: 3000;
      width: 250px;
      opacity: 0;
      visibility: hidden;
      pointer-events: none; /* Allows mouse events to pass through */
      transition: opacity 0.3s ease, visibility 0.3s ease;
    }

    .hover-popup.visible {
      opacity: 1;
      visibility: visible;
    }

    .hover-popup h4 {
      margin-top: 0;
      font-size: 18px;
      color: #343a40;
    }

    .hover-popup p {
      margin: 5px 0;
      font-size: 14px;
      color: #495057;
    }

    .hover-popup label {
      font-weight: bold;
      display: block;
      margin-top: 10px;
      font-size: 14px;
      color: #343a40;
    }

    .hover-popup .popup-field {
      margin-bottom: 10px;
      font-size: 14px;
      color: #495057;
      word-wrap: break-word;
    }
  </style>

</head>
<body>

  <!-- Sidebar Menu -->

  <div class="sidebar slide-in" id="sidebar">
    <!-- Current Title (Shows Classes or Student Name) -->
    <div class="current-title" id="current-title" tabindex="0" aria-label="Back to Classes">
      <h2>Strategimeny</h2>
    </div>

<!-- Search Bar -->
<div class="search-bar" id="search-bar">
  <input type="text" id="search-input" placeholder="Sök strategier..." aria-label="Sök strategier">
  <button id="clear-search" class="clear-search" aria-label="Rensa sökning">×</button>
</div>

<!-- Categories and Subcategories -->
<?php
// Define classes and students
$classes = [
    '7' => [
        'alice' => 'Alice',
        'bob' => 'Bob',
        'charlie' => 'Charlie'
    ],
    '8' => [
        'david' => 'David',
        'eva' => 'Eva',
        'frank' => 'Frank'
    ],
    '9' => [
        'grace' => 'Grace',
        'henry' => 'Henry',
        'irene' => 'Irene'
    ]
];

// Function to generate classes and students
function renderClasses($classes) {
    foreach ($classes as $classNumber => $students) {
        echo '<div class="category" tabindex="0" aria-expanded="false" role="button">';
        echo '<span>Klasse ' . htmlspecialchars($classNumber, ENT_QUOTES, 'UTF-8') . '</span>';
        echo '<span class="arrow">▶</span>';
        echo '</div>';
        echo '<div class="subcategory-list">';
        foreach ($students as $studentId => $studentName) {
            echo '<div class="subcategory" data-class="' . htmlspecialchars($classNumber, ENT_QUOTES, 'UTF-8') . '" data-student="' . htmlspecialchars($studentId, ENT_QUOTES, 'UTF-8') . '" tabindex="0">' . htmlspecialchars($studentName, ENT_QUOTES, 'UTF-8') . '</div>';
        }
        echo '</div>';
    }
}

renderClasses($classes);
?>

<!-- Add more classes and students as needed -->
content_copy
 Use code with caution.
  </div>

  <!-- Main Content with Journey Path and Tool Menu -->

  <div class="main-content delete-disabled drag-disabled"> <!-- Added delete-disabled and drag-disabled by default -->
    <div class="journey-path" id="journey-container">
      <div class="journey-line"></div>
      <!-- Journey steps will be added dynamically here -->
    </div>
  </div>

  <!-- Toast Notification -->

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

  <!-- Popup for Rich Text Editing -->

  <div class="popup-overlay" id="popup-overlay">
    <div class="popup">
      <div class="popup-header">
        <h3 id="popup-header">Redigera Strategi</h3>
        <button class="close-popup-btn" aria-label="Stäng Popup">&times;</button>
      </div>
      <div class="popup-content">
        <!-- Title Input -->
        <div>
          <label for="popup-title">Titel:</label>
          <input type="text" id="popup-title" placeholder="Ange titel..." aria-label="Strategi Titel">
        </div>

<!-- Notering Label and Toolbar Container -->
    <!-- Notering Section: Toolbar and Note Field Wrapped Together -->
    <div class="notering-section">
      <div class="toolbar-container">
        <label for="popup-note">Notering:</label>

        <!-- Quill Toolbar -->
        <div id="toolbar">

          <select class="ql-header" aria-label="Header">
            <option value="1">Heading</option>
            <option value="2">Subheading</option>
            <option selected>Normal</option>
          </select>
          <button class="ql-bold" aria-label="Bold"></button>
          <button class="ql-italic" aria-label="Italic"></button>
          <button class="ql-underline" aria-label="Underline"></button>
          <button class="ql-strike" aria-label="Strikethrough"></button>
          <button class="ql-blockquote" aria-label="Blockquote"></button>
          <button class="ql-list" value="ordered" aria-label="Numbered List"></button>
          <button class="ql-list" value="bullet" aria-label="Bullet List"></button>
          <button class="ql-link" aria-label="Insert Link"></button>
          <button class="ql-image" aria-label="Insert Image"></button>
          <!-- Add more toolbar options as needed -->
        </div>
      </div>

      <!-- Note Field -->
      <div id="popup-note" class="note-field" aria-label="Strategi Notering"></div>
    </div>
  </div>
  <div class="popup-footer">
    <button class="save-btn" id="save-btn">Spara</button>
    <button class="cancel-btn" id="cancel-btn">Avbryt</button>
  </div>
</div>
content_copy
 Use code with caution.
  </div>

  <!-- New View Popup for Checked Rectangles -->

  <div class="view-popup-overlay" id="view-popup-overlay">
    <div class="view-popup">
      <div class="view-popup-header">
        <h3 id="view-popup-header">Strategi Detaljer</h3>
        <button class="close-view-popup-btn" aria-label="Stäng Popup">&times;</button>
      </div>
      <div class="view-popup-content">
        <!-- Label (Name) Display -->
        <div>
          <label for="view-name">Namn:</label>
          <div id="view-name" class="view-field"></div>
        </div>

<!-- Text (Title) Display -->
    <div>
      <label for="view-title">Titel:</label>
      <div id="view-title" class="view-field"></div>
    </div>

    <!-- Note (Notering) Display -->
    <div>
      <label for="view-note">Notering:</label>
      <div id="view-note" class="view-field"></div>
    </div>
  </div>
  <div class="view-popup-footer">
    <button class="close-btn" id="view-close-btn">Stäng</button>
  </div>
</div>
content_copy
 Use code with caution.
  </div>
  <!-- ==================== End of New View Popup ==================== -->

  <!-- Hover Popup for Checked Sections -->

  <div class="hover-popup" id="hover-popup">
    <h4 id="hover-title">Titel Här</h4>
    <label for="hover-note">Notering:</label>
    <div class="popup-field" id="hover-note"></div>
  </div>

  <!-- Quill JS -->

  <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

  <script>
    (function() {
      const sidebar = document.getElementById('sidebar');
      const currentTitle = document.getElementById('current-title');
      const journeyContainer = document.getElementById('journey-container');
      const toast = document.getElementById('toast');
      const searchInput = document.getElementById('search-input');
      const clearSearchBtn = document.getElementById('clear-search');
      const popupOverlay = document.getElementById('popup-overlay');
      const popupHeader = document.getElementById('popup-header');
      const popupTitle = document.getElementById('popup-title');
      const saveBtn = document.getElementById('save-btn');
      const cancelBtn = document.getElementById('cancel-btn');
      const closePopupBtn = document.querySelector('.close-popup-btn');
      const viewPopupOverlay = document.getElementById('view-popup-overlay');
      const viewPopupHeader = document.getElementById('view-popup-header');
      const viewName = document.getElementById('view-name');
      const viewTitle = document.getElementById('view-title');
      const viewNote = document.getElementById('view-note');
      const viewCloseBtn = document.getElementById('view-close-btn');
      const hoverPopup = document.getElementById('hover-popup');
      const hoverTitle = document.getElementById('hover-title');
      const hoverNote = document.getElementById('hover-note');

      let quill; // Quill editor instance
      let draggedElement = null;
      let ghostElement = null;
      let isTouch = false;
      let isDraggingEnabled = false; // Disabled by default
      let isDeleteEnabled = false;   // Disabled by default

      let currentEditingRect = null; // The rectangle being edited
      let savedData = {}; // Object to store saved data (title, note, and checked) for each rectangle

      let selectedClass = null;    // Currently selected class
      let selectedStudent = null;  // Currently selected student

      // Initialize Quill editor when the popup is opened
      function initializeQuill() {
        quill = new Quill('#popup-note', {
          theme: 'snow',
          modules: {
            toolbar: '#toolbar'
          },
          placeholder: 'Skriv din text här...',
          scrollingContainer: '#popup-note'
        });

        // Listen to text-change events to adjust height
        quill.on('text-change', function() {
          autoResizeQuill();
        });

        // Initial resize
        autoResizeQuill();
      }

      // Function to auto-resize Quill editor
      function autoResizeQuill() {
        const editor = document.querySelector('#popup-note .ql-editor');
        const container = document.getElementById('popup-note');

        // Reset height to auto to calculate the new height
        container.style.height = 'auto';

        // Set the height based on the content, but ensure it doesn't exceed 200px
        const desiredHeight = Math.min(editor.scrollHeight, 200);
        container.style.height = `${desiredHeight}px`;
      }

      // Function to show toast notifications
      function showToast(message) {
        toast.textContent = message;
        toast.classList.add('show');
        setTimeout(() => { toast.classList.remove('show'); }, 3000);
      }

      // Utility function to create elements with classes and attributes
      function createElement(tag, classNames = [], attributes = {}) {
        const el = document.createElement(tag);
        classNames.forEach(cls => el.classList.add(cls));
        for (const attr in attributes) {
          el.setAttribute(attr, attributes[attr]);
        }
        return el;
      }

      // Function to find the first empty drop zone
      function findFirstEmptyDropZone() {
        return document.querySelector('.drop-zone:not(:has(.rectangle))');
      }

      // Function to add a new journey step with a drop zone
      function addJourneyStep() {
        const newStepIndex = document.querySelectorAll('.drop-zone').length;

        const journeyStep = createElement('div', ['journey-step']);

        const dropZone = createElement('div', ['drop-zone'], {
          'data-index': newStepIndex,
          'aria-label': 'Drop zone för strategi',
          'tabindex': '0'
        });

        journeyStep.appendChild(dropZone);
        journeyContainer.appendChild(journeyStep);

        // Update connectors after adding a new step
        updateConnectors();
        // Save state
        saveState();
      }

      // Function to create a rectangle with a remove button, name, title, and tooltip
      function createRectangle(type, name, title = '', checked = false) {
        const rect = createElement('div', ['rectangle', type], {
          'draggable': 'true',
          'tabindex': '0',
          'role': 'button',
          'aria-label': `Strategi: ${name}`
        });
        rect.dataset.id = 'rect-' + Math.random().toString(36).substr(2, 9);

        if (checked) {
          rect.classList.add('dimmed', 'checked');
        }

        // Initialize savedData for this rectangle
        if (!savedData[rect.dataset.id]) {
          savedData[rect.dataset.id] = {
            title: title,
            note: '',
            checked: checked
          };
        }

        // Remove Button
        const removeButton = createElement('button', ['remove-button'], {
          'aria-label': 'Ta bort strategi'
        });
        removeButton.innerHTML = '&times;';
        const removeTooltip = createElement('div', ['tooltip']);
        removeTooltip.textContent = 'Ta bort';
        removeButton.appendChild(removeTooltip);
        rect.appendChild(removeButton);

        // Name Div
        const nameDiv = createElement('div', ['rectangle-name']);
        nameDiv.textContent = name;
        rect.appendChild(nameDiv);

        // Title Div
        const titleDiv = createElement('div', ['rectangle-title']);
        titleDiv.innerHTML = title;
        rect.appendChild(titleDiv);

        // Checkmark
        const checkmark = createElement('div', ['checkmark'], {
          'aria-label': 'Markera strategi som klar',
          'tabindex': '0'
        });
        const checkmarkTooltip = createElement('div', ['tooltip']);
        checkmarkTooltip.textContent = 'Markera som klar';
        checkmark.appendChild(checkmarkTooltip);
        rect.appendChild(checkmark);

        // Event Listener for Checkmark Click
        checkmark.addEventListener('click', (e) => {
          e.stopPropagation();
          toggleCheckmark(rect);
        });

        // Keyboard Accessibility for Checkmark
        checkmark.addEventListener('keypress', (e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            toggleCheckmark(rect);
          }
        });

        return rect;
      }

      // Handle Class and Student Selection using Event Delegation
      sidebar.addEventListener('click', (e) => {
        const category = e.target.closest('.category');
        if (category) {
          const isExpanded = category.classList.toggle('expanded');
          category.setAttribute('aria-expanded', isExpanded);
          // Toggle corresponding subcategory list
          const subcategoryList = category.nextElementSibling;
          if (subcategoryList) {
            subcategoryList.classList.toggle('expanded');
          }
          return;
        }

        const subcategory = e.target.closest('.subcategory');
        if (subcategory) {
          // Remove 'selected' class from all subcategories
          document.querySelectorAll('.subcategory').forEach(sub => sub.classList.remove('selected'));
          // Add 'selected' class to the clicked subcategory
          subcategory.classList.add('selected');

          // Set selected class and student
          selectedClass = subcategory.getAttribute('data-class');
          selectedStudent = subcategory.getAttribute('data-student');

          // Get student name
          const studentName = subcategory.textContent.trim();

          // Update sidebar to show student name as title
          currentTitle.innerHTML = `
            <h2>${studentName}</h2>
          `;

          // Slide sidebar to show student-specific menu
          sidebar.classList.remove('slide-in');
          setTimeout(() => {
            sidebar.classList.add('slide-in');
          }, 10);

          // Clear existing journey-path
          journeyContainer.innerHTML = '<div class="journey-line"></div>';

          // Load state for the selected student
          loadState();
        }
      });

      // Enable keyboard accessibility for categories and subcategories using Event Delegation
      sidebar.addEventListener('keypress', (e) => {
        const category = e.target.closest('.category');
        if (category && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          category.click();
        }

        const subcategory = e.target.closest('.subcategory');
        if (subcategory && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          subcategory.click();
        }

        const current = e.target.closest('.current-title');
        if (current && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          resetSidebarToClasses();
        }
      });

      // Function to reset sidebar to show classes
      function resetSidebarToClasses() {
        currentTitle.innerHTML = `
          <h2>Strategimeny</h2>
        `;
        // Slide sidebar back to show classes
        sidebar.classList.remove('slide-in');
        setTimeout(() => {
          sidebar.classList.add('slide-in');
        }, 10);

        // Clear existing journey-path
        journeyContainer.innerHTML = '<div class="journey-line"></div>';
      }

      // Function to remove a rectangle and its drop-zone, and possibly the journey-step
      function removeRectangle(rect) {
        const dropZone = rect.parentElement;
        const journeyStep = dropZone.parentElement;

        const rectId = rect.dataset.id;
        delete savedData[rectId]; // Remove saved data

        rect.remove(); // Remove the rectangle
        dropZone.remove(); // Remove the drop-zone

        // Check if the journeyStep has any other drop-zones (it shouldn't, but just in case)
        if (journeyStep.querySelectorAll('.drop-zone').length === 0) {
          journeyStep.remove(); // Remove the journey-step if no drop-zones left
        }

        // After removing, update connectors
        updateConnectors();
        // Save state
        saveState();
      }

      // Function to swap two elements in the journey path
      function swapElements(el1, el2) {
        const parent1 = el1.parentElement;
        const parent2 = el2.parentElement;

        // Swap in the DOM
        parent1.appendChild(el2);
        parent2.appendChild(el1);

        // After swapping, update connectors
        updateConnectors();
        // Save state
        saveState();
      }

      // Handle Drag Start (Mouse)
      function handleDragStart(e) {
        if (!isDraggingEnabled || !selectedClass || !selectedStudent) return; // Do nothing if dragging is disabled or no student selected

        const targetRect = e.target.closest('.rectangle');
        if (targetRect) {
          draggedElement = targetRect;
          draggedElement.classList.add('dragging');

          // Create a ghost element
          ghostElement = draggedElement.cloneNode(true);
          ghostElement.classList.add('dragging-ghost');
          document.body.appendChild(ghostElement);
          updateGhostPosition(e.pageX, e.pageY);

          // Hide the original element
          setTimeout(() => {
            draggedElement.style.opacity = '0';
          }, 0);

          e.dataTransfer.effectAllowed = 'move';
          e.dataTransfer.setData('text/plain', ''); // Required for Firefox
        }
      }

      // Handle Drag Over (Mouse)
      function handleDragOver(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';

        const dropZone = e.target.closest('.drop-zone');
        if (dropZone && dropZone !== draggedElement.parentElement) {
          document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
          dropZone.classList.add('over');
        }
      }

      // Handle Drop (Mouse)
      function handleDrop(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        e.preventDefault();
        const dropZone = e.target.closest('.drop-zone');
        if (dropZone && draggedElement) {
          const targetRect = dropZone.querySelector('.rectangle');
          if (targetRect && targetRect !== draggedElement) {
            swapElements(draggedElement, targetRect);
          } else if (!targetRect) {
            dropZone.appendChild(draggedElement);
            // After adding, update connectors
            updateConnectors();
            // Save state
            saveState();
          }
        }
        endDrag();
      }

      // Handle Drag End (Mouse)
      function handleDragEnd(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        endDrag();
        document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
      }

      // End Dragging
      function endDrag() {
        if (draggedElement) {
          draggedElement.classList.remove('dragging');
          draggedElement.style.opacity = '1';
          draggedElement = null;
        }
        if (ghostElement) {
          ghostElement.remove();
          ghostElement = null;
        }
      }

      // Update Ghost Position
      function updateGhostPosition(x, y) {
        if (ghostElement) {
          ghostElement.style.left = `${x - ghostElement.offsetWidth / 2}px`;
          ghostElement.style.top = `${y - ghostElement.offsetHeight / 2}px`;
        }
      }

      // Handle Mouse Move for Ghost
      function handleMouseMove(e) {
        if (ghostElement) {
          updateGhostPosition(e.pageX, e.pageY);
        }
      }

      // Handle Touch Start
      function handleTouchStart(e) {
        if (!isDraggingEnabled || !selectedClass || !selectedStudent) return; // Do nothing if dragging is disabled or no student selected

        const touch = e.touches[0];
        const targetRect = e.target.closest('.rectangle');
        if (targetRect) {
          isTouch = true;
          draggedElement = targetRect;
          draggedElement.classList.add('dragging');

          const rect = draggedElement.getBoundingClientRect();
          const offsetX = touch.clientX - rect.left;
          const offsetY = touch.clientY - rect.top;

          // Create a ghost element
          ghostElement = draggedElement.cloneNode(true);
          ghostElement.classList.add('dragging-ghost');
          ghostElement.style.left = `${touch.pageX - rect.width / 2}px`;
          ghostElement.style.top = `${touch.pageY - rect.height / 2}px`;
          document.body.appendChild(ghostElement);

          // Hide the original element
          draggedElement.style.opacity = '0';

          document.addEventListener('touchmove', handleTouchMove, { passive: false });
          document.addEventListener('touchend', handleTouchEnd);
        }
      }

      // Handle Touch Move
      function handleTouchMove(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        if (ghostElement && e.touches.length === 1) {
          e.preventDefault();
          const touch = e.touches[0];
          ghostElement.style.left = `${touch.pageX - ghostElement.offsetWidth / 2}px`;
          ghostElement.style.top = `${touch.pageY - ghostElement.offsetHeight / 2}px`;

          const elemBelow = document.elementFromPoint(touch.clientX, touch.clientY);
          const targetDropZone = elemBelow ? elemBelow.closest('.drop-zone') : null;

          document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
          if (targetDropZone && targetDropZone !== draggedElement.parentElement) {
            targetDropZone.classList.add('over');
          }
        }
      }

      // Handle Touch End
      function handleTouchEnd(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        const touch = e.changedTouches[0];
        const elemBelow = document.elementFromPoint(touch.clientX, touch.clientY);
        const targetDropZone = elemBelow ? elemBelow.closest('.drop-zone') : null;

        if (draggedElement && targetDropZone) {
          const targetRect = targetDropZone.querySelector('.rectangle');
          if (targetRect && targetRect !== draggedElement) {
            swapElements(draggedElement, targetRect);
          } else if (!targetRect) {
            targetDropZone.appendChild(draggedElement);
            // After adding, update connectors
            updateConnectors();
            // Save state
            saveState();
          }
        }

        endDrag();
        document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
        document.removeEventListener('touchmove', handleTouchMove);
        document.removeEventListener('touchend', handleTouchEnd);
      }

      // Function to update connectors based on row positions with alternating last-in-row
      function updateConnectors() {
        const journeySteps = Array.from(document.querySelectorAll('.journey-step'));

        // Reset all journey-steps by removing the 'last-in-row' class
        journeySteps.forEach(step => step.classList.remove('last-in-row'));

        if (journeySteps.length === 0) {
          // If no steps, ensure dividing lines are hidden
          journeyPath.classList.remove('single-row');
          return;
        }

        // Determine the row each step is in by its top position
        const rowMap = {};
        journeySteps.forEach(step => {
          const top = step.getBoundingClientRect().top;
          // Use a tolerance to group steps in the same row
          let rowFound = false;
          for (let row in rowMap) {
            if (Math.abs(rowMap[row].top - top) < 10) { // 10px tolerance
              rowMap[row].steps.push(step);
              rowFound = true;
              break;
            }
          }
          if (!rowFound) {
            // If no existing row matches, create a new row
            rowMap[Object.keys(rowMap).length] = { top: top, steps: [step] };
          }
        });

        const rows = Object.values(rowMap);

        // Check if there's only one row
        if (rows.length <= 1) {
          // Add 'single-row' class to hide dividing lines
          journeyPath.classList.add('single-row');
        } else {
          // Remove 'single-row' class if multiple rows exist
          journeyPath.classList.remove('single-row');

          // Iterate through each row and apply 'last-in-row' accordingly
          rows.forEach((row, index) => {
            // Only add 'last-in-row' if there's a row after the current one
            if (index < rows.length -1) {
              if (index % 2 === 0) { // Even index: first row, third row, etc.
                const lastStep = row.steps[row.steps.length - 1];
                if (lastStep) {
                  lastStep.classList.add('last-in-row');
                }
              } else { // Odd index: second row, fourth row, etc.
                const firstStep = row.steps[0];
                if (firstStep) {
                  firstStep.classList.add('last-in-row');
                }
              }
            }
          });
        }
      }

      // Handle Tool Menu Toggle for Dragging
      // Not needed as per instructions (no extra buttons), so removed

      // Handle Tool Menu Toggle for Deletion
      // Not needed as per instructions, since strategy management is handled via drop zones

      // Initialize with empty journey-path (since selection is required)
      document.addEventListener('DOMContentLoaded', () => {
        // Initialize Quill
        initializeQuill();
        // Load state from the server if any (initially none)

        // Ensure delete and drag are disabled by default
        document.querySelector('.main-content').classList.add('delete-disabled', 'drag-disabled');

        // Initialize Search Functionality
        initializeSearch();
      });

      // Update connectors on window resize to handle dynamic layout changes
      window.addEventListener('resize', () => {
        updateConnectors();
      });

      // Add Event Listeners for Mouse
      journeyContainer.addEventListener('dragstart', handleDragStart);
      journeyContainer.addEventListener('dragover', handleDragOver);
      journeyContainer.addEventListener('drop', handleDrop);
      journeyContainer.addEventListener('dragend', handleDragEnd);
      document.addEventListener('mousemove', handleMouseMove);

      // Add Event Listeners for Touch
      journeyContainer.addEventListener('touchstart', handleTouchStart, { passive: false });

      // Prevent default dragover behavior to allow drop
      document.addEventListener('dragover', function(e) {
        e.preventDefault();
      }, false);

      document.addEventListener('drop', function(e) {
        e.preventDefault();
      }, false);

      // Persisting State with Server-Side PHP
      function saveState() {
        if (!selectedClass || !selectedStudent) {
          showToast('Välj en klass och student att spara strategier för.');
          return;
        }

        const journeySteps = Array.from(document.querySelectorAll('.journey-step')).map(step => {
          const dropZone = step.querySelector('.drop-zone');
          if (dropZone) {
            const rect = dropZone.querySelector('.rectangle');
            if (rect) {
              const type = [...rect.classList].find(cls => cls !== 'rectangle');
              const name = rect.querySelector('.rectangle-name').textContent;
              const title = rect.querySelector('.rectangle-title').innerHTML; // Use innerHTML to preserve formatting
              const rectId = rect.dataset.id;
              const note = savedData[rectId] ? savedData[rectId].note : '';
              const checked = savedData[rectId] ? savedData[rectId].checked : false;
              return { id: rectId, type, name, title, note: note || null, checked };
            }
          }
          return null;
        }).filter(step => step !== null);

        // Send the state to the server via AJAX
        fetch('', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            'action': 'saveState',
            'class': selectedClass,
            'student': selectedStudent,
            'data': JSON.stringify(journeySteps),
            'csrf_token': '<?php echo $_SESSION['csrf_token']; ?>'
          })
        })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            showToast('Strategier sparade för ' + getStudentName(selectedClass, selectedStudent) + '.');
          } else {
            showToast('Kunde inte spara till servern: ' + data.message);
          }
        })
        .catch(() => {
          showToast('Ett fel uppstod vid spara till servern.');
        });
      }

      // Function to load the saved state
      function loadState() {
        if (!selectedClass || !selectedStudent) return;

        // Request the state from the server via AJAX
        fetch('', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            'action': 'loadState',
            'class': selectedClass,
            'student': selectedStudent,
            'csrf_token': '<?php echo $_SESSION['csrf_token']; ?>'
          })
        })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success' && data.data) {
            data.data.forEach(step => {
              const rect = createRectangle(step.type, step.name, step.title, step.checked);
              const dropZone = findFirstEmptyDropZone();
              if (dropZone) {
                dropZone.appendChild(rect);
              } else {
                // If no empty drop zone, add a new journey step
                addJourneyStep();
                const newDropZone = findFirstEmptyDropZone();
                if (newDropZone) {
                  newDropZone.appendChild(rect);
                }
              }
            });
            updateConnectors();
          }
        })
        .catch(() => {
          showToast('Ett fel uppstod vid laddning från servern.');
        });
      }

      // Function to toggle the checkmark state
      function toggleCheckmark(rect) {
        const rectId = rect.dataset.id;
        if (rect.classList.contains('checked')) {
          rect.classList.remove('checked', 'dimmed');
          if (savedData[rectId]) {
            savedData[rectId].checked = false;
          }
          showToast('Strategi markerad som oavslutad.');
        } else {
          rect.classList.add('checked', 'dimmed');
          if (!savedData[rectId]) {
            savedData[rectId] = { title: '', note: '', checked: true };
          }
          savedData[rectId].checked = true;
          showToast('Strategi markerad som avslutad.');
        }
        // Save the updated state to the server
        saveState();
      }

      // Function to get student name based on class and student ID
      function getStudentName(classNumber, studentId) {
        const classes = {
          '7': { 'alice': 'Alice', 'bob': 'Bob', 'charlie': 'Charlie' },
          '8': { 'david': 'David', 'eva': 'Eva', 'frank': 'Frank' },
          '9': { 'grace': 'Grace', 'henry': 'Henry', 'irene': 'Irene' }
        };
        return classes[classNumber][studentId] || 'Okänd Student';
      }

      // Function to open the popup
      function openPopup() {
        popupOverlay.style.display = 'flex';
        quill.focus();
      }

      // Function to close the popup
      function closePopup() {
        popupOverlay.style.display = 'none';
        currentEditingRect = null;
        popupTitle.value = '';
        quill.root.innerHTML = '';
        popupHeader.textContent = 'Redigera Strategi'; // Reset header
      }

      // Function to open the view popup as a modal showing both title and note
      function openViewPopup(rect) {
        const rectId = rect.dataset.id;
        const name = rect.querySelector('.rectangle-name').textContent;
        const title = savedData[rectId] ? savedData[rectId].title : '';
        const note = savedData[rectId] ? savedData[rectId].note : '';

        // Populate the view popup
        viewName.textContent = name;
        viewTitle.innerHTML = title || 'Ingen titel';
        viewNote.innerHTML = note || 'Ingen notering';

        // Set dynamic header text
        viewPopupHeader.textContent = `DETALJER FÖR ${name}`;

        // Show the view popup
        viewPopupOverlay.style.display = 'flex';
      }

      // Function to close the view popup
      function closeViewPopup() {
        viewPopupOverlay.style.opacity = '0';
        setTimeout(() => {
          viewPopupOverlay.style.display = 'none';
          viewPopupHeader.textContent = 'Strategi Detaljer'; // Reset header
        }, 300);
      }

      // Handle Save Button in Popup
      saveBtn.addEventListener('click', () => {
        if (!currentEditingRect) {
          showToast('Ingen strategi att spara.');
          return;
        }

        const title = popupTitle.value.trim();
        const note = quill.root.innerHTML.trim(); // Get HTML content from Quill

        const rectId = currentEditingRect.dataset.id;

        if (title !== '' || quill.getText().trim() !== '') {
          // Save the data
          if (!savedData[rectId]) {
            savedData[rectId] = { title: '', note: '', checked: false };
          }
          savedData[rectId].title = title;
          savedData[rectId].note = quill.root.innerHTML;

          // Update the title in the rectangle
          const titleDiv = currentEditingRect.querySelector('.rectangle-title');
          if (titleDiv) {
            titleDiv.innerHTML = title || 'Ingen titel'; // Use innerHTML to allow rich text in title if needed
          }

          showToast('Data sparad.');
        } else {
          // Remove the saved data if both fields are empty
          delete savedData[rectId];
          // Clear the title
          const titleDiv = currentEditingRect.querySelector('.rectangle-title');
          if (titleDiv) {
            titleDiv.innerHTML = '';
          }
          showToast('Data borttagen.');
        }
        // Save state to server
        saveState();
        closePopup();
      });

      // Handle Cancel Button in Popup
      cancelBtn.addEventListener('click', () => {
        closePopup();
      });

      // Handle Close Button in Edit Popup
      closePopupBtn.addEventListener('click', () => {
        closePopup();
      });

      // Handle Close Button in View Popup
      viewCloseBtn.addEventListener('click', () => {
        closeViewPopup();
      });

      // Function to handle rectangle clicks
      function handleRectangleClick(rect) {
        if (rect.classList.contains('checked')) {
          // If rectangle is checked, open the view popup
          openViewPopup(rect);
        } else {
          // If unchecked, open the editable popup
          popupTitle.value = savedData[rect.dataset.id] ? savedData[rect.dataset.id].title : '';
          quill.root.innerHTML = savedData[rect.dataset.id] ? savedData[rect.dataset.id].note : '';
          currentEditingRect = rect;

          // Set dynamic header text
          const name = rect.querySelector('.rectangle-name').textContent;
          popupHeader.textContent = `EDIT ${name}`;

          openPopup();
        }
      }

      // Function to initialize search functionality
      function initializeSearch() {
        // Debounce function to limit the rate of function execution
        const debounce = (func, delay) => {
          let timeout;
          return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), delay);
          };
        };

        searchInput.addEventListener('input', debounce(function() {
          const query = this.value.trim().toLowerCase();

          // Show or hide the clear search button
          clearSearchBtn.classList.toggle('visible', query.length > 0);

          // Get all category elements
          const categories = document.querySelectorAll('.sidebar .category');

          categories.forEach(category => {
            const subcategoryList = category.nextElementSibling;
            const subcategories = subcategoryList.querySelectorAll('.subcategory');

            let categoryHasMatch = false;

            subcategories.forEach(subcategory => {
              const subcategoryText = subcategory.textContent.toLowerCase();
              if (subcategoryText.includes(query)) {
                subcategory.style.display = 'flex'; // Show matching subcategory
                subcategory.classList.add('highlight'); // Highlight match
                categoryHasMatch = true;
              } else {
                subcategory.style.display = 'none'; // Hide non-matching subcategory
                subcategory.classList.remove('highlight'); // Remove highlight
              }
            });

            if (query === '') {
              // If search field is empty, show all subcategories and collapse categories
              subcategories.forEach(subcategory => {
                subcategory.style.display = 'flex';
                subcategory.classList.remove('highlight');
              });
              category.classList.remove('expanded');
              subcategoryList.classList.remove('expanded');
              category.setAttribute('aria-expanded', 'false');
            } else {
              if (categoryHasMatch) {
                // Expand category if it has matching subcategories
                category.classList.add('expanded');
                subcategoryList.classList.add('expanded');
                category.setAttribute('aria-expanded', 'true');
              } else {
                // Collapse category if no matching subcategories
                category.classList.remove('expanded');
                subcategoryList.classList.remove('expanded');
                category.setAttribute('aria-expanded', 'false');
              }
            }
          });
        }, 300)); // Adjust the delay (in milliseconds) as needed

        // Handle Clear Search Button Click
        clearSearchBtn.addEventListener('click', () => {
          searchInput.value = '';
          clearSearchBtn.classList.remove('visible');
          searchInput.dispatchEvent(new Event('input')); // Trigger input event to reset the search
        });
      }

      // ==================== Hover Popup Functionality ====================

      // Function to show the hover popup
      function showHoverPopup(rect) {
        const rectId = rect.dataset.id;
        const title = savedData[rectId] ? savedData[rectId].title : '';
        const note = savedData[rectId] ? savedData[rectId].note : '';

        if (title || note) {
          // Populate the hover popup
          hoverTitle.textContent = title || 'Ingen titel';
          hoverNote.innerHTML = note || 'Ingen notering';

          // Temporarily make the popup visible to get its dimensions
          hoverPopup.style.display = 'block';
          hoverPopup.style.visibility = 'hidden';
          hoverPopup.style.opacity = '0';

          const rectBounds = rect.getBoundingClientRect();
          const popupWidth = hoverPopup.offsetWidth;
          const popupHeight = hoverPopup.offsetHeight;
          const viewportWidth = window.innerWidth;
          const viewportHeight = window.innerHeight;

          // Decide where to position the popup: right or below
          let top, left;

          // Prefer positioning to the right
          if (rectBounds.right + popupWidth + 10 < viewportWidth) { // 10px margin
            top = rectBounds.top + window.scrollY;
            left = rectBounds.right + window.scrollX + 10; // 10px to the right
          } else {
            // Otherwise, position below
            top = rectBounds.bottom + window.scrollY + 10; // 10px below
            left = rectBounds.left + window.scrollX;
            // Adjust if it overflows the viewport
            if (left + popupWidth + 10 > viewportWidth) {
              left = viewportWidth - popupWidth - 10;
            }
          }

          // Apply styles
          hoverPopup.style.top = `${top}px`;
          hoverPopup.style.left = `${left}px`;

          // Show the popup
          hoverPopup.classList.add('visible');
        }
      }

      // Function to hide the hover popup
      function hideHoverPopup() {
        hoverPopup.classList.remove('visible');
      }

      // Event delegation for handling hover on checked rectangles using 'mouseenter' and 'mouseleave'
      document.body.addEventListener('mouseenter', function(e) {
        const rect = e.target.closest('.rectangle');
        if (rect && rect.classList.contains('checked')) {
          showHoverPopup(rect);
        }
      }, true); // Use capture phase

      document.body.addEventListener('mouseleave', function(e) {
        const rect = e.target.closest('.rectangle');
        if (rect && rect.classList.contains('checked')) {
          hideHoverPopup();
        }
      }, true); // Use capture phase

      // Prevent the hover popup from interfering with mouse events
      hoverPopup.addEventListener('mouseenter', () => {
        hoverPopup.classList.add('visible');
      });

      hoverPopup.addEventListener('mouseleave', () => {
        hoverPopup.classList.remove('visible');
      });

      // ==================== End of Hover Popup Functionality ====================

      // ==================== Drag and Drop Functionality ====================

      // [Included above]

      // ==================== End of Drag and Drop Functionality ====================

      // ==================== Persisting State with Server-Side PHP ====================

      // Already handled above in saveState and loadState functions

      // ==================== End of Persisting State with Server-Side PHP ====================

    })();
  </script>

</body>
</html>


When clicking on student name it must show the category menu with strategies. just learn form this and update complete code again:
<?php
// index.php

// Start the session with secure settings
session_start([
    'cookie_lifetime' => 0,
    'cookie_secure' => isset($_SERVER['HTTPS']),
    'cookie_httponly' => true,
    'cookie_samesite' => 'Strict'
]);

// CSRF Token Generation
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');

    // CSRF Token Validation
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token']);
        exit();
    }

    switch ($_POST['action']) {
        case 'saveState':
            // Validate JSON
            $data = json_decode($_POST['data'], true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
                exit();
            }
            // Sanitize data
            $_SESSION['journeyState'] = htmlspecialchars($_POST['data'], ENT_QUOTES, 'UTF-8');
            echo json_encode(['status' => 'success']);
            exit();

        case 'loadState':
            if (isset($_SESSION['journeyState'])) {
                echo json_encode(['status' => 'success', 'data' => json_decode($_SESSION['journeyState'], true)]);
            } else {
                echo json_encode(['status' => 'empty']);
            }
            exit();

        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
            exit();
    }
}
?>
<!DOCTYPE html>
<html lang="sv">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lärares Strategijournal</title>

  <!-- Quill CSS -->
  <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

  <style>
    /* Basic Reset */
    *, *::before, *::after {
      box-sizing: border-box;
    }
    body {
      display: flex;
      height: 100vh;
      background: linear-gradient(135deg, #f8f9fa 25%, #e9ecef 100%);
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      color: #343a40;
      overflow: hidden;
    }

    /* Sidebar Menu */
    .sidebar {
      width: 350px;
      background-color: #343a40;
      padding: 20px;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      gap: 15px;
      transition: width 0.3s ease;
    }

    .sidebar.collapsed {
      width: 60px;
    }

    .sidebar h2 {
      color: #ffffff;
      margin-bottom: 10px;
      font-size: 24px;
      text-align: center;
    }

    /* Search Bar */
    .search-bar {
      position: relative;
      margin-bottom: 15px;
    }

    .search-bar input {
      width: 100%;
      padding: 8px 35px 8px 35px; /* Adjusted padding for clear button */
      border: none;
      border-radius: 6px;
      font-size: 14px;
      outline: none;
      transition: box-shadow 0.3s ease;
    }

    .search-bar input:focus {
      box-shadow: 0 0 5px rgba(23, 162, 184, 0.5);
    }

    .search-bar::before {
      content: '🔍';
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      pointer-events: none;
    }

    /* Clear Search Button */
    .search-bar .clear-search {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      background: transparent;
      border: none;
      font-size: 18px;
      color: #adb5bd;
      cursor: pointer;
      display: none; /* Hidden by default */
      padding: 0;
    }

    .search-bar .clear-search.visible {
      display: block;
    }

    .search-bar .clear-search:hover {
      color: #ffffff;
    }

    /* Category Styles */
    .category {
      color: #adb5bd;
      cursor: pointer;
      padding: 12px 15px;
      background-color: #495057;
      border-radius: 8px;
      position: relative;
      transition: background-color 0.3s ease, color 0.3s ease;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
    }

    .category:hover, .category.expanded {
      background-color: #6c757d;
      color: #ffffff;
    }

    .category .arrow {
      transition: transform 0.3s ease;
      font-size: 12px;
    }

    .category.expanded .arrow {
      transform: rotate(90deg);
    }

    .subcategory-list {
      display: none;
      flex-direction: column;
      margin-top: 8px;
      gap: 6px;
      padding-left: 20px;
    }

    .category.expanded + .subcategory-list {
      display: flex;
    }

    .subcategory {
      background-color: #495057;
      padding: 10px 15px;
      border-radius: 6px;
      cursor: pointer;
      color: #ced4da;
      transition: background-color 0.3s ease, color 0.3s ease;
      font-size: 14px;
    }

    .subcategory:hover {
      background-color: #6c757d;
      color: #ffffff;
    }

    /* Highlight search results */
    .subcategory.highlight {
      background-color: #17a2b8;
      color: #ffffff;
    }

    /* Main Content with Journey Path and Tool Menu */
    .main-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 20px;
      overflow: auto;
      position: relative;
    }

    /* Tool Menu */
    .tool-menu {
      margin-top: 25px;
      width: 100%;
      max-width: 700px;
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 30px;
      flex-wrap: wrap;
    }

    .tool-menu label {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      color: #343a40;
    }

    /* Toggle Switch */
    .switch {
      position: relative;
      display: inline-block;
      width: 50px;
      height: 24px;
    }

    .switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }

    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ccc;
      transition: background-color 0.4s;
      border-radius: 24px;
    }

    .slider:before {
      position: absolute;
      content: "";
      height: 18px;
      width: 18px;
      left: 3px;
      bottom: 3px;
      background-color: white;
      transition: transform 0.4s;
      border-radius: 50%;
    }

    input:checked + .slider {
      background-color: #28a745;
    }

    input:checked + .slider:before {
      transform: translateX(26px);
    }

    /* Journey Path Container */
    .journey-path {
      display: flex;
      flex-wrap: wrap; /* Allow wrapping to new lines */
      align-items: center;
      position: relative;
      padding: 20px 0;
      width: 100%;
      max-width: 1600px;
      gap: 40px; /* Space between steps */
    }

    /* Horizontal Connection Lines */
    .journey-line {
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 4px;
      background-color: #dee2e6;
      z-index: 1;
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    /* Dividing Vertical Lines */
    .dividing-line {
      position: absolute;
      width: 4px;
      background-color: #adb5bd;
      z-index: 1;
      transition: background-color 0.3s ease;
    }

    /* Journey Steps */
    .journey-step {
      position: relative;
      z-index: 2;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 180px; /* Increased width */
      height: 220px; /* Increased height to accommodate name and title */
      flex-shrink: 0; /* Prevent steps from shrinking */
      transition: transform 0.3s ease;
    }

    .journey-step:hover {
      transform: scale(1.05);
    }

    /* Drop Zones */
    .drop-zone {
      width: 140px; /* Increased width */
      height: 140px; /* Increased height */
      border: 2px dashed #ced4da;
      border-radius: 12px; /* More rounded corners */
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      transition: border-color 0.3s ease, background-color 0.3s ease;
      background-color: #f8f9fa;
    }

    .drop-zone.over {
      border-color: #17a2b8;
      background-color: rgba(23, 162, 184, 0.1);
    }

    /* Connectors */
    .journey-step::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 100%;
      width: 60px; /* Increased connector length */
      height: 4px;
      background-color: #dee2e6;
      transform: translateY(-50%);
      z-index: -1;
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    .journey-step.last-in-row::after {
      display: none; /* Remove horizontal connector if it's marked as last in row */
    }

    /* Dividing Lines Between Rows */
    .journey-step.last-in-row::before {
      content: '';
      position: absolute;
      top: 100%;
      left: 50%;
      width: 4px;
      height: 60px; /* Increased height */
      background-color: #adb5bd;
      transform: translateX(-50%);
      z-index: -1;
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    /* Hide Dividing Lines When Only One Row */
    .single-row .journey-line {
      display: none;
    }

    /* Grid Items (Rectangles) */
    .rectangle {
      background: linear-gradient(145deg, #6c5ce7, #a29bfe);
      color: #ffffff;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      font-size: 14px;
      border-radius: 12px; /* More rounded corners */
      cursor: grab;
      transition: box-shadow 0.3s ease, transform 0.3s ease, background 0.5s ease, opacity 0.3s ease;
      width: 140px;        /* Increased width */
      height: 140px;       /* Increased height */
      user-select: none;
      padding: 20px 5px 5px 5px;       /* Adjusted padding to make space for checkmark */
      overflow: visible;    /* Allow checkmark to be visible outside */
      position: relative;
      box-sizing: border-box; /* Include padding within dimensions */
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* Soft shadow */
    }

    .rectangle:hover {
      box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2);
      transform: translateY(-5px);
    }

    /* Checkmark Styles */
    .checkmark {
      position: absolute;
      top: -10px; /* Position above the rectangle */
      left: -10px; /* Position to the left of the rectangle */
      width: 20px;
      height: 20px;
      background-color: #ffffff;
      border: 2px solid #343a40;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 10;
    }

    .checkmark::after {
      content: '';
      display: none;
      width: 6px;
      height: 12px;
      border: solid #343a40;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
    }

    /* Show the checkmark when checked */
    .rectangle.checked .checkmark::after {
      display: block;
    }

    /* Dimmed state for checked rectangles */
    .rectangle.dimmed {
      opacity: 0.5;
      transition: opacity 0.3s ease;
    }

    /* Rectangle Name */
    .rectangle-name {
      font-weight: 600;
      margin-bottom: 6px; /* Increased margin for better separation */
      font-size: 14px;
      text-align: center;
      width: 100%;
      word-wrap: break-word;
      border-bottom: 1px solid rgba(255, 255, 255, 0.3); /* Separator line */
      padding-bottom: 4px;
    }

    /* Rectangle Title */
    .rectangle-title {
      font-size: 13px;
      text-align: center;
      word-wrap: break-word;
      word-break: break-word;
      flex-grow: 0;               /* Prevents stretching */
      margin-top: 6px;            /* Provides space above the title */
      padding: 5px;               /* Adds 5px padding inside the title container */
      white-space: normal;        /* Allows text to wrap normally */
      overflow: hidden;           /* Hides any overflowing text */
      text-overflow: ellipsis;    /* Adds ellipsis if text is too long */
      box-sizing: border-box;     /* Ensures padding is included within the element's total width */
      width: 100%;                /* Ensures the title takes the full width of the container */
    }

    /* Inner Text Container */
    .rectangle-text {
      display: none; /* Hide original text container */
    }

    /* Specific Rectangle Types */
    .rectangle.differentiated-instruction { background: linear-gradient(145deg, #ff9a9e, #fad0c4); }
    .rectangle.collaborative-learning { background: linear-gradient(145deg, #a18cd1, #fbc2eb); }
    .rectangle.positive-reinforcement { background: linear-gradient(145deg, #fbc2eb, #a6c1ee); }
    .rectangle.behavior-modeling { background: linear-gradient(145deg, #84fab0, #8fd3f4); }
    .rectangle.individual-tutoring { background: linear-gradient(145deg, #fccb90, #d57eeb); }
    .rectangle.mentoring-programs { background: linear-gradient(145deg, #ffecd2, #fcb69f); }
    .rectangle.feedback-sessions { background: linear-gradient(145deg, #f6d365, #fda085); }
    .rectangle.learning-games { background: linear-gradient(145deg, #cfd9df, #e2ebf0); }
    .rectangle.student-reflections { background: linear-gradient(145deg, #f093fb, #f5576c); }
    /* Additional Rectangle Types */
    .rectangle.observations { background: linear-gradient(145deg, #d4fc79, #96e6a1); }
    .rectangle.specific-adjustments { background: linear-gradient(145deg, #fbc2eb, #a6c1ee); }
    .rectangle.individual-conversations { background: linear-gradient(145deg, #84fab0, #8fd3f4); }
    .rectangle.group-activities { background: linear-gradient(145deg, #f6d365, #fda085); }
    .rectangle.behavior-charts { background: linear-gradient(145deg, #cfd9df, #e2ebf0); }
    .rectangle.self-reflection { background: linear-gradient(145deg, #fbc2eb, #a6c1ee); }
    .rectangle.peer-feedback { background: linear-gradient(145deg, #d4fc79, #96e6a1); }
    .rectangle.classroom-observation { background: linear-gradient(145deg, #f093fb, #f5576c); }

    /* Dragging Styles */
    .rectangle.dragging {
      cursor: grabbing;
      box-shadow: 0 15px 25px rgba(0, 0, 0, 0.3);
      transform: scale(1.1);
      z-index: 1000;
    }

    .dragging-ghost {
      position: absolute;
      pointer-events: none;
      background-color: rgba(23, 162, 184, 0.8);
      color: #ffffff;
      font-size: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 140px; /* Match rectangle width */
      height: 140px; /* Match rectangle height */
      border-radius: 12px;
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
      transform: scale(1.1);
      z-index: 1000;
    }

    /* Remove Button Styles */
    .remove-button {
      position: absolute;
      top: 6px;
      right: 6px;
      background: rgba(0, 0, 0, 0.6);
      color: #ffffff;
      border: none;
      border-radius: 50%;
      width: 22px;
      height: 22px;
      font-size: 16px;
      line-height: 18px;
      text-align: center;
      cursor: pointer;
      opacity: 0.9;
      transition: opacity 0.2s ease, background-color 0.2s ease;
    }

    .remove-button:hover {
      opacity: 1;
      background-color: rgba(0, 0, 0, 0.8);
    }

    /* Hide remove buttons when deletion is disabled */
    .delete-disabled .remove-button {
      display: none;
    }

    /* Tooltip Styles */
    /* Removed tooltip from entire rectangle to comply with user request */

    /* Tooltips for specific elements */
    .remove-button .tooltip,
    .checkmark .tooltip {
      position: absolute;
      bottom: 125%;
      left: 50%;
      transform: translateX(-50%);
      background-color: #343a40;
      color: #ffffff;
      padding: 5px 8px;
      border-radius: 4px;
      font-size: 12px;
      white-space: nowrap;
      opacity: 0;
      pointer-events: none; /* Allows mouse events to pass through */
      transition: opacity 0.3s ease;
      z-index: 10;
    }

    .remove-button:hover .tooltip,
    .checkmark:hover .tooltip {
      opacity: 1;
    }

    /* Toast Notification */
    .toast {
      visibility: hidden;
      min-width: 250px;
      background-color: #333;
      color: #fff;
      text-align: center;
      border-radius: 4px;
      padding: 16px;
      position: fixed;
      z-index: 1000;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);
      opacity: 0;
      transition: opacity 0.5s, bottom 0.5s;
    }

    .toast.show {
      visibility: visible;
      opacity: 1;
      bottom: 50px;
    }

    /* Popup Styles */
    .popup-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 2000;
    }

    .popup {
      background: #ffffff;
      padding: 0;
      border-radius: 12px; /* More rounded corners */
      width: 90%;
      max-width: 700px; /* Increased max-width for better space */
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
      animation: fadeIn 0.3s ease;
      display: flex;
      flex-direction: column;
      max-height: 80vh; /* Changed from fixed height */
      height: auto; /* Allow height to adjust based on content */
      overflow: hidden; /* Hide overflow to manage internal scrolling */
      transition: max-height 0.3s ease, height 0.3s ease; /* Smooth transitions */
    }

    .popup-header {
      padding: 20px;
      background-color: #343a40;
      color: #ffffff;
      position: sticky;
      top: 0;
      z-index: 2;
      border-top-left-radius: 12px;
      border-top-right-radius: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .popup-header h3 {
      margin: 0;
      font-size: 24px;
      text-align: center;
      flex-grow: 1;
    }

    /* Close Button in Popup */
    .popup-header .close-popup-btn {
      background: transparent;
      border: none;
      color: #ffffff;
      font-size: 24px;
      cursor: pointer;
      line-height: 1;
      padding: 0;
      margin-left: 10px;
      transition: color 0.3s ease;
    }

    .popup-header .close-popup-btn:hover {
      color: #adb5bd;
    }

    .popup-content {
      padding: 20px;
      overflow-y: auto; /* Enable vertical scrolling */
      flex-grow: 1;
      max-height: calc(80vh - 160px); /* Adjust based on popup's max-height minus header and footer */
    }

    .popup-footer {
      padding: 10px 20px;
      background-color: #f8f9fa;
      border-bottom-left-radius: 12px;
      border-bottom-right-radius: 12px;
      position: sticky;
      bottom: 0;
      z-index: 2;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      border-top: 1px solid #dee2e6;
    }

    /* Buttons in Popup */
    .buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }

    .buttons .save-btn {
      background-color: #28a745;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .buttons .save-btn:hover {
      background-color: #218838;
    }

    .buttons .cancel-btn {
      background-color: #dc3545;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .buttons .cancel-btn:hover {
      background-color: #c82333;
    }

    /* View Popup Styles */
    .view-popup-overlay {
      position: fixed; /* Changed to fixed for consistency */
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 2500;
    }

    .view-popup {
      background: #ffffff;
      padding: 0;
      border-radius: 12px;
      width: 90%;
      max-width: 500px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
      animation: fadeIn 0.3s ease;
      display: flex;
      flex-direction: column;
      max-height: 80vh; /* Changed from fixed height */
      height: auto; /* Allow height to adjust based on content */
      overflow: hidden; /* Hide overflow to manage internal scrolling */
      transition: max-height 0.3s ease, height 0.3s ease; /* Smooth transitions */
    }

    .view-popup-header {
      padding: 20px;
      background-color: #343a40;
      color: #ffffff;
      position: sticky;
      top: 0;
      z-index: 2;
      border-top-left-radius: 12px;
      border-top-right-radius: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .view-popup-header h3 {
      margin: 0;
      font-size: 24px;
      text-align: center;
      flex-grow: 1;
    }

    /* Close Button in View Popup */
    .view-popup-header .close-view-popup-btn {
      background: transparent;
      border: none;
      color: #ffffff;
      font-size: 24px;
      cursor: pointer;
      line-height: 1;
      padding: 0;
      margin-left: 10px;
      transition: color 0.3s ease;
    }

    .view-popup-header .close-view-popup-btn:hover {
      color: #adb5bd;
    }

    .view-popup-content {
      padding: 20px;
      overflow-y: auto; /* Enable vertical scrolling */
      flex-grow: 1;
      max-height: calc(80vh - 160px); /* Adjust based on popup's max-height minus header and footer */
    }

    .view-popup-footer {
      padding: 10px 20px;
      background-color: #f8f9fa;
      border-bottom-left-radius: 12px;
      border-bottom-right-radius: 12px;
      position: sticky;
      bottom: 0;
      z-index: 2;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      border-top: 1px solid #dee2e6;
    }

    .view-popup .close-btn {
      background-color: #6c757d;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .view-popup .close-btn:hover {
      background-color: #5a6268;
    }
    /* ==================== End of New View Popup Styles ==================== */

    /* Responsive Design */
    @media (max-width: 1600px) {
      .journey-step {
        width: 160px;
        height: 200px;
      }

      .drop-zone {
        width: 130px;
        height: 130px;
      }

      .rectangle, .dragging-ghost, .placeholder {
        width: 130px; /* Increased width */
        height: 130px; /* Increased height */
      }

      .rectangle-name {
        font-size: 13px;
        margin-bottom: 8px;
      }

      .tool-menu {
        max-width: 600px;
      }

      /* Adjust Remove Button Size */
      .remove-button {
        width: 20px;
        height: 20px;
      }

      /* Adjust Dividing Line */
      .journey-step.last-in-row::before {
        height: 35px;
      }

      /* New Styles for Full-Width Title Input with Padding */
      .popup input#popup-title {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ced4da;
        border-radius: 6px;
        font-size: 16px;
        outline: none;
        transition: box-shadow 0.3s ease, border-color 0.3s ease;
      }

      .popup input#popup-title:focus {
        border-color: #17a2b8;
        box-shadow: 0 0 5px rgba(23, 162, 184, 0.5);
      }

      /* Optional: Adjust the label to align with the input field */
      .popup label[for="popup-title"] {
        margin-bottom: 5px;
        display: block;
      }

      /* Add 5px margin-bottom to title container for spacing */
      .popup-content > div:first-child {
        margin-bottom: 15px; /* Increased spacing between title and notering */
      }

      /* Add 5px margin-top to notering-section */
      .notering-section {
        margin-top: 5px; /* Added 5px distance */
      }

      /* Set default height of the note-field to 200px */
      .note-field {
        height: 200px; /* Set default height to 200px */
        min-height: 200px; /* Ensure it doesn't shrink below 200px */
        overflow: auto; /* Allow scrolling if content exceeds */
      }
    }

    @media (max-width: 1400px) {
      .journey-path {
        max-width: 1400px;
      }
    }

    @media (max-width: 1200px) {
      .journey-path {
        max-width: 1000px;
      }
    }

    @media (max-width: 768px) {
      body {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        flex-direction: row;
        overflow-x: auto;
        padding: 15px 10px;
      }

      .sidebar.collapsed {
        width: 100%;
      }

      .sidebar h2 {
        display: none;
      }

      .search-bar {
        width: 80%;
      }

      .category {
        flex-direction: column;
        align-items: flex-start;
        position: relative;
      }

      .subcategory-list {
        position: absolute;
        top: 100%;
        left: 0;
        background-color: #495057;
        width: 100%;
        border-radius: 0 0 6px 6px;
        z-index: 100;
      }

      .journey-path {
        flex-direction: row; /* Maintain row direction with wrapping */
        align-items: center;
        min-width: 100%;
        padding: 15px 0;
        gap: 30px; /* Adjust gap for smaller screens */
      }

      .journey-line {
        top: 50%;
        left: 0;
        right: 0;
        height: 4px;
      }

      .journey-step {
        width: 140px;
        height: 180px;
      }

      .journey-step::after {
        width: 4px;
        height: 40px;
        top: 50%;
        left: 100%;
        transform: translateY(-50%);
      }

      .drop-zone {
        width: 100px;
        height: 100px;
      }

      .rectangle, .dragging-ghost, .placeholder {
        width: 100px;
        height: 100px;
      }

      .rectangle {
        font-size: 12px; /* Further reduce font size for small rectangles */
      }

      .rectangle-name,
      .rectangle-title {
        font-size: 11px;
      }

      .tool-menu {
        max-width: 300px;
      }

      .switch {
        width: 40px;
        height: 20px;
      }

      .slider:before {
        height: 16px;
        width: 16px;
        left: 2px;
        bottom: 2px;
      }

      input:checked + .slider:before {
        transform: translateX(20px);
      }

      /* Adjust Remove Button Size */
      .remove-button {
        width: 18px;
        height: 18px;
        font-size: 14px;
      }

      /* Adjust Dividing Line */
      .journey-step.last-in-row::before {
        height: 30px;
      }

      /* Toolbar Adjustments for Small Screens */
      .toolbar-container {
        gap: 4px; /* Reduce gap between label and toolbar */
      }

      #toolbar {
        /* Adjust toolbar layout if necessary */
      }

      /* Ensure the note field adjusts height on smaller screens */
      .note-field {
        height: 200px; /* Consistent height across devices */
      }

      /* Add 5px margin-bottom to title container for spacing */
      .popup-content > div:first-child {
        margin-bottom: 15px; /* Increased spacing between title and notering */
      }

      /* Add 5px margin-top to notering-section */
      .notering-section {
        margin-top: 5px; /* Added 5px distance */
      }

      /* Set default height of the note-field to 200px */
      .note-field {
        height: 200px; /* Set default height to 200px */
        min-height: 200px; /* Ensure it doesn't shrink below 200px */
        overflow: auto; /* Allow scrolling if content exceeds */
      }
    }

    /* Responsive Toolbar */
    @media (max-width: 768px) {
      #toolbar {
        flex-wrap: wrap;
      }
    }

    /* Hover Popup Styles */
    .hover-popup {
      position: absolute;
      background-color: #ffffff;
      border: 1px solid #ced4da;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      z-index: 3000;
      width: 250px;
      opacity: 0;
      visibility: hidden;
      pointer-events: none; /* Allows mouse events to pass through */
      transition: opacity 0.3s ease, visibility 0.3s ease;
    }

    .hover-popup.visible {
      opacity: 1;
      visibility: visible;
    }

    .hover-popup h4 {
      margin-top: 0;
      font-size: 18px;
      color: #343a40;
    }

    .hover-popup p {
      margin: 5px 0;
      font-size: 14px;
      color: #495057;
    }

    .hover-popup label {
      font-weight: bold;
      display: block;
      margin-top: 10px;
      font-size: 14px;
      color: #343a40;
    }

    .hover-popup .popup-field {
      margin-bottom: 10px;
      font-size: 14px;
      color: #495057;
      word-wrap: break-word;
    }

    /* ==================== New View Popup Styles ==================== */
    /* View Popup Styles */
    .view-popup-overlay {
      position: fixed; /* Changed to fixed for consistency */
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 2500;
    }

    .view-popup {
      background: #ffffff;
      padding: 0;
      border-radius: 12px;
      width: 90%;
      max-width: 500px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
      animation: fadeIn 0.3s ease;
      display: flex;
      flex-direction: column;
      max-height: 80vh; /* Changed from fixed height */
      height: auto; /* Allow height to adjust based on content */
      overflow: hidden; /* Hide overflow to manage internal scrolling */
      transition: max-height 0.3s ease, height 0.3s ease; /* Smooth transitions */
    }

    .view-popup-header {
      padding: 20px;
      background-color: #343a40;
      color: #ffffff;
      position: sticky;
      top: 0;
      z-index: 2;
      border-top-left-radius: 12px;
      border-top-right-radius: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .view-popup-header h3 {
      margin: 0;
      font-size: 24px;
      text-align: center;
      flex-grow: 1;
    }

    /* Close Button in View Popup */
    .view-popup-header .close-view-popup-btn {
      background: transparent;
      border: none;
      color: #ffffff;
      font-size: 24px;
      cursor: pointer;
      line-height: 1;
      padding: 0;
      margin-left: 10px;
      transition: color 0.3s ease;
    }

    .view-popup-header .close-view-popup-btn:hover {
      color: #adb5bd;
    }

    .view-popup-content {
      padding: 20px;
      overflow-y: auto; /* Enable vertical scrolling */
      flex-grow: 1;
      max-height: calc(80vh - 160px); /* Adjust based on popup's max-height minus header and footer */
    }

    .view-popup-footer {
      padding: 10px 20px;
      background-color: #f8f9fa;
      border-bottom-left-radius: 12px;
      border-bottom-right-radius: 12px;
      position: sticky;
      bottom: 0;
      z-index: 2;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      border-top: 1px solid #dee2e6;
    }

    .view-popup .close-btn {
      background-color: #6c757d;
      color: #ffffff;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    .view-popup .close-btn:hover {
      background-color: #5a6268;
    }
    /* ==================== End of New View Popup Styles ==================== */

    /* Responsive Design */
    /* [Media queries as previously defined] */

  </style>
</head>
<body>

  <!-- Sidebar Menu -->
  <div class="sidebar">
    <h2>Strategimeny</h2>

    <!-- Search Bar -->
    <div class="search-bar">
      <input type="text" id="search-input" placeholder="Sök strategier..." aria-label="Sök strategier">
      <button id="clear-search" class="clear-search" aria-label="Rensa sökning">&times;</button>
    </div>

    <!-- Categories and Subcategories -->
    <?php
    // Define categories and subcategories
    $categories = [
        'Instruktionsstrategier' => [
            'differentiated-instruction' => 'Differentierad Undervisning',
            'collaborative-learning' => 'Samarbetsinlärning',
            'learning-games' => 'Lärande Genom Spel',
            'student-reflections' => 'Elevers Reflektioner',
            'multimedia-instruction' => 'Multimedia Undervisning',
            'problem-based-learning' => 'Problem-baserat Lärande',
            'flipped-classroom' => 'Flipped Classroom',
            'scaffolding' => 'Stödjande Undervisning'
        ],
        'Klassrumsledning' => [
            'positive-reinforcement' => 'Positiv Förstärkning',
            'behavior-modeling' => 'Beteendemodellering',
            'behavior-charts' => 'Beteendediagram',
            'specific-adjustments' => 'Specifika Anpassningar',
            'classroom-routines' => 'Klassrumsrutiner',
            'conflict-resolution' => 'Konflikthantering',
            'time-management' => 'Tidshantering',
            'student-engagement' => 'Elevernas Engagemang'
        ],
        'Elevstöd' => [
            'individual-tutoring' => 'Individuell Vägledning',
            'mentoring-programs' => 'Mentorprogram',
            'individual-conversations' => 'Enskilda Samtal',
            'group-activities' => 'Gruppaktiviteter',
            'academic-support' => 'Akademiskt Stöd',
            'social-skills-training' => 'Sociala Färdigheter Träning',
            'emotional-support' => 'Emotionellt Stöd',
            'peer-mentoring' => 'Kollegial Mentorskap'
        ],
        'Observationer' => [
            'classroom-observation' => 'Klassrumsobservation',
            'peer-observation' => 'Kollegial Observation',
            'self-observation' => 'Självobservation',
            'behavioral-observation' => 'Beteendeobservation',
            'learning-environment-observation' => 'Lärmiljöobservation',
            'instructional-observation' => 'Instruktionsobservation',
            'peer-feedback-observation' => 'Kollegial Feedback Observation',
            'student-participation-observation' => 'Elevers Deltagande Observation'
        ],
        'Feedback & Utvärdering' => [
            'feedback-sessions' => 'Feedbacksessioner',
            'peer-feedback' => 'Kollegial Feedback',
            'student-evaluations' => 'Elevers Utvärderingar',
            'self-reflection' => 'Självreflektion',
            'formative-assessments' => 'Formativa Bedömningar',
            'summative-assessments' => 'Summativa Bedömningar',
            'peer-assessments' => 'Kollegiala Bedömningar',
            'performance-assessments' => 'Prestation Bedömningar'
        ],
        'Specifika Insatser' => [
            'individual-tutoring' => 'Individuell Vägledning',
            'behavior-modeling' => 'Beteendemodellering',
            'positive-reinforcement' => 'Positiv Förstärkning',
            'specific-adjustments' => 'Specifika Anpassningar',
            'assistive-technology' => 'Assistiv Teknik',
            'alternative-assessments' => 'Alternativa Bedömningar',
            'curriculum-modification' => 'Läroplansmodifiering',
            'instructional-aides' => 'Instruktionshjälpmedel'
        ]
    ];

    // Function to generate categories and subcategories
    function renderCategories($categories) {
        foreach ($categories as $categoryName => $subcategories) {
            echo '<div class="category" tabindex="0" aria-expanded="false" role="button">';
            echo '<span>' . htmlspecialchars($categoryName, ENT_QUOTES, 'UTF-8') . '</span>';
            echo '<span class="arrow">&#9654;</span>';
            echo '</div>';
            echo '<div class="subcategory-list">';
            foreach ($subcategories as $type => $name) {
                echo '<div class="subcategory" data-type="' . htmlspecialchars($type, ENT_QUOTES, 'UTF-8') . '" tabindex="0">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</div>';
            }
            echo '</div>';
        }
    }

    renderCategories($categories);
    ?>

    <!-- Add more categories and subcategories as needed -->
  </div>

  <!-- Main Content with Journey Path and Tool Menu -->
  <div class="main-content delete-disabled drag-disabled"> <!-- Added delete-disabled and drag-disabled by default -->
    <div class="journey-path" id="journey-container">
      <div class="journey-line"></div>
      <!-- Journey steps will be added dynamically here -->
    </div>

    <!-- Tool Menu -->
    <div class="tool-menu">
      <!-- Dragging Toggle -->
      <label for="drag-toggle">Aktivera Dragning:</label>
      <label class="switch">
        <input type="checkbox" id="drag-toggle" aria-label="Toggle Dragging">
        <span class="slider"></span>
      </label>

      <!-- Deletion Toggle -->
      <label for="delete-toggle">Aktivera Ta bort:</label>
      <label class="switch">
        <input type="checkbox" id="delete-toggle" aria-label="Toggle Deletion">
        <span class="slider"></span>
      </label>
    </div>
  </div>

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

  <!-- Popup for Rich Text Editing -->
  <div class="popup-overlay" id="popup-overlay">
    <div class="popup">
      <div class="popup-header">
        <h3 id="popup-header">Redigera Strategi</h3>
        <button class="close-popup-btn" aria-label="Stäng Popup">&times;</button>
      </div>
      <div class="popup-content">
        <!-- Title Input -->
        <div>
          <label for="popup-title">Titel:</label>
          <input type="text" id="popup-title" placeholder="Ange titel..." aria-label="Strategi Titel">
        </div>

        <!-- Notering Label and Toolbar Container -->
        <!-- Notering Section: Toolbar and Note Field Wrapped Together -->
        <div class="notering-section">
          <div class="toolbar-container">
            <label for="popup-note">Notering:</label>

            <!-- Quill Toolbar -->
            <div id="toolbar">

              <select class="ql-header" aria-label="Header">
                <option value="1">Heading</option>
                <option value="2">Subheading</option>
                <option selected>Normal</option>
              </select>
              <button class="ql-bold" aria-label="Bold"></button>
              <button class="ql-italic" aria-label="Italic"></button>
              <button class="ql-underline" aria-label="Underline"></button>
              <button class="ql-strike" aria-label="Strikethrough"></button>
              <button class="ql-blockquote" aria-label="Blockquote"></button>
              <button class="ql-list" value="ordered" aria-label="Numbered List"></button>
              <button class="ql-list" value="bullet" aria-label="Bullet List"></button>
              <button class="ql-link" aria-label="Insert Link"></button>
              <button class="ql-image" aria-label="Insert Image"></button>
              <!-- Add more toolbar options as needed -->
            </div>
          </div>

          <!-- Note Field -->
          <div id="popup-note" class="note-field" aria-label="Strategi Notering"></div>
        </div>
      </div>
      <div class="popup-footer">
        <button class="save-btn" id="save-btn">Spara</button>
        <button class="cancel-btn" id="cancel-btn">Avbryt</button>
      </div>
    </div>
  </div>

  <!-- New View Popup for Checked Rectangles -->
  <div class="view-popup-overlay" id="view-popup-overlay">
    <div class="view-popup">
      <div class="view-popup-header">
        <h3 id="view-popup-header">Strategi Detaljer</h3>
        <button class="close-view-popup-btn" aria-label="Stäng Popup">&times;</button>
      </div>
      <div class="view-popup-content">
        <!-- Label (Name) Display -->
        <div>
          <label for="view-name">Namn:</label>
          <div id="view-name" class="view-field"></div>
        </div>

        <!-- Text (Title) Display -->
        <div>
          <label for="view-title">Titel:</label>
          <div id="view-title" class="view-field"></div>
        </div>

        <!-- Note (Notering) Display -->
        <div>
          <label for="view-note">Notering:</label>
          <div id="view-note" class="view-field"></div>
        </div>
      </div>
      <div class="view-popup-footer">
        <button class="close-btn" id="view-close-btn">Stäng</button>
      </div>
    </div>
  </div>
  <!-- ==================== End of New View Popup ==================== -->

  <!-- Hover Popup for Checked Sections -->
  <div class="hover-popup" id="hover-popup">
    <h4 id="hover-title">Titel Här</h4>
    <label for="hover-note">Notering:</label>
    <div class="popup-field" id="hover-note"></div>
  </div>

  <!-- Quill JS -->
  <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

  <script>
    (function() {
      const journeyContainer = document.getElementById('journey-container');
      const toast = document.getElementById('toast');
      const searchInput = document.getElementById('search-input');
      const clearSearchBtn = document.getElementById('clear-search');
      const journeyPath = document.querySelector('.journey-path');

      const popupOverlay = document.getElementById('popup-overlay');
      const popupHeader = document.getElementById('popup-header'); // Updated
      const popupTitle = document.getElementById('popup-title');
      const saveBtn = document.getElementById('save-btn');
      const cancelBtn = document.getElementById('cancel-btn');
      const closePopupBtn = document.querySelector('.close-popup-btn');

      const viewPopupOverlay = document.getElementById('view-popup-overlay');
      const viewPopupHeader = document.getElementById('view-popup-header'); // Updated
      const viewName = document.getElementById('view-name');
      const viewTitle = document.getElementById('view-title');
      const viewNote = document.getElementById('view-note'); // Added for notes
      const viewCloseBtn = document.getElementById('view-close-btn');
      const closeViewPopupBtn = document.querySelector('.close-view-popup-btn');

      const hoverPopup = document.getElementById('hover-popup');
      const hoverTitle = document.getElementById('hover-title');
      const hoverNote = document.getElementById('hover-note');

      let quill; // Quill editor instance
      let draggedElement = null;
      let ghostElement = null;
      let isTouch = false;
      let isDraggingEnabled = false; // Disabled by default
      let isDeleteEnabled = false;   // Disabled by default

      let currentEditingRect = null; // The rectangle being edited
      let savedData = {}; // Object to store saved data (title, note, and checked) for each rectangle

      // Initialize Quill editor when the popup is opened
      function initializeQuill() {
        quill = new Quill('#popup-note', {
          theme: 'snow',
          modules: {
            toolbar: '#toolbar'
          },
          placeholder: 'Skriv din text här...',
          scrollingContainer: '#popup-note'
        });

        // Listen to text-change events to adjust height
        quill.on('text-change', function() {
          autoResizeQuill();
        });

        // Initial resize
        autoResizeQuill();
      }

      // Function to auto-resize Quill editor
      function autoResizeQuill() {
        const editor = document.querySelector('#popup-note .ql-editor');
        const container = document.getElementById('popup-note');

        // Reset height to auto to calculate the new height
        container.style.height = 'auto';

        // Set the height based on the content, but ensure it doesn't exceed 200px
        const desiredHeight = Math.min(editor.scrollHeight, 200);
        container.style.height = `${desiredHeight}px`;
      }

      // Function to show toast notifications
      function showToast(message) {
        toast.textContent = message;
        toast.classList.add('show');
        setTimeout(() => { toast.classList.remove('show'); }, 3000);
      }

      // Utility function to create elements with classes and attributes
      function createElement(tag, classNames = [], attributes = {}) {
        const el = document.createElement(tag);
        classNames.forEach(cls => el.classList.add(cls));
        for (const attr in attributes) {
          el.setAttribute(attr, attributes[attr]);
        }
        return el;
      }

      // Function to find the first empty drop zone
      function findFirstEmptyDropZone() {
        return document.querySelector('.drop-zone:not(:has(.rectangle))');
      }

      // Function to add a new journey step with a drop zone
      function addJourneyStep() {
        const newStepIndex = document.querySelectorAll('.drop-zone').length;

        const journeyStep = createElement('div', ['journey-step']);

        const dropZone = createElement('div', ['drop-zone'], {
          'data-index': newStepIndex,
          'aria-label': 'Drop zone för strategi',
          'tabindex': '0'
        });

        journeyStep.appendChild(dropZone);
        journeyContainer.appendChild(journeyStep);

        // Update connectors after adding a new step
        updateConnectors();
        // Save state
        saveState();
      }

      // Function to create a rectangle with a remove button, name, title, and tooltip
      function createRectangle(type, name, title = '', checked = false) {
        const rect = createElement('div', ['rectangle', type], {
          'draggable': 'true',
          'tabindex': '0',
          'role': 'button',
          'aria-label': `Strategi: ${name}`
        });
        rect.dataset.id = 'rect-' + Math.random().toString(36).substr(2, 9);

        if (checked) {
          rect.classList.add('dimmed', 'checked');
        }

        // Initialize savedData for this rectangle
        if (!savedData[rect.dataset.id]) {
          savedData[rect.dataset.id] = {
            title: title,
            note: '',
            checked: checked
          };
        }

        // Remove Button
        const removeButton = createElement('button', ['remove-button'], {
          'aria-label': 'Ta bort strategi'
        });
        removeButton.innerHTML = '&times;';
        const removeTooltip = createElement('div', ['tooltip']);
        removeTooltip.textContent = 'Ta bort';
        removeButton.appendChild(removeTooltip);
        rect.appendChild(removeButton);

        // Name Div
        const nameDiv = createElement('div', ['rectangle-name']);
        nameDiv.textContent = name;
        rect.appendChild(nameDiv);

        // Title Div
        const titleDiv = createElement('div', ['rectangle-title']);
        titleDiv.innerHTML = title;
        rect.appendChild(titleDiv);

        // Checkmark
        const checkmark = createElement('div', ['checkmark'], {
          'aria-label': 'Markera strategi som klar',
          'tabindex': '0'
        });
        const checkmarkTooltip = createElement('div', ['tooltip']);
        checkmarkTooltip.textContent = 'Markera som klar';
        checkmark.appendChild(checkmarkTooltip);
        rect.appendChild(checkmark);

        // Event Listener for Checkmark Click
        checkmark.addEventListener('click', (e) => {
          e.stopPropagation();
          toggleCheckmark(rect);
        });

        // Keyboard Accessibility for Checkmark
        checkmark.addEventListener('keypress', (e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            toggleCheckmark(rect);
          }
        });

        return rect;
      }

      // Handle Subcategory Click using Event Delegation
      document.querySelector('.sidebar').addEventListener('click', (e) => {
        const subcategory = e.target.closest('.subcategory');
        if (subcategory) {
          const type = subcategory.getAttribute('data-type');
          const contentMap = {
            // Define your content mappings here
            'differentiated-instruction': 'Differentierad Undervisning',
            'collaborative-learning': 'Samarbetsinlärning',
            'learning-games': 'Lärande Genom Spel',
            'student-reflections': 'Elevers Reflektioner',
            'multimedia-instruction': 'Multimedia Undervisning',
            'problem-based-learning': 'Problem-baserat Lärande',
            'flipped-classroom': 'Flipped Classroom',
            'scaffolding': 'Stödjande Undervisning',
            'positive-reinforcement': 'Positiv Förstärkning',
            'behavior-modeling': 'Beteendemodellering',
            'behavior-charts': 'Beteendediagram',
            'specific-adjustments': 'Specifika Anpassningar',
            'classroom-routines': 'Klassrumsrutiner',
            'conflict-resolution': 'Konflikthantering',
            'time-management': 'Tidshantering',
            'student-engagement': 'Elevernas Engagemang',
            'individual-tutoring': 'Individuell Vägledning',
            'mentoring-programs': 'Mentorprogram',
            'individual-conversations': 'Enskilda Samtal',
            'group-activities': 'Gruppaktiviteter',
            'academic-support': 'Akademiskt Stöd',
            'social-skills-training': 'Sociala Färdigheter Träning',
            'emotional-support': 'Emotionellt Stöd',
            'peer-mentoring': 'Kollegial Mentorskap',
            'classroom-observation': 'Klassrumsobservation',
            'peer-observation': 'Kollegial Observation',
            'self-observation': 'Självobservation',
            'behavioral-observation': 'Beteendeobservation',
            'learning-environment-observation': 'Lärmiljöobservation',
            'instructional-observation': 'Instruktionsobservation',
            'peer-feedback-observation': 'Kollegial Feedback Observation',
            'student-participation-observation': 'Elevers Deltagande Observation',
            'feedback-sessions': 'Feedbacksessioner',
            'peer-feedback': 'Kollegial Feedback',
            'student-evaluations': 'Elevers Utvärderingar',
            'self-reflection': 'Självreflektion',
            'formative-assessments': 'Formativa Bedömningar',
            'summative-assessments': 'Summativa Bedömningar',
            'peer-assessments': 'Kollegiala Bedömningar',
            'performance-assessments': 'Prestation Bedömningar',
            'assistive-technology': 'Assistiv Teknik',
            'alternative-assessments': 'Alternativa Bedömningar',
            'curriculum-modification': 'Läroplansmodifiering',
            'instructional-aides': 'Instruktionshjälpmedel'
            // Add more mappings as needed
          };
          const name = contentMap[type] || 'Strategi';
          let firstEmpty = findFirstEmptyDropZone();
          if (!firstEmpty) {
            // If no empty drop zone, add a new journey step
            addJourneyStep();
            firstEmpty = findFirstEmptyDropZone();
          }
          if (firstEmpty) {
            const rect = createRectangle(type, name, '', false); // Initialize with empty title and unchecked
            firstEmpty.appendChild(rect);
            // After adding, update connectors
            updateConnectors();
            // Save state
            saveState();
          } else {
            showToast('Alla steg är fulla!');
          }
        }
      });

      // Enable keyboard accessibility for subcategories using Event Delegation
      document.querySelector('.sidebar').addEventListener('keypress', (e) => {
        if (e.target.classList.contains('subcategory') && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          e.target.click();
        }
      });

      // Function to remove a rectangle and its drop-zone, and possibly the journey-step
      function removeRectangle(rect) {
        const dropZone = rect.parentElement;
        const journeyStep = dropZone.parentElement;

        const rectId = rect.dataset.id;
        delete savedData[rectId]; // Remove saved data

        rect.remove(); // Remove the rectangle
        dropZone.remove(); // Remove the drop-zone

        // Check if the journeyStep has any other drop-zones (it shouldn't, but just in case)
        if (journeyStep.querySelectorAll('.drop-zone').length === 0) {
          journeyStep.remove(); // Remove the journey-step if no drop-zones left
        }

        // After removing, update connectors
        updateConnectors();
        // Save state
        saveState();
      }

      // Event delegation for remove buttons
      document.body.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-button')) {
          const rect = e.target.closest('.rectangle');
          if (isDeleteEnabled) { // Check if deletion is enabled
            // Confirmation before deletion
            if (confirm('Är du säker på att du vill ta bort denna strategi?')) {
              removeRectangle(rect);
            }
          }
        }
      });

      // Enable keyboard accessibility for remove buttons using Event Delegation
      document.body.addEventListener('keypress', function(e) {
        if (e.target.classList.contains('remove-button') && (e.key === 'Enter' || e.key === ' ')) {
          const rect = e.target.closest('.rectangle');
          if (isDeleteEnabled) { // Check if deletion is enabled
            if (confirm('Är du säker på att du vill ta bort denna strategi?')) {
              removeRectangle(rect);
            }
          }
        }
      });

      // Swap two elements in the journey path
      function swapElements(el1, el2) {
        const parent1 = el1.parentElement;
        const parent2 = el2.parentElement;

        // Swap in the DOM
        parent1.appendChild(el2);
        parent2.appendChild(el1);

        // After swapping, update connectors
        updateConnectors();
        // Save state
        saveState();
      }

      // Handle Drag Start (Mouse)
      function handleDragStart(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        const targetRect = e.target.closest('.rectangle');
        if (targetRect) {
          draggedElement = targetRect;
          draggedElement.classList.add('dragging');

          // Create a ghost element
          ghostElement = draggedElement.cloneNode(true);
          ghostElement.classList.add('dragging-ghost');
          document.body.appendChild(ghostElement);
          updateGhostPosition(e.pageX, e.pageY);

          // Hide the original element
          setTimeout(() => {
            draggedElement.style.opacity = '0';
          }, 0);

          e.dataTransfer.effectAllowed = 'move';
          e.dataTransfer.setData('text/plain', ''); // Required for Firefox
        }
      }

      // Handle Drag Over (Mouse)
      function handleDragOver(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';

        const dropZone = e.target.closest('.drop-zone');
        if (dropZone && dropZone !== draggedElement.parentElement) {
          document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
          dropZone.classList.add('over');
        }
      }

      // Handle Drop (Mouse)
      function handleDrop(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        e.preventDefault();
        const dropZone = e.target.closest('.drop-zone');
        if (dropZone && draggedElement) {
          const targetRect = dropZone.querySelector('.rectangle');
          if (targetRect && targetRect !== draggedElement) {
            swapElements(draggedElement, targetRect);
          } else if (!targetRect) {
            dropZone.appendChild(draggedElement);
            // After adding, update connectors
            updateConnectors();
            // Save state
            saveState();
          }
        }
        endDrag();
      }

      // Handle Drag End (Mouse)
      function handleDragEnd(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        endDrag();
        document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
      }

      // End Dragging
      function endDrag() {
        if (draggedElement) {
          draggedElement.classList.remove('dragging');
          draggedElement.style.opacity = '1';
          draggedElement = null;
        }
        if (ghostElement) {
          ghostElement.remove();
          ghostElement = null;
        }
      }

      // Update Ghost Position
      function updateGhostPosition(x, y) {
        if (ghostElement) {
          ghostElement.style.left = `${x - ghostElement.offsetWidth / 2}px`;
          ghostElement.style.top = `${y - ghostElement.offsetHeight / 2}px`;
        }
      }

      // Handle Mouse Move for Ghost
      function handleMouseMove(e) {
        if (ghostElement) {
          updateGhostPosition(e.pageX, e.pageY);
        }
      }

      // Handle Touch Start
      function handleTouchStart(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        const touch = e.touches[0];
        const targetRect = e.target.closest('.rectangle');
        if (targetRect) {
          isTouch = true;
          draggedElement = targetRect;
          draggedElement.classList.add('dragging');

          const rect = draggedElement.getBoundingClientRect();
          const offsetX = touch.clientX - rect.left;
          const offsetY = touch.clientY - rect.top;

          // Create a ghost element
          ghostElement = draggedElement.cloneNode(true);
          ghostElement.classList.add('dragging-ghost');
          ghostElement.style.left = `${touch.pageX - rect.width / 2}px`;
          ghostElement.style.top = `${touch.pageY - rect.height / 2}px`;
          document.body.appendChild(ghostElement);

          // Hide the original element
          draggedElement.style.opacity = '0';

          document.addEventListener('touchmove', handleTouchMove, { passive: false });
          document.addEventListener('touchend', handleTouchEnd);
        }
      }

      // Handle Touch Move
      function handleTouchMove(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        if (ghostElement && e.touches.length === 1) {
          e.preventDefault();
          const touch = e.touches[0];
          ghostElement.style.left = `${touch.pageX - ghostElement.offsetWidth / 2}px`;
          ghostElement.style.top = `${touch.pageY - ghostElement.offsetHeight / 2}px`;

          const elemBelow = document.elementFromPoint(touch.clientX, touch.clientY);
          const targetDropZone = elemBelow ? elemBelow.closest('.drop-zone') : null;

          document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
          if (targetDropZone && targetDropZone !== draggedElement.parentElement) {
            targetDropZone.classList.add('over');
          }
        }
      }

      // Handle Touch End
      function handleTouchEnd(e) {
        if (!isDraggingEnabled) return; // Do nothing if dragging is disabled

        const touch = e.changedTouches[0];
        const elemBelow = document.elementFromPoint(touch.clientX, touch.clientY);
        const targetDropZone = elemBelow ? elemBelow.closest('.drop-zone') : null;

        if (draggedElement && targetDropZone) {
          const targetRect = targetDropZone.querySelector('.rectangle');
          if (targetRect && targetRect !== draggedElement) {
            swapElements(draggedElement, targetRect);
          } else if (!targetRect) {
            targetDropZone.appendChild(draggedElement);
            // After adding, update connectors
            updateConnectors();
            // Save state
            saveState();
          }
        }

        endDrag();
        document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
        document.removeEventListener('touchmove', handleTouchMove);
        document.removeEventListener('touchend', handleTouchEnd);
      }

      // Function to update connectors based on row positions with alternating last-in-row
      function updateConnectors() {
        const journeySteps = Array.from(document.querySelectorAll('.journey-step'));

        // Reset all journey-steps by removing the 'last-in-row' class
        journeySteps.forEach(step => step.classList.remove('last-in-row'));

        if (journeySteps.length === 0) {
          // If no steps, ensure dividing lines are hidden
          journeyPath.classList.remove('single-row');
          return;
        }

        // Determine the row each step is in by its top position
        const rowMap = {};
        journeySteps.forEach(step => {
          const top = step.getBoundingClientRect().top;
          // Use a tolerance to group steps in the same row
          let rowFound = false;
          for (let row in rowMap) {
            if (Math.abs(rowMap[row].top - top) < 10) { // 10px tolerance
              rowMap[row].steps.push(step);
              rowFound = true;
              break;
            }
          }
          if (!rowFound) {
            // If no existing row matches, create a new row
            rowMap[Object.keys(rowMap).length] = { top: top, steps: [step] };
          }
        });

        const rows = Object.values(rowMap);

        // Check if there's only one row
        if (rows.length <= 1) {
          // Add 'single-row' class to hide dividing lines
          journeyPath.classList.add('single-row');
        } else {
          // Remove 'single-row' class if multiple rows exist
          journeyPath.classList.remove('single-row');

          // Iterate through each row and apply 'last-in-row' accordingly
          rows.forEach((row, index) => {
            // Only add 'last-in-row' if there's a row after the current one
            if (index < rows.length -1) {
              if (index % 2 === 0) { // Even index: first row, third row, etc.
                const lastStep = row.steps[row.steps.length - 1];
                if (lastStep) {
                  lastStep.classList.add('last-in-row');
                }
              } else { // Odd index: second row, fourth row, etc.
                const firstStep = row.steps[0];
                if (firstStep) {
                  firstStep.classList.add('last-in-row');
                }
              }
            }
          });
        }
      }

      // Handle Tool Menu Toggle for Dragging
      document.getElementById('drag-toggle').addEventListener('change', (e) => {
        isDraggingEnabled = e.target.checked;
        document.querySelector('.main-content').classList.toggle('drag-disabled', !isDraggingEnabled);
        if (!isDraggingEnabled) {
          // If dragging is disabled, ensure no ghost elements or dragging states remain
          endDrag();
        }
      });

      // Handle Tool Menu Toggle for Deletion
      document.getElementById('delete-toggle').addEventListener('change', (e) => {
        isDeleteEnabled = e.target.checked;
        document.querySelector('.main-content').classList.toggle('delete-disabled', !isDeleteEnabled);
      });

      // Handle Category Collapse/Expand with Keyboard Accessibility
      document.querySelector('.sidebar').addEventListener('click', (e) => {
        const category = e.target.closest('.category');
        if (category) {
          const isExpanded = category.classList.toggle('expanded');
          category.setAttribute('aria-expanded', isExpanded);
          // Toggle corresponding subcategory list
          const subcategoryList = category.nextElementSibling;
          if (subcategoryList) {
            subcategoryList.classList.toggle('expanded');
          }
        }
      });

      // Initialize with one journey step
      document.addEventListener('DOMContentLoaded', () => {
        addJourneyStep();
        updateConnectors();
        // Initialize Quill
        initializeQuill();
        // Load state from the server
        loadState();

        // Ensure delete and drag are disabled by default
        document.querySelector('.main-content').classList.add('delete-disabled', 'drag-disabled');

        // Initialize Search Functionality
        initializeSearch();
      });

      // Update connectors on window resize to handle dynamic layout changes
      window.addEventListener('resize', () => {
        updateConnectors();
      });

      // Add Event Listeners for Mouse
      journeyContainer.addEventListener('dragstart', handleDragStart);
      journeyContainer.addEventListener('dragover', handleDragOver);
      journeyContainer.addEventListener('drop', handleDrop);
      journeyContainer.addEventListener('dragend', handleDragEnd);
      document.addEventListener('mousemove', handleMouseMove);

      // Add Event Listeners for Touch
      journeyContainer.addEventListener('touchstart', handleTouchStart, { passive: false });

      // Prevent default dragover behavior to allow drop
      document.addEventListener('dragover', function(e) {
        e.preventDefault();
      }, false);

      document.addEventListener('drop', function(e) {
        e.preventDefault();
      }, false);

      // Persisting State with Server-Side PHP
      function saveState() {
        const journeySteps = Array.from(document.querySelectorAll('.journey-step')).map(step => {
          const dropZone = step.querySelector('.drop-zone');
          if (dropZone) {
            const rect = dropZone.querySelector('.rectangle');
            if (rect) {
              const type = [...rect.classList].find(cls => cls !== 'rectangle');
              const name = rect.querySelector('.rectangle-name').textContent;
              const title = rect.querySelector('.rectangle-title').innerHTML; // Use innerHTML to preserve formatting
              const rectId = rect.dataset.id;
              const note = savedData[rectId] ? savedData[rectId].note : '';
              const checked = savedData[rectId] ? savedData[rectId].checked : false;
              return { type, name, title, note: note || null, checked };
            }
          }
          return null;
        }).filter(step => step !== null);

        // Send the state to the server via AJAX
        fetch('', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            'action': 'saveState',
            'data': JSON.stringify(journeySteps),
            'csrf_token': '<?php echo $_SESSION['csrf_token']; ?>'
          })
        })
        .then(response => response.json())
        .then(data => {
          if (data.status !== 'success') {
            showToast('Kunde inte spara till servern.');
          }
        })
        .catch(() => {
          showToast('Ett fel uppstod vid spara till servern.');
        });
      }

      // Function to load the saved state
      function loadState() {
        // Request the state from the server via AJAX
        fetch('', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            'action': 'loadState',
            'csrf_token': '<?php echo $_SESSION['csrf_token']; ?>'
          })
        })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success' && data.data) {
            data.data.forEach(step => {
              let dropZone = findFirstEmptyDropZone();
              if (!dropZone) {
                addJourneyStep();
                dropZone = findFirstEmptyDropZone();
              }
              if (dropZone) {
                const rect = createRectangle(step.type, step.name, step.title, step.checked);
                dropZone.appendChild(rect);
                if (step.note) {
                  const rectId = rect.dataset.id;
                  savedData[rectId].note = step.note;
                  if (step.checked) {
                    rect.classList.add('dimmed', 'checked');
                  }
                }
              }
            });
            updateConnectors();
          }
        })
        .catch(() => {
          showToast('Ett fel uppstod vid laddning från servern.');
        });
      }

      // Function to toggle the checkmark state
      function toggleCheckmark(rect) {
        const rectId = rect.dataset.id;
        if (rect.classList.contains('checked')) {
          rect.classList.remove('checked', 'dimmed');
          if (savedData[rectId]) {
            savedData[rectId].checked = false;
          }
          showToast('Strategi markerad som oavslutad.');
        } else {
          rect.classList.add('checked', 'dimmed');
          if (!savedData[rectId]) {
            savedData[rectId] = { title: '', note: '', checked: true };
          }
          savedData[rectId].checked = true;
          showToast('Strategi markerad som avslutad.');
        }
        // Save the updated state to the server
        saveState();
      }

      // Function to open the popup
      function openPopup() {
        popupOverlay.style.display = 'flex';
        quill.focus();
      }

      // Function to close the popup
      function closePopup() {
        popupOverlay.style.display = 'none';
        currentEditingRect = null;
        popupTitle.value = '';
        quill.root.innerHTML = '';
        popupHeader.textContent = 'Redigera Strategi'; // Reset header
      }

      // Function to open the view popup as a modal showing both title and note
      function openViewPopup(rect) {
        const rectId = rect.dataset.id;
        const name = rect.querySelector('.rectangle-name').textContent;
        const title = savedData[rectId] ? savedData[rectId].title : '';
        const note = savedData[rectId] ? savedData[rectId].note : '';

        // Populate the view popup
        viewName.textContent = name;
        viewTitle.innerHTML = title || 'Ingen titel';
        viewNote.innerHTML = note || 'Ingen notering';

        // Set dynamic header text
        viewPopupHeader.textContent = `DETALJER FÖR ${name}`;

        // Show the view popup
        viewPopupOverlay.style.display = 'flex';
      }

      // Function to close the view popup
      function closeViewPopup() {
        viewPopupOverlay.style.opacity = '0';
        setTimeout(() => {
          viewPopupOverlay.style.display = 'none';
          viewPopupHeader.textContent = 'Strategi Detaljer'; // Reset header
        }, 300);
      }

      // Handle Save Button in Popup
      saveBtn.addEventListener('click', () => {
        const title = popupTitle.value.trim();
        const note = quill.root.innerHTML.trim(); // Get HTML content from Quill

        if (currentEditingRect) {
          const rectId = currentEditingRect.dataset.id;
          if (title !== '' || quill.getText().trim() !== '') {
            // Save the data
            if (!savedData[rectId]) {
              savedData[rectId] = { title: '', note: '', checked: false };
            }
            savedData[rectId].title = title;
            savedData[rectId].note = quill.root.innerHTML;

            // Update the title in the rectangle
            const titleDiv = currentEditingRect.querySelector('.rectangle-title');
            if (titleDiv) {
              titleDiv.innerHTML = title || 'Ingen titel'; // Use innerHTML to allow rich text in title if needed
            }

            showToast('Data sparad.');
          } else {
            // Remove the saved data if both fields are empty
            delete savedData[rectId];
            // Clear the title
            const titleDiv = currentEditingRect.querySelector('.rectangle-title');
            if (titleDiv) {
              titleDiv.innerHTML = '';
            }
            showToast('Data borttagen.');
          }
          // Save state to server
          saveState();
        }
        closePopup();
      });

      // Handle Cancel Button in Popup
      cancelBtn.addEventListener('click', () => {
        closePopup();
      });

      // Handle Close Button in Edit Popup
      closePopupBtn.addEventListener('click', () => {
        closePopup();
      });

      // Handle Close Button in View Popup
      viewCloseBtn.addEventListener('click', () => {
        closeViewPopup();
      });

      // Function to handle rectangle clicks
      function handleRectangleClick(rect) {
        if (rect.classList.contains('checked')) {
          // If rectangle is checked, open the view popup
          openViewPopup(rect);
        } else {
          // If unchecked, open the editable popup
          popupTitle.value = savedData[rect.dataset.id] ? savedData[rect.dataset.id].title : '';
          quill.root.innerHTML = savedData[rect.dataset.id] ? savedData[rect.dataset.id].note : '';
          currentEditingRect = rect;

          // Set dynamic header text
          const name = rect.querySelector('.rectangle-name').textContent;
          popupHeader.textContent = `EDIT ${name}`;

          openPopup();
        }
      }

      // Attach click event to rectangles using Event Delegation
      document.body.addEventListener('click', function(e) {
        const rect = e.target.closest('.rectangle');
        if (rect && !e.target.classList.contains('remove-button') && !e.target.classList.contains('checkmark')) {
          handleRectangleClick(rect);
        }
      });

      // Function to initialize search functionality
      function initializeSearch() {
        // Debounce function to limit the rate of function execution
        const debounce = (func, delay) => {
          let timeout;
          return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), delay);
          };
        };

        searchInput.addEventListener('input', debounce(function() {
          const query = this.value.trim().toLowerCase();

          // Show or hide the clear search button
          clearSearchBtn.classList.toggle('visible', query.length > 0);

          // Get all category elements
          const categories = document.querySelectorAll('.sidebar .category');

          categories.forEach(category => {
            const subcategoryList = category.nextElementSibling;
            const subcategories = subcategoryList.querySelectorAll('.subcategory');

            let categoryHasMatch = false;

            subcategories.forEach(subcategory => {
              const subcategoryText = subcategory.textContent.toLowerCase();
              if (subcategoryText.includes(query)) {
                subcategory.style.display = 'flex'; // Show matching subcategory
                subcategory.classList.add('highlight'); // Highlight match
                categoryHasMatch = true;
              } else {
                subcategory.style.display = 'none'; // Hide non-matching subcategory
                subcategory.classList.remove('highlight'); // Remove highlight
              }
            });

            if (query === '') {
              // If search field is empty, show all subcategories and collapse categories
              subcategories.forEach(subcategory => {
                subcategory.style.display = 'flex';
                subcategory.classList.remove('highlight');
              });
              category.classList.remove('expanded');
              subcategoryList.classList.remove('expanded');
              category.setAttribute('aria-expanded', 'false');
            } else {
              if (categoryHasMatch) {
                // Expand category if it has matching subcategories
                category.classList.add('expanded');
                subcategoryList.classList.add('expanded');
                category.setAttribute('aria-expanded', 'true');
              } else {
                // Collapse category if no matching subcategories
                category.classList.remove('expanded');
                subcategoryList.classList.remove('expanded');
                category.setAttribute('aria-expanded', 'false');
              }
            }
          });
        }, 300)); // Adjust the delay (in milliseconds) as needed

        // Handle Clear Search Button Click
        clearSearchBtn.addEventListener('click', () => {
          searchInput.value = '';
          clearSearchBtn.classList.remove('visible');
          searchInput.dispatchEvent(new Event('input')); // Trigger input event to reset the search
        });
      }

      // ==================== Hover Popup Functionality ====================

      // Function to show the hover popup
      function showHoverPopup(rect) {
        const rectId = rect.dataset.id;
        const title = savedData[rectId] ? savedData[rectId].title : '';
        const note = savedData[rectId] ? savedData[rectId].note : '';

        if (title || note) {
          // Populate the hover popup
          hoverTitle.textContent = title || 'Ingen titel';
          hoverNote.innerHTML = note || 'Ingen notering';

          // Temporarily make the popup visible to get its dimensions
          hoverPopup.style.display = 'block';
          hoverPopup.style.visibility = 'hidden';
          hoverPopup.style.opacity = '0';

          const rectBounds = rect.getBoundingClientRect();
          const popupWidth = hoverPopup.offsetWidth;
          const popupHeight = hoverPopup.offsetHeight;
          const viewportWidth = window.innerWidth;
          const viewportHeight = window.innerHeight;

          // Decide where to position the popup: right or below
          let top, left;

          // Prefer positioning to the right
          if (rectBounds.right + popupWidth + 10 < viewportWidth) { // 10px margin
            top = rectBounds.top + window.scrollY;
            left = rectBounds.right + window.scrollX + 10; // 10px to the right
          } else {
            // Otherwise, position below
            top = rectBounds.bottom + window.scrollY + 10; // 10px below
            left = rectBounds.left + window.scrollX;
            // Adjust if it overflows the viewport
            if (left + popupWidth + 10 > viewportWidth) {
              left = viewportWidth - popupWidth - 10;
            }
          }

          // Apply styles
          hoverPopup.style.top = `${top}px`;
          hoverPopup.style.left = `${left}px`;

          // Show the popup
          hoverPopup.classList.add('visible');
        }
      }

      // Function to hide the hover popup
      function hideHoverPopup() {
        hoverPopup.classList.remove('visible');
      }

      // Event delegation for handling hover on checked rectangles using 'mouseenter' and 'mouseleave'
      document.body.addEventListener('mouseenter', function(e) {
        const rect = e.target.closest('.rectangle');
        if (rect && rect.classList.contains('checked')) {
          showHoverPopup(rect);
        }
      }, true); // Use capture phase

      document.body.addEventListener('mouseleave', function(e) {
        const rect = e.target.closest('.rectangle');
        if (rect && rect.classList.contains('checked')) {
          hideHoverPopup();
        }
      }, true); // Use capture phase

      // Prevent the hover popup from interfering with mouse events
      hoverPopup.addEventListener('mouseenter', () => {
        hoverPopup.classList.add('visible');
      });

      hoverPopup.addEventListener('mouseleave', () => {
        hoverPopup.classList.remove('visible');
      });

      // ==================== End of Hover Popup Functionality ====================

      // ==================== Drag and Drop Functionality ====================

      // [All drag and drop functions as defined above]

      // ==================== End of Drag and Drop Functionality ====================

      // ==================== Persisting State with Server-Side PHP ====================

      // [Persisting state functions as provided above]

      // ==================== End of Persisting State with Server-Side PHP ====================

      // ==================== Rectangle Click Event ====================

      // [All rectangle click functions as defined above]

      // ==================== End of Rectangle Click Event ====================

    })();
  </script>

</body>
</html>