/*
Plugin Name: Teacher Strategy Journal
Description: A comprehensive tool for teachers to manage strategies and student IDs.
Version: 1.0
Author: Your Name
Text Domain: teacher-strategy-journal

*/

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}



// Add this function at the top, after the plugin header and before other hooks
// Add this function at the top, after the plugin header and before other hooks
function tsj_get_allowed_student_id_range() {
    $current_user = wp_get_current_user();
    $allowed_min_id = 1;
    $allowed_max_id = 300;

    if ($current_user->user_login === 'daer1001') {
        $allowed_min_id = 100;
        $allowed_max_id = 200;
    }

    return array('min' => $allowed_min_id, 'max' => $allowed_max_id);
}



// 1. Register Custom Post Type for Student IDs
// 1. Register Custom Post Type for Student IDs
function tsj_register_student_id_cpt() {
    $labels = array(
        'name'                  => _x( 'Student IDs', 'Post Type General Name', 'teacher-strategy-journal' ),
        'singular_name'         => _x( 'Student ID', 'Post Type Singular Name', 'teacher-strategy-journal' ),
        'menu_name'             => __( 'Student IDs', 'teacher-strategy-journal' ),
        'name_admin_bar'        => __( 'Student ID', 'teacher-strategy-journal' ),
        'archives'              => __( 'Student ID Archives', 'teacher-strategy-journal' ),
        'attributes'            => __( 'Student ID Attributes', 'teacher-strategy-journal' ),
        'parent_item_colon'     => __( 'Parent Student ID:', 'teacher-strategy-journal' ),
        'all_items'             => __( 'All Student IDs', 'teacher-strategy-journal' ),
        'add_new_item'          => __( 'Add New Student ID', 'teacher-strategy-journal' ),
        'add_new'               => __( 'Add New', 'teacher-strategy-journal' ),
        'new_item'              => __( 'New Student ID', 'teacher-strategy-journal' ),
        'edit_item'             => __( 'Edit Student ID', 'teacher-strategy-journal' ),
        'update_item'           => __( 'Update Student ID', 'teacher-strategy-journal' ),
        'view_item'             => __( 'View Student ID', 'teacher-strategy-journal' ),
        'view_items'            => __( 'View Student IDs', 'teacher-strategy-journal' ),
        'search_items'          => __( 'Search Student ID', 'teacher-strategy-journal' ),
        'not_found'             => __( 'Not found', 'teacher-strategy-journal' ),
        'not_found_in_trash'    => __( 'Not found in Trash', 'teacher-strategy-journal' ),
        'featured_image'        => __( 'Featured Image', 'teacher-strategy-journal' ),
        'set_featured_image'    => __( 'Set featured image', 'teacher-strategy-journal' ),
        'remove_featured_image' => __( 'Remove featured image', 'teacher-strategy-journal' ),
        'use_featured_image'    => __( 'Use as featured image', 'teacher-strategy-journal' ),
        'insert_into_item'      => __( 'Insert into student ID', 'teacher-strategy-journal' ),
        'uploaded_to_this_item' => __( 'Uploaded to this student ID', 'teacher-strategy-journal' ),
        'items_list'            => __( 'Student IDs list', 'teacher-strategy-journal' ),
        'items_list_navigation' => __( 'Student IDs list navigation', 'teacher-strategy-journal' ),
        'filter_items_list'     => __( 'Filter student IDs list', 'teacher-strategy-journal' ),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'has_archive'        => true,
        'show_in_menu'       => true,
        'supports'           => array( 'title', 'custom-fields' ),
        'capability_type'    => 'post',
    );

    register_post_type( 'student_id', $args );
}
add_action( 'init', 'tsj_register_student_id_cpt' );



// AJAX Handler to Remove Student ID
function tsj_remove_student_id_callback() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'tsj_students';

    // Check nonce for security
    check_ajax_referer('tsj_remove_student_id_nonce', 'csrf_token');

    // Get current user
    $current_user = wp_get_current_user();
    if ( ! $current_user->exists() ) {
        wp_send_json_error( array( 'message' => 'Användare är inte inloggad.' ) );
    }

    $user_id = $current_user->ID;

    // Get allowed range
    $range = tsj_get_allowed_student_id_range();
    $allowed_min_id = $range['min'];
    $allowed_max_id = $range['max'];

    // Get student ID from POST
    $student_id = isset( $_POST['student_id'] ) ? intval( $_POST['student_id'] ) : 0;

    // Validate student ID
    if ( $student_id < $allowed_min_id || $student_id > $allowed_max_id ) {
        wp_send_json_error( array( 'message' => "Student ID måste vara mellan {$allowed_min_id} och {$allowed_max_id}." ) );
    }

    // Check if student ID exists for the current user
    $existing = $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM $table_name WHERE student_id = %d AND user_id = %d",
        $student_id,
        $user_id
    ) );

    if ( $existing == 0 ) {
        wp_send_json_error( array( 'message' => 'Student ID hittades inte eller du har inte behörighet att ta bort det.' ) );
    }

    // Delete from custom table
    $result = $wpdb->delete(
        $table_name,
        array(
            'student_id' => $student_id,
            'user_id'    => $user_id
        ),
        array( '%d', '%d' )
    );

    if ( $result === false ) {
        wp_send_json_error( array( 'message' => 'Ett fel uppstod vid borttagning av student ID.' ) );
    }

    wp_send_json_success( array( 'message' => 'Student ID har tagits bort.' ) );
}


// Register AJAX actions for removing student IDs
add_action('wp_ajax_tsj_remove_student_id', 'tsj_remove_student_id_callback');
add_action('wp_ajax_nopriv_tsj_remove_student_id', 'tsj_remove_student_id_callback');


// 3. AJAX Handler to Add Student ID
// Update in tsj_add_student_id_callback function
function tsj_add_student_id_callback() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'tsj_students';

    // Check nonce for security
    check_ajax_referer('tsj_add_student_id_nonce', 'csrf_token');

    // Get current user
    $current_user = wp_get_current_user();
    if ( !$current_user->exists() ) {
        wp_send_json_error( array( 'message' => 'Användare är inte inloggad.' ) );
    }

    $user_id = $current_user->ID;

    // Get allowed range
    $range = tsj_get_allowed_student_id_range();
    $allowed_min_id = $range['min'];
    $allowed_max_id = $range['max'];

    
	 // Get student ID from POST
    $student_id = isset( $_POST['student_id'] ) ? intval( $_POST['student_id'] ) : 0;

	
    // Validate student ID
    if ( $student_id < $allowed_min_id || $student_id > $allowed_max_id ) {
        wp_send_json_error( array( 'message' => "Student ID måste vara mellan {$allowed_min_id} och {$allowed_max_id}." ) );
    }

    // Check for duplicates for the current user
    $existing = $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM $table_name WHERE student_id = %d AND user_id = %d",
        $student_id,
        $user_id
    ) );

    if ( $existing > 0 ) {
        wp_send_json_error( array( 'message' => 'Du har redan lagt till detta Student ID.' ) );
    }

    // Insert into custom table
    $result = $wpdb->insert(
        $table_name,
        array(
            'student_id' => $student_id,
            'user_id'    => $user_id,
        ),
        array(
            '%d',
            '%d',
        )
    );

    if ( $result === false ) {
        wp_send_json_error( array( 'message' => 'Ett fel uppstod vid skapandet av student ID.' ) );
    }

    wp_send_json_success( array( 'message' => 'Student ID har lagts till.' ) );
}

// Move the AJAX action hooks below the function definition
add_action('wp_ajax_tsj_add_student_id', 'tsj_add_student_id_callback');
add_action('wp_ajax_nopriv_tsj_add_student_id', 'tsj_add_student_id_callback');




// 4. AJAX Handler to Remove Student ID
add_shortcode('teacher_strategy_journal', 'tsj_teacher_strategy_journal_shortcode');


// Shortcode Handler
function tsj_teacher_strategy_journal_shortcode() {
    // Ensure Gravity Forms is installed and form ID 1 exists
    if(!class_exists('GFAPI')){
        return '<p>Gravity Forms plugin is not installed or activated.</p>';
    }

	// Get allowed range
    $range = tsj_get_allowed_student_id_range();
    $allowed_min_id = $range['min'];
    $allowed_max_id = $range['max'];
	
	
	// Get the current user
$current_user = wp_get_current_user();
$user_id = $current_user->ID;

// Fetch student IDs from custom table
global $wpdb;
$table_name = $wpdb->prefix . 'tsj_students';

$student_ids = $wpdb->get_col( $wpdb->prepare(
    "SELECT student_id FROM $table_name WHERE user_id = %d AND student_id BETWEEN %d AND %d ORDER BY student_id ASC",
    $user_id,
    $allowed_min_id,
    $allowed_max_id
) );

	
    // 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' => 'Klassrumsiner',
            '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'
        ]
    ];
	
	// Get the current user
$current_user = wp_get_current_user();

	  // Fetch student IDs from Custom Post Type
    $student_id_posts = get_posts([
        'post_type'      => 'student_id',
        'posts_per_page' => -1,
        'meta_key'       => 'student_id_number',
        'orderby'        => 'meta_value_num',
        'order'          => 'ASC',
    ]);
	
     // Filter student IDs within allowed range
    $filtered_student_ids = array_filter($student_id_posts, function($post) use ($allowed_min_id, $allowed_max_id) {
        $id = get_post_meta($post->ID, 'student_id_number', true);
        return is_numeric($id) && $id >= $allowed_min_id && $id <= $allowed_max_id;
    });

    // Function to render categories and subcategories
    function tsj_render_categories($categories) {
        $output = '';
        foreach ($categories as $categoryName => $subcategories) {
            $output .= '<div class="category" tabindex="0" aria-expanded="false" role="button">';
            $output .= '<span>' . esc_html($categoryName) . '</span>';
            $output .= '<span class="arrow">&#9654;</span>';
            $output .= '</div>';
            $output .= '<div class="subcategory-list">';
            foreach ($subcategories as $type => $name) {
                $output .= '<div class="subcategory" data-type="' . esc_attr($type) . '" data-category="' . esc_attr($categoryName) . '" tabindex="0">' . esc_html($name) . '</div>';
            }
            $output .= '</div>';
        }
        return $output;
    }

    // Start Output Buffering
    ob_start();
    ?>
    <!-- Teacher Strategy Journal Shortcode Output -->
    <style>
	/* Connector Line Styles */
#custom-connector-line {
    transition: all 0.3s ease;
    /* Additional styles can be added here if needed */
}



/* Vertical line below the first rectangle in the second row */


/* Add vertical line below the specified rectangles */
.journey-step::before {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    width: 4px;
    height: 60px; /* Adjust as needed */
    background-color: #adb5bd;
    transform: translateX(-50%);
    z-index: -1;
    border-radius: 2px;
    display: none; /* Default hidden */
}

/* Initially hide the vertical line */
.journey-step.vertical-line::before {
    display: none;
}

/* Show the vertical line when the next row is created */
.journey-step.vertical-line.show-vertical::before {
    display: block;
}		
		
		
        /* Add this CSS to position the sidebar and main content side by side */
        .js_strategy-journal-container {
            display: flex;
            width: 100%;
            height: 100%;
        }

     

        /* ==================== Category and Subcategory 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 ==================== */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding-left: 40px;
			padding-right:20p
            overflow: auto;
            position: relative;
        }

    
        /* ==================== 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 ==================== */
        .journey-path {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            position: relative;
            padding: 20px 0;
            width: 100%;
            max-width: 1600px;
            gap: 40px;
        }

        /* Horizontal Connection Lines */
        .journey-line {
            position: absolute;
        }

        /* 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: 100%
           
            flex-shrink: 0;
            transition: transform 0.3s ease;
        }

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

        /* Drop Zones */
        .drop-zone {
            width: 140px;
            height: 140px;
            border: 2px dashed #ced4da;
            border-radius: 12px;
            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 */
     
      

        /* Dividing Lines Between Rows */
        .journey-step.last-in-row::before {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            width: 4px;
            height: 60px;
            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;
            cursor: grab;
            transition: box-shadow 0.3s ease, transform 0.3s ease, background 0.5s ease, opacity 0.3s ease;
            width: 140px;
            height: 140px;
            user-select: none;
            padding: 20px 5px 5px 5px;
            overflow: visible;
            position: relative;
            box-sizing: border-box;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

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

        /* Checkmark Styles */
        .checkmark {
            position: absolute;
            top: -10px;
            left: -10px;
            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;
            font-size: 14px;
            text-align: center;
            width: 100%;
            word-wrap: break-word;
            border-bottom: 1px solid rgba(255, 255, 255, 0.3);
            padding-bottom: 4px;
        }

        /* Rectangle Title */
        .rectangle-title {
            font-size: 13px;
            text-align: center;
            word-wrap: break-word;
            word-break: break-word;
            flex-grow: 0;
            margin-top: 6px;
            padding: 5px;
            white-space: normal;
            overflow: hidden;
            text-overflow: ellipsis;
            box-sizing: border-box;
            width: 100%;
        }

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

        /* Specific Rectangle Types */
        .rectangle.differentiated-instruction,
        .rectangle.specific-adjustments,
        .rectangle.self-reflection {
            background: linear-gradient(145deg, #fbc2eb, #a6c1ee);
        }

        .rectangle.collaborative-learning {
            background: linear-gradient(145deg, #a18cd1, #fbc2eb);
        }

        .rectangle.behavior-modeling,
        .rectangle.individual-conversations {
            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,
        .rectangle.group-activities {
            background: linear-gradient(145deg, #f6d365, #fda085);
        }

        .rectangle.learning-games,
        .rectangle.behavior-charts {
            background: linear-gradient(145deg, #cfd9df, #e2ebf0);
        }

        .rectangle.student-reflections,
        .rectangle.classroom-observation {
            background: linear-gradient(145deg, #f093fb, #f5576c);
        }

        .rectangle.observations,
        .rectangle.peer-feedback {
            background: linear-gradient(145deg, #d4fc79, #96e6a1);
        }

        /* ==================== 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;
            height: 140px;
            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 ==================== */
        /* 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;
            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,
        .view-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;
            transition: opacity 0.3s ease; /* Add this line */
        }

        .popup,
        .view-popup {
            background: #ffffff;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            animation: fadeIn 0.3s ease;
            display: flex;
            flex-direction: column;
            max-height: 80vh;
            height: auto;
            overflow: hidden;
            transition: max-height 0.3s ease, height 0.3s ease;
        }

        .popup {
            max-width: 700px;
        }

        .view-popup {
            max-width: 500px;
        }

        .popup-header,
        .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;
        }

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

        /* Close Button in Popup */
        .popup-header .close-popup-btn,
        .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;
        }

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

        .popup-content,
        .view-popup-content {
            padding: 20px;
            overflow-y: auto;
            flex-grow: 1;
            max-height: calc(80vh - 160px);
        }

        .popup-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;
        }

        /* 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;
        }

        /* ==================== 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;
            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;
        }

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

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

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

            .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;
            }

            /* Responsive Toolbar */
            #toolbar {
                flex-wrap: wrap;
            }
        }

        /* 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);
        }

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

        /* Add spacing */
        .popup-content > div:first-child {
            margin-bottom: 15px;
        }

        /* Notering section */
        .notering-section {
            margin-top: 5px;
        }

        /* Note field */
        .note-field {
            height: 200px;
            min-height: 200px;
            overflow: auto;
        }
        /* Add your CSS styles here */
    </style>

            <!-- Strategy Menu -->
            <div class="strategy-menu" style="display: none;">
             
               

            </div>
        </div>

        <!-- Main Content with Journey Path and Tool Menu -->
  <div class="main-content delete-disabled drag-disabled">
    <div class="journey-path" id="journey-container" style="position: relative;">
        <!-- SVG Container for Connector Lines -->
        <svg id="connector-svg" width="100%" height="100%" style="position:absolute; top:0; left:0; pointer-events:none; z-index:0;">
            <defs>
                <!-- Define Arrowhead Marker -->
                <marker id="arrowhead" markerWidth="10" markerHeight="7" 
                        refX="10" refY="3.5" orient="auto">
                    <polygon points="0 0, 10 3.5, 0 7" fill="#adb5bd" />
                </marker>
            </defs>
        </svg>

                <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>
    </div>

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

    <!-- Popup for Gravity Forms -->
    <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">
                <?php
                    // Embed Gravity Form with ID 1
                    gravity_form(1, false, false, false, '', false);
                ?>
            </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>

    <!-- 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>

<script>
(function() {
    const tsj_ajax_object = {
        ajax_url: "<?php echo admin_url('admin-ajax.php'); ?>",
        add_nonce: "<?php echo wp_create_nonce('tsj_add_student_id_nonce'); ?>",
        remove_nonce: "<?php echo wp_create_nonce('tsj_remove_student_id_nonce'); ?>",
        allowed_min_id: <?php echo intval($allowed_min_id); ?>,
        allowed_max_id: <?php echo intval($allowed_max_id); ?>
    };

    const categories = <?php echo json_encode($categories); ?>; 
    const initialStudentIds = <?php echo json_encode($student_ids); ?>;
    const allowedMinStudentId = <?php echo $allowed_min_id; ?>;
    const allowedMaxStudentId = <?php echo $allowed_max_id; ?>;

    const predefinedTextMap = {
        'Instruktionsstrategier': 'Här är en fördefinierad text för Instruktionsstrategier.',
        'Klassrumsledning': 'Här är en fördefinierad text för Klassrumsledning.',
        'Elevstöd': 'Här är en fördefinierad text för Elevstöd.',
        'Observationer': 'Här är en fördefinierad text för Observationer.',
        'Feedback & Utvärdering': 'Här är en fördefinierad text för Feedback & Utvärdering.',
        'Specifika Insatser': 'Här är en fördefinierad text för Specifika Insatser.'
    };

    const contentMap = {
        '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'
    };

    let studentIds = initialStudentIds.slice();
    const defaultStudentIds = initialStudentIds.slice();

    // DOM elements
    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');
    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 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');

    const studentIdContainer = document.querySelector('.student-id-container');
    const studentIdInput = document.getElementById('student-id-input');
    const addStudentIdButton = document.getElementById('add-student-id');
    const studentIdList = document.querySelector('.student-id-list');
    const strategyMenu = document.querySelector('.strategy-menu');
    const backButton = document.getElementById('back-to-student-id');
    const studentIdHeader = document.querySelector('.student-id-container .menu-header');

    let currentStudentId = null;
    let draggedElement = null;
    let ghostElement = null;
    let isTouch = false;
    let isDraggingEnabled = false; 
    let isDeleteEnabled = false;   
    let currentEditingRect = null;
    let savedData = {};
    let studentJourneyStates = {};

    strategyMenu.style.display = 'none';

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

    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 findFirstEmptyDropZone() {
        return document.querySelector('.drop-zone:not(:has(.rectangle))');
    }

    function addJourneyStep() {
    const newStepIndex = document.querySelectorAll('.drop-zone').length;
    const journeyStep = document.createElement('div');
    journeyStep.classList.add('journey-step');

    const dropZone = document.createElement('div');
    dropZone.classList.add('drop-zone');
    dropZone.setAttribute('data-index', newStepIndex);
    dropZone.setAttribute('aria-label', 'Drop zone för strategi');
    dropZone.setAttribute('tabindex', '0');

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

    // Draw a line to the previous rectangle (if it exists)
    const journeySteps = Array.from(document.querySelectorAll('.drop-zone'));
    if (journeySteps.length > 1) {
        const previousRect = journeySteps[journeySteps.length - 2].querySelector('.rectangle');
        const currentRect = dropZone.querySelector('.rectangle');

        if (previousRect && currentRect) {
            drawConnectorLine(previousRect, currentRect);
        }
    }
}

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

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

        if (!savedData[rect.dataset.id]) {
            savedData[rect.dataset.id] = {
                title: title,
                note: '',
                predefinedText: predefinedTextMap[category] || '',
                checked: checked
            };
        }

        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);

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

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

        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);

        checkmark.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleCheckmark(rect);
        });

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

        return rect;
    }

    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: '', predefinedText: predefinedTextMap[rect.getAttribute('data-category')] || '', checked: true };
            } else {
                savedData[rectId].checked = true;
                if (!savedData[rectId].predefinedText) {
                    savedData[rectId].predefinedText = predefinedTextMap[rect.getAttribute('data-category')] || '';
                }
            }
            showToast('Strategi markerad som avslutad.');
        }
    }

/**
 * Updates all connectors within the journey path.
 */
function updateConnectors() {
    const journeySteps = Array.from(document.querySelectorAll('.drop-zone'));
    journeySteps.forEach(step => step.parentElement.classList.remove('last-in-row', 'first-in-row'));

    const rowMap = {};
    journeySteps.forEach(step => {
        const top = step.getBoundingClientRect().top;
        let rowFound = false;
        for (let row in rowMap) {
            if (Math.abs(rowMap[row].top - top) < 10) { // Tolerance for row alignment
                rowMap[row].steps.push(step.parentElement);
                rowFound = true;
                break;
            }
        }
        if (!rowFound) {
            rowMap[Object.keys(rowMap).length] = { top: top, steps: [step.parentElement] };
        }
    });

    const rows = Object.values(rowMap);

    // Iterate through each row and draw connectors
    rows.forEach((row, index) => {
        const steps = row.steps;

        if (steps.length) {
            // Assign 'last-in-row' to the last step
            const lastStep = steps[steps.length - 1];
            lastStep.classList.add('last-in-row');

            // Assign 'first-in-row' to the first step
            const firstStep = steps[0];
            firstStep.classList.add('first-in-row');

            // Draw within-row connectors
            for (let i = 0; i < steps.length - 1; i++) {
                const currentRect = steps[i].querySelector('.rectangle');
                const nextRect = steps[i + 1].querySelector('.rectangle');
                if (currentRect && nextRect) {
                    drawWithinRowConnector(currentRect, nextRect);
                }
            }

            // Draw between-row connectors
            if (index < rows.length - 1) {
                const nextRow = rows[index + 1].steps;
                if (nextRow.length) {
                    const fromRect = steps[steps.length - 1].querySelector('.rectangle');
                    const toRect = nextRow[0].querySelector('.rectangle');
                    if (fromRect && toRect) {
                        drawBetweenRowConnector(fromRect, toRect);
                    }
                }
            }
        }
    });
}



	
	function drawConnectorLine(rect1, rect2) {
    const svg = document.getElementById('connector-svg');
    if (!svg) return;

    const rect1Rect = rect1.getBoundingClientRect();
    const rect2Rect = rect2.getBoundingClientRect();
    const containerRect = document.getElementById('journey-container').getBoundingClientRect();

    // Calculate start and end positions
    const startX = rect1Rect.right - containerRect.left;
    const startY = rect1Rect.top + rect1Rect.height / 2 - containerRect.top;
    const endX = rect2Rect.left - containerRect.left;
    const endY = rect2Rect.top + rect2Rect.height / 2 - containerRect.top;

    // Create a line element
    const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    line.setAttribute('x1', startX);
    line.setAttribute('y1', startY);
    line.setAttribute('x2', endX);
    line.setAttribute('y2', endY);
    line.setAttribute('stroke', '#adb5bd');
    line.setAttribute('stroke-width', '2');
    line.setAttribute('stroke-linecap', 'round');
    line.setAttribute('marker-end', 'url(#arrowhead)'); // Optional arrowhead

    // Append the line to the SVG
    svg.appendChild(line);
}


/**
 * Draws a connector between two rows using three lines (vertical down, horizontal, vertical up).
 * @param {HTMLElement} rect1 - The last rectangle of the current row.
 * @param {HTMLElement} rect2 - The first rectangle of the next row.
 */
function drawBetweenRowConnector(rect1, rect2) {
    const svg = document.getElementById('connector-svg');
    if (!svg) return;

    // Remove existing between-row connectors to prevent duplication
    const existingBetweenRowConnectors = svg.querySelectorAll('.connector-line.between-row');
    existingBetweenRowConnectors.forEach(connector => connector.remove());

    // Calculate positions relative to the container
    const rect1Rect = rect1.getBoundingClientRect();
    const rect2Rect = rect2.getBoundingClientRect();
    const containerRect = document.getElementById('journey-container').getBoundingClientRect();

    // Start point: bottom center of rect1
    const startX = rect1Rect.left + rect1Rect.width / 2 - containerRect.left;
    const startY = rect1Rect.bottom - containerRect.top;

    // End point: top center of rect2
    const endX = rect2Rect.left + rect2Rect.width / 2 - containerRect.left;
    const endY = rect2Rect.top - containerRect.top;

    // Decide the Y position for the horizontal line
    // Position it slightly above the top of rect2 to create space for the vertical line
    const horizontalY = endY - 20; // 20px above the top of rect2

    // Create Vertical Line 1: From rect1 to horizontal line
    const verticalDown = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    verticalDown.setAttribute('x1', startX);
    verticalDown.setAttribute('y1', startY);
    verticalDown.setAttribute('x2', startX);
    verticalDown.setAttribute('y2', horizontalY);
    verticalDown.setAttribute('stroke', '#adb5bd');
    verticalDown.setAttribute('stroke-width', '2'); // Updated stroke width
    verticalDown.setAttribute('stroke-linecap', 'round');
    verticalDown.classList.add('connector-line', 'between-row');

    // Create Horizontal Line: Connecting the two vertical lines
    const horizontal = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    horizontal.setAttribute('x1', startX);
    horizontal.setAttribute('y1', horizontalY);
    horizontal.setAttribute('x2', endX);
    horizontal.setAttribute('y2', horizontalY);
    horizontal.setAttribute('stroke', '#adb5bd');
    horizontal.setAttribute('stroke-width', '2'); // Updated stroke width
    horizontal.setAttribute('stroke-linecap', 'round');
    horizontal.classList.add('connector-line', 'between-row');

    // Create Vertical Line 2: From horizontal line up to rect2 center top
    const verticalUp = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    verticalUp.setAttribute('x1', endX);
    verticalUp.setAttribute('y1', horizontalY);
    verticalUp.setAttribute('x2', endX);
    verticalUp.setAttribute('y2', endY);
    verticalUp.setAttribute('stroke', '#adb5bd');
    verticalUp.setAttribute('stroke-width', '2'); // Updated stroke width
    verticalUp.setAttribute('stroke-linecap', 'round');
    verticalUp.setAttribute('marker-end', 'url(#arrowhead)'); // Add arrowhead to the end
    verticalUp.classList.add('connector-line', 'between-row');

    // Append lines to SVG
    svg.appendChild(verticalDown);
    svg.appendChild(horizontal);
    svg.appendChild(verticalUp);
}

/**
 * Draws a connector within the same row with an arrow pointing to the right.
 * @param {HTMLElement} rect1 - The first rectangle element.
 * @param {HTMLElement} rect2 - The second rectangle element.
 */
function drawWithinRowConnector(rect1, rect2) {
    const svg = document.getElementById('connector-svg');
    if (!svg) return;

    // Remove existing within-row connectors to prevent duplication
    const existingWithinRowConnectors = svg.querySelectorAll('.connector-line.within-row');
    existingWithinRowConnectors.forEach(connector => connector.remove());

    // Calculate positions relative to the container
    const rect1Rect = rect1.getBoundingClientRect();
    const rect2Rect = rect2.getBoundingClientRect();
    const containerRect = document.getElementById('journey-container').getBoundingClientRect();

    // Start point: center right of rect1
    const startX = rect1Rect.right - containerRect.left;
    const startY = rect1Rect.top + rect1Rect.height / 2 - containerRect.top;

    // End point: center left of rect2
    const endX = rect2Rect.left - containerRect.left;
    const endY = rect2Rect.top + rect2Rect.height / 2 - containerRect.top;

    // Create the line element with arrow
    const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    line.setAttribute('x1', startX);
    line.setAttribute('y1', startY);
    line.setAttribute('x2', endX);
    line.setAttribute('y2', endY);
    line.setAttribute('stroke', '#adb5bd');
    line.setAttribute('stroke-width', '2'); // Adjust as needed
    line.setAttribute('stroke-linecap', 'round');
    line.setAttribute('marker-end', 'url(#arrowhead)'); // Add arrowhead

    line.classList.add('connector-line', 'within-row');

    // Append the line to the SVG
    svg.appendChild(line);
}

	
	
    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) {
            hoverPopup.style.display = 'block';
            hoverPopup.style.visibility = 'hidden';
            hoverPopup.style.opacity = '0';

            hoverTitle.textContent = title || 'Ingen titel';
            hoverNote.innerHTML = note || 'Ingen notering';

            const rectBounds = rect.getBoundingClientRect();
            const popupWidth = hoverPopup.offsetWidth;
            const viewportWidth = window.innerWidth;

            let top, left;
            if (rectBounds.right + popupWidth + 10 < viewportWidth) {
                top = rectBounds.top + window.scrollY;
                left = rectBounds.right + window.scrollX + 10;
            } else {
                top = rectBounds.bottom + window.scrollY + 10;
                left = rectBounds.left + window.scrollX;
                if (left + popupWidth + 10 > viewportWidth) {
                    left = viewportWidth - popupWidth - 10;
                }
            }

            hoverPopup.style.top = `${top}px`;
            hoverPopup.style.left = `${left}px`;
            hoverPopup.classList.add('visible');
        }
    }

    function hideHoverPopup() {
        hoverPopup.classList.remove('visible');
    }

    function showPopupMenu(rect) {
        if (rect.classList.contains('checked')) {
            openViewPopup(rect);
        } else {
            currentEditingRect = rect;
            const name = rect.querySelector('.rectangle-name').textContent;
            popupHeader.textContent = `Redigera ${name}`;
            openPopup();
        }
    }

    function openPopup() {
        popupOverlay.style.display = 'flex';
        const firstInput = popupOverlay.querySelector('input, textarea, select');
        if (firstInput) {
            firstInput.focus();
        }
    }

    function closePopup() {
        popupOverlay.style.display = 'none';
        currentEditingRect = null;
        popupHeader.textContent = 'Redigera Strategi';
    }

    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 : '';

        viewName.textContent = name;
        viewTitle.innerHTML = title || 'Ingen titel';
        viewNote.innerHTML = note || 'Ingen notering';
        viewPopupHeader.textContent = `DETALJER FÖR ${name}`;
        viewPopupOverlay.style.display = 'flex';
        setTimeout(() => {
            viewPopupOverlay.style.opacity = '1';
        }, 0);
    }

    function closeViewPopup() {
        viewPopupOverlay.style.opacity = '0';
        setTimeout(() => {
            viewPopupOverlay.style.display = 'none';
            viewPopupHeader.textContent = 'Strategi Detaljer';
        }, 300);
    }

    function removeRectangle(rect) {
        const dropZone = rect.parentElement;
        const journeyStep = dropZone.parentElement;

        const rectId = rect.dataset.id;
        delete savedData[rectId];
        rect.remove();
        dropZone.remove();

        if (journeyStep.querySelectorAll('.drop-zone').length === 0) {
            journeyStep.remove();
        }

        updateConnectors();
    }

    function saveJourneyState(studentId) {
        const journeyData = getJourneyData();
        studentJourneyStates[studentId] = journeyData;
    }

    function loadJourneyState(studentId) {
        const journeyData = studentJourneyStates[studentId];
        if (journeyData) {
            setJourneyData(journeyData);
        } else {
            clearJourneyPath();
            updateConnectors();
        }
    }

    function getJourneyData() {
        const journeySteps = Array.from(document.querySelectorAll('.drop-zone'));
        const data = journeySteps.map(dropZone => {
            const rect = dropZone.querySelector('.rectangle');
            if (rect) {
                const rectId = rect.dataset.id;
                const type = Array.from(rect.classList).find(cls => cls !== 'rectangle' && cls !== 'dimmed' && cls !== 'checked');
                const name = rect.querySelector('.rectangle-name').textContent;
                const saved = savedData[rectId] || {};
                return {
                    type: type,
                    name: name,
                    title: saved.title || '',
                    note: saved.note || '',
                    predefinedText: saved.predefinedText || '',
                    checked: saved.checked || false,
                    category: rect.getAttribute('data-category') || ''
                };
            } else {
                return null;
            }
        }).filter(item => item !== null);
        return data;
    }

    function setJourneyData(data) {
        clearJourneyPath();
        data.forEach(item => {
            addJourneyStep();
            const dropZone = document.querySelector('.drop-zone:last-child');
            const rect = createRectangle(item.type, item.name, item.title, item.checked, item.category);
            savedData[rect.dataset.id] = {
                title: item.title,
                note: item.note,
                predefinedText: item.predefinedText,
                checked: item.checked
            };
            dropZone.appendChild(rect);
        });
        updateConnectors();
    }

    function clearJourneyPath() {
        journeyContainer.innerHTML = '<div class="journey-line"></div>';
        savedData = {};
    }

    window.addEventListener('beforeunload', () => {
        if (currentStudentId) {
            saveJourneyState(currentStudentId);
        }
    });

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

        const rect = e.target.closest('.rectangle');
        if (rect && !e.target.closest('.remove-button') && !e.target.closest('.checkmark')) {
            showPopupMenu(rect);
        }
    });

    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) {
                if (confirm('Är du säker på att du vill ta bort denna strategi?')) {
                    removeRectangle(rect);
                }
            }
        }
    });

    document.body.addEventListener('mouseenter', function(e) {
        const rect = e.target.closest('.rectangle');
        if (rect && rect.classList.contains('checked')) {
            showHoverPopup(rect);
        }
    }, true);

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

    hoverPopup.addEventListener('mouseenter', () => {
        hoverPopup.classList.add('visible');
    });

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

    // Drag/Drop handlers
    function swapElements(el1, el2) {
        const parent1 = el1.parentElement;
        const parent2 = el2.parentElement;
        parent1.appendChild(el2);
        parent2.appendChild(el1);
        updateConnectors();
    }

    function handleDragStart(e) {
        if (!isDraggingEnabled) return;
        const targetRect = e.target.closest('.rectangle');
        if (targetRect) {
            draggedElement = targetRect;
            draggedElement.classList.add('dragging');
            ghostElement = draggedElement.cloneNode(true);
            ghostElement.classList.add('dragging-ghost');
            document.body.appendChild(ghostElement);
            updateGhostPosition(e.pageX, e.pageY);
            setTimeout(() => { draggedElement.style.opacity = '0'; }, 0);
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', '');
        }
    }

    function handleDragOver(e) {
        if (!isDraggingEnabled) return;
        e.preventDefault();
        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');
        }
    }

    function handleDrop(e) {
        if (!isDraggingEnabled) return;
        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);
                updateConnectors();
            }
        }
        endDrag();
    }

    function handleDragEnd(e) {
        if (!isDraggingEnabled) return;
        endDrag();
        document.querySelectorAll('.drop-zone').forEach(zone => zone.classList.remove('over'));
    }

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

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

    function handleMouseMove(e) {
        if (ghostElement) {
            updateGhostPosition(e.pageX, e.pageY);
        }
    }

    function handleTouchStart(e) {
        if (!isDraggingEnabled) return;
        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();
            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);
            draggedElement.style.opacity = '0';
            document.addEventListener('touchmove', handleTouchMove, { passive: false });
            document.addEventListener('touchend', handleTouchEnd);
        }
    }

    function handleTouchMove(e) {
        if (!isDraggingEnabled) return;
        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');
            }
        }
    }

    function handleTouchEnd(e) {
        if (!isDraggingEnabled) return;
        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);
                updateConnectors();
            }
        }

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

    // Main menu strategy click handler
    function initializeMainMenuStrategyClick() {
        const mainMenu = document.getElementById('custom-sidemenu');
        if (!mainMenu) return;

        mainMenu.addEventListener('click', function(e) {
            const submenuItem = e.target.closest('.submenu-item');
            if (submenuItem) {
                const type = submenuItem.getAttribute('data-type');
                const category = submenuItem.getAttribute('data-category');
                const name = contentMap[type] || 'Strategi';

                let firstEmpty = findFirstEmptyDropZone();
                if (!firstEmpty) {
                    addJourneyStep();
                    firstEmpty = findFirstEmptyDropZone();
                }

                if (firstEmpty) {
                    const rect = createRectangle(type, name, '', false, category);
                    firstEmpty.appendChild(rect);
                    updateConnectors();
                } else {
                    showToast('Alla steg är fulla!');
                }
            }
        });
    }

    // No sidebar anymore, so we don't initialize student id click from sidebar.

    // Main menu student ID click handler
    function initializeMainMenuStudentIdClick() {
        const mainMenuStudentLinks = document.querySelectorAll('#custom-sidemenu .menu-item a[data-id]');
        mainMenuStudentLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const studentId = this.getAttribute('data-id');
                strategyMenu.style.display = 'block';
                const headerText = strategyMenu.querySelector('h2.menu-header');
                if (headerText) {
                    headerText.textContent = `Strategimeny - Student ID ${studentId}`;
                }
                currentStudentId = studentId;
                showToast(`Vald Student ID: ${studentId}`);

                if (studentIdContainer) studentIdContainer.style.display = 'none';
                if (addStudentIdButton) addStudentIdButton.style.display = 'none';
                if (studentIdList) studentIdList.style.display = 'none';
                if (studentIdInput) studentIdInput.style.display = 'none';
                if (studentIdHeader) studentIdHeader.style.display = 'none';

                // Remove all student IDs from main menu
                const allStudentItems = document.querySelectorAll('#custom-sidemenu .menu-item[data-id]');
                allStudentItems.forEach(item => {
                    const sid = item.getAttribute('data-id');
                    document.dispatchEvent(new CustomEvent('updateMenuItems', {
                        detail: {
                            action: 'remove',
                            parentMenuId: 'custom-sidemenu',
                            menuItemId: sid
                        }
                    }));
                });

                // Add categories to main menu
                for (const [catName, subcats] of Object.entries(categories)) {
                    const catId = catName.replace(/\s+/g, '-').toLowerCase();
                    document.dispatchEvent(new CustomEvent('updateMenuItems', {
                        detail: {
                            action: 'add',
                            parentMenuId: 'custom-sidemenu',
                            menuItemHtml: `
                                <div class="menu-category" data-id="${catId}">
                                    <div class="menu-title">${catName}</div>
                                    <div class="submenu">
                                        ${Object.entries(subcats).map(([subType, subLabel]) => `
                                            <a href="#" class="submenu-item" data-type="${subType}" data-category="${catName}">${subLabel}</a>
                                        `).join('')}
                                    </div>
                                </div>
                            `
                        }
                    }));
                }

                // After adding categories, ensure main menu strategies can be clicked
                initializeMainMenuStrategyClick();
            });
        });
    }

    function resetStudentIdList() {
        if (addStudentIdButton) addStudentIdButton.style.display = 'block';
        if (studentIdList) studentIdList.style.display = 'block';
        if (studentIdInput) studentIdInput.style.display = 'flex';
    }

  

    function initializePredefinedTextEdit() {
        const editButton = document.getElementById('edit-predefined-text');
        const predefinedTextDiv = document.getElementById('predefined-text');
        if(!editButton || !predefinedTextDiv) return;

        editButton.addEventListener('click', () => {
            if (predefinedTextDiv.contentEditable === 'false') {
                predefinedTextDiv.contentEditable = 'true';
                predefinedTextDiv.classList.add('editable');
                predefinedTextDiv.focus();
                editButton.textContent = 'Spara';
            } else {
                predefinedTextDiv.contentEditable = 'false';
                predefinedTextDiv.classList.remove('editable');
                editButton.textContent = 'Redigera';
            }
        });
    }

 

   

    saveBtn.addEventListener('click', () => {
        const form = popupOverlay.querySelector('form#gform_1');
        if(!form){
            showToast('Formulär hittades inte.');
            return;
        }

        const formData = new FormData(form);
        const serializedData = new URLSearchParams(formData).toString();

        fetch(tsj_ajax_object.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: new URLSearchParams({
                'action': 'tsj_submit_gravity_form',
                'csrf_token': '<?php echo wp_create_nonce('tsj_submit_gravity_form_nonce'); ?>',
                'form_data': serializedData
            })
        })
        .then(response => response.json())
        .then(data => {
            if(data.success){
                showToast(data.data.message);
                closePopup();
            } else {
                showToast(data.data.message || 'Ett fel uppstod vid formulärsändningen.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Ett fel uppstod vid formulärsändningen.');
        });
    });

    cancelBtn.addEventListener('click', () => {
        closePopup();
    });

    closePopupBtn.addEventListener('click', () => {
        closePopup();
    });

    viewCloseBtn.addEventListener('click', () => {
        closeViewPopup();
    });

    closeViewPopupBtn.addEventListener('click', () => {
        closeViewPopup();
    });

    document.addEventListener('DOMContentLoaded', () => {
        // Add a static title "Studentid" to main menu
        document.dispatchEvent(new CustomEvent('updateMenuItems', {
            detail: {
                action: 'addTitle',
                parentMenuId: 'custom-sidemenu',
                menuTitleHtml: '<div class="menu-title static-title">Studentid</div>'
            }
        }));

        <?php foreach ($student_ids as $sid): ?>
        document.dispatchEvent(new CustomEvent('updateMenuItems', {
            detail: {
                action: 'add',
                parentMenuId: 'custom-sidemenu',
                menuItemHtml: '<div class="menu-item" data-id="<?php echo esc_attr($sid); ?>"><a href="#<?php echo esc_attr($sid); ?>" data-id="<?php echo esc_attr($sid); ?>"><?php echo esc_html($sid); ?></a></div>'
            }
        }));
        <?php endforeach; ?>

        initializeMainMenuStudentIdClick();
        updateConnectors();
        document.querySelector('.main-content').classList.add('delete-disabled', 'drag-disabled');
       
        initializePredefinedTextEdit();

        if (allowedMinStudentId === allowedMaxStudentId) {
            studentIdInput.disabled = true;
            addStudentIdButton.disabled = true;
        }

        resetStudentIdList();
    });

   let resizeTimeout;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
        updateConnectors();
    }, 250); // Adjust the timeout as needed
}); 
	
	
	 // 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);
        });


    journeyContainer.addEventListener('dragstart', handleDragStart);
    journeyContainer.addEventListener('dragover', handleDragOver);
    journeyContainer.addEventListener('drop', handleDrop);
    journeyContainer.addEventListener('dragend', handleDragEnd);
    document.addEventListener('mousemove', handleMouseMove);
    journeyContainer.addEventListener('touchstart', handleTouchStart, { passive: false });
    document.addEventListener('dragover', function(e) { e.preventDefault(); }, false);
    document.addEventListener('drop', function(e) { e.preventDefault(); }, false);

	
})();
</script>

     
  <?php
  // End Output Buffering and Return Content
  return ob_get_clean();
}