<?php
$imageEngineTenant = preg_replace('/[^a-z0-9.-]/i', '', (string)($_SERVER['HTTP_HOST'] ?? ''));
$imageEngineDocumentRoot = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\');
$imageEngineConfigs = array_filter([
    $imageEngineDocumentRoot !== '' ? $imageEngineDocumentRoot . '/config.php' : '',
    $imageEngineTenant !== '' ? '../../../' . $imageEngineTenant . '/config.php' : '',
    '/config.php'
]);
$imageEngineConfigLoaded = false;
foreach ($imageEngineConfigs as $imageEngineConfig) {
    if (file_exists($imageEngineConfig)) {
        require_once $imageEngineConfig;
        $imageEngineConfigLoaded = true;
        break;
    }
}
if (!$imageEngineConfigLoaded) {
    http_response_code(500);
    exit('Image Engine configuration could not be loaded.');
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>LEV Drawing App</title>
    
     <script>
    const TENANT_URL = "<?=TENANT_URL?>";
    const ROOT_URL = "<?=ROOT_URL?>";
    </script>
    <style>
      body,
      html {
        height: 100%;
        margin: 0;
        overflow: hidden;
      }
      #drawingAppContainer {
        display: grid;
        grid-template-columns: 254px minmax(0, 1fr);
        height: 100%;
        background: #edf1f5;
      }
      #toolbar {
        padding: 16px 14px;
        background: linear-gradient(135deg, #19324a, #2c506f);
        display: flex;
        flex-direction: column;
        flex-wrap: nowrap;
        gap: 12px;
        align-items: stretch;
        box-shadow: 0 2px 8px rgba(21, 44, 65, .25);
        z-index: 3;
        overflow-y: auto;
      }
      .toolbar-group { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; padding: 0 0 12px; border-bottom: 1px solid rgba(255,255,255,.22); }
      .toolbar-group:last-of-type { border-bottom: 0; padding-bottom: 0; }
      .toolbar-title { font-weight: 700; letter-spacing: .01em; white-space: nowrap; padding-bottom: 12px; border-bottom: 1px solid rgba(255,255,255,.35); }
      .toolbar-title i { color: #67d5ef; margin-right: 7px; }
      .toolbar-group-label { width: 100%; color: rgba(255,255,255,.72); font-size: .69rem; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; margin-right: 1px; }
      .toolbar-separator { display: none; }
      #editorHint { margin-top: auto; font-size: .78rem; line-height: 1.35; color: rgba(255,255,255,.84); padding: 10px; border-radius: 5px; background: rgba(0,0,0,.14); }
      #toolbar .btn { min-width: 34px; }
      #canvasContainer { grid-column: 2; }
      #mobileToolbarToggle, #mobileToolbarBackdrop { display: none; }
      #canvasContainer {
        flex: 1 1 auto;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        position: relative;
        background: radial-gradient(circle at 50% 0, #ffffff 0, #eef2f6 65%);
        min-height: 0;
        box-sizing: border-box;
      }
      #drawingCanvas {
        /* Fabric controls size */
      }
      .canvas-container {
        /* Fabric wrapper */
      }
      .tool-btn.active {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.5);
      }
      .canvas-container { max-width: 100%; border: 1px solid #d7e0e8; border-radius: 4px; background: #fff; }
      #canvasContainer { overflow: auto; align-items: flex-start; padding: 22px; }
      .canvas-container { box-shadow: 0 5px 18px rgba(32, 57, 78, .15); }
      .image-engine-grid {
        position: absolute;
        inset: 0;
        pointer-events: none;
        z-index: 1;
        display: none;
        background-image: linear-gradient(to right, rgba(108,117,125,.24) 1px, transparent 1px), linear-gradient(to bottom, rgba(108,117,125,.24) 1px, transparent 1px);
        background-size: 25px 25px;
      }
      .canvas-container .upper-canvas { z-index: 2 !important; }
      @media (max-width: 1199.98px) {
        #drawingAppContainer { grid-template-columns: minmax(0, 1fr); }
        #canvasContainer { grid-column: 1; }
        #toolbar {
          position: fixed;
          inset: 0 auto 0 0;
          width: min(300px, calc(100vw - 54px));
          transform: translateX(-105%);
          transition: transform .22s ease;
          z-index: 1055;
          box-shadow: 4px 0 18px rgba(18, 37, 54, .35);
        }
        #toolbar.is-open { transform: translateX(0); }
        #mobileToolbarToggle {
          display: inline-flex;
          position: fixed;
          left: 12px;
          top: 12px;
          z-index: 1040;
          min-width: 44px;
          min-height: 44px;
          align-items: center;
          justify-content: center;
          box-shadow: 0 3px 10px rgba(20, 47, 70, .28);
        }
        #mobileToolbarBackdrop {
          position: fixed;
          inset: 0;
          z-index: 1050;
          background: rgba(15, 30, 43, .42);
        }
        #mobileToolbarBackdrop.is-open { display: block; }
        #canvasContainer { padding: 12px; justify-content: flex-start; }
        .tool-btn, #toolbar .btn { min-width: 42px; min-height: 42px; }
      }
      /* Styles for icon modal items */
      .icon-entry {
        display: inline-block;
        margin: 8px;
        padding: 5px;
        vertical-align: top;
        cursor: pointer;
        width: 80px; /* Adjust width as needed */
        text-align: center;
        border: 1px solid transparent;
        border-radius: 4px;
        transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out;
      }
      .icon-entry:hover {
        border-color: #007bff;
        background-color: #e9ecef;
      }
      .icon-entry img {
        max-width: 50px; /* Slightly smaller max width */
        max-height: 50px;
        display: block;
        margin: 0 auto 5px auto; /* Center image, space below */
      }
      .icon-entry div {
        font-size: 0.8em;
        word-wrap: break-word;
        line-height: 1.2;
      }

      /* Cursor styles */
      .cursor-grab { cursor: grab; }
      .cursor-grabbing { cursor: grabbing; }
      .cursor-pointer { cursor: pointer; }
      .cursor-nwse-resize { cursor: nwse-resize; }
      .cursor-nesw-resize { cursor: nesw-resize; }
      .cursor-ew-resize { cursor: ew-resize; }
      .cursor-ns-resize { cursor: ns-resize; }
      .cursor-crosshair { cursor: crosshair; }
      .cursor-default { cursor: default; }
      .cursor-rotate { cursor: alias; }
      
      /* Styles for template modal container and items */
      #templateLibrary { /* Container for the template entries */
        display: flex;         /* Enable Flexbox */
        flex-wrap: wrap;       /* Allow items to wrap to the next line */
        justify-content: center; /* Center items horizontally (or use flex-start/space-around) */
        gap: 15px;             /* Add space between items (adjust as needed) */
        padding: 10px 0;       /* Add some padding top/bottom */
      }

      .template-entry {
        /* Removed display: inline-block and vertical-align */
        width: 100px;           /* Define base width (adjust as needed) */
        flex-grow: 0;           /* Don't allow items to grow */
        flex-shrink: 0;         /* Don't allow items to shrink */
        /* Height will now automatically adjust to the tallest item in each row */

        /* Internal layout for icon + text within the box */
        display: flex;
        flex-direction: column;    /* Stack icon above text */
        justify-content: flex-start;/* Align content to the top of the box */
        align-items: center;      /* Center content horizontally */

        box-sizing: border-box; /* Include padding and border in the element's total width and height */
        margin: 0;              /* Gap property handles spacing */
        padding: 10px;
        cursor: pointer;
        text-align: center;
        border: 1px solid #ccc;
        border-radius: 4px;
        transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out;
      }
      .template-entry:hover {
        border-color: #007bff;
        background-color: #e9ecef;
      }
      .template-entry i { /* Icon style */
        font-size: 2.5em;
        display: block;
        margin-bottom: 10px; /* Increased space below icon */
        color: #6c757d;
        flex-shrink: 0; /* Prevent icon from shrinking */
      }
      .template-entry div { /* Text label style */
        font-size: 0.85em;
        word-wrap: break-word; /* Allow wrapping */
        line-height: 1.2;
        /* Let the container handle height - remove max-height/overflow for now */
      }
    </style>
    <script src='../src/js/jq.js'></script>
    <?= "<link href='../packages/font-awesome/css/all.min.css' rel='stylesheet'>
    <link href='../packages/mdb/css/mdb.min.css' rel='stylesheet' />
    <link href='../packages/mdb/plugins/css/all.min.css' rel='stylesheet' />
    <link href='../src/css/custom2.min.css' rel='stylesheet'> 
    <script src='../src/js/custom.min.js'></script>
    "?>
  </head>
  <body> <div id="response" class="response-container"></div>
    <button type="button" class="btn btn-info" id="mobileToolbarToggle" data-mdb-tooltip-init data-mdb-placement="right" data-mdb-trigger="hover" title="Open editor tools" aria-controls="toolbar" aria-expanded="false"><i class="fad fa-tools"></i></button>
    <div id="mobileToolbarBackdrop" aria-hidden="true"></div>
    <div id="drawingAppContainer">
      <div id="toolbar" class="text-light">
        <span class="toolbar-title"><i class="fad fa-draw-square"></i>Image Engine</span>
        <div class="toolbar-group">
          <span class="toolbar-group-label">Draw</span>
          <button type="button" class="btn btn-light btn-sm tool-btn active" data-tool="select" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Select, move and resize"><i class="fad fa-mouse-pointer"></i></button>
          <button type="button" class="btn btn-light btn-sm tool-btn" data-tool="freehand" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Draw freehand"><i class="fad fa-pencil-alt"></i></button>
          <button type="button" class="btn btn-light btn-sm tool-btn" data-tool="line" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Draw one line"><i class="far fa-minus"></i></button>
          <button type="button" class="btn btn-light btn-sm tool-btn" data-tool="rectangle" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Draw one rectangle"><i class="far fa-square"></i></button>
          <button type="button" class="btn btn-light btn-sm tool-btn" data-tool="circle" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Draw one circle"><i class="far fa-circle"></i></button>
          <button type="button" class="btn btn-light btn-sm tool-btn" data-tool="triangle" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Draw one triangle"><i class="far fa-triangle"></i></button>
          <button type="button" class="btn btn-light btn-sm tool-btn" data-tool="text" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Add text"><i class="far fa-font"></i></button>
        </div>
        <span class="toolbar-separator"></span>
        <div class="toolbar-group">
          <span class="toolbar-group-label">Style</span>
          <input type="color" id="lineColor" value="#000000" title="Colour" class="form-control form-control-sm" style="width: 46px; padding: 0.2rem" />
          <label for="shapeFillMode" class="form-label-sm mb-0">Shape:</label>
          <select id="shapeFillMode" class="form-select form-select-sm" style="width: 92px" title="Standard shape fill mode">
            <option value="outline" selected>Outline</option>
            <option value="filled">Filled</option>
          </select>
          <label for="lineWidth" class="form-label-sm mb-0">W:</label>
           <input type="range" class="form-range-sm" id="lineWidth" min="1" max="50" value="5" style="width: 70px" />
           <span id="lineWidthValue">5</span>
        </div>
        <span class="toolbar-separator"></span>
        <div class="toolbar-group">
          <span class="toolbar-group-label">Icons</span>
           <button type="button" class="btn btn-info btn-sm" data-mdb-modal-init data-mdb-target="#iconModal" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Add icon"><i class="fad fa-icons"></i></button>
        </div>
        <span class="toolbar-separator"></span>
        <div class="toolbar-group">
          <span class="toolbar-group-label">Arrange</span>
          <button type="button" class="btn btn-light btn-sm" id="bringForward" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Bring selected object forward"><i class="fad fa-layer-plus"></i></button>
          <button type="button" class="btn btn-light btn-sm" id="sendBackward" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Send selected object backward"><i class="fad fa-layer-minus"></i></button>
          <button type="button" class="btn btn-light btn-sm" id="cloneSelected" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clone selected object"><i class="fad fa-clone"></i></button>
          <button type="button" class="btn btn-danger btn-sm" id="deleteSelected" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Delete selected object"><i class="fad fa-eraser"></i></button>
          <button type="button" class="btn btn-danger btn-sm" id="clearCanvas" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear the canvas"><i class="fad fa-trash-alt"></i></button>
        </div>
        <span class="toolbar-separator"></span>
        <div class="toolbar-group">
          <span class="toolbar-group-label">Output</span>
          <button type="button" class="btn btn-success btn-sm" id="saveAsImage" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save image"><i class="fad fa-save"></i></button>
          <button type="button" class="btn btn-light btn-sm" id="downloadImage" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Download image"><i class="fad fa-download"></i></button>
          <button type="button" class="btn btn-warning btn-sm" id="saveAsTemplate" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save template"><i class="fad fa-file-code"></i></button>
          <button type="button" class="btn btn-info btn-sm mb-0" id="loadTemplateBtn" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Load template"><i class="fad fa-folder-open"></i></button>
          <button type="button" class="btn btn-light btn-sm" id="fullscreenBtn" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Toggle fullscreen"><i class="fad fa-expand"></i></button>
        </div>
        <div class="toolbar-group">
          <span class="toolbar-group-label">Canvas</span>
          <button type="button" class="btn btn-light btn-sm" id="toggleGrid" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Show placement grid" aria-pressed="false"><i class="fad fa-grid-4"></i><span class="ms-1 d-none d-xl-inline">Grid</span></button>
        </div>
        <span id="editorHint"><i class="fad fa-mouse-pointer me-1"></i>Select an object to move, resize or layer it</span>
      </div>
      <div id="canvasContainer">
        <canvas id="drawingCanvas"></canvas>
      </div>
    </div>

    <div class="modal fade" id="textModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Enter Text</h5>
            <button type="button" class="btn-close" data-mdb-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input type="text" id="textInput" class="form-control" placeholder="Text" />
          </div>
          <div class="modal-footer"><button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button> <button type="button" class="btn btn-info" id="addTextBtn">Add Text</button></div>
        </div>
      </div>
    </div>
    <div class="modal fade" id="iconModal" tabindex="-1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Select Icon</h5>
            <button type="button" class="btn-close" data-mdb-dismiss="modal"></button>
          </div>
          <div class="modal-body" id="iconLibrary" style="text-align: center;"> </div>
          <div class="modal-footer"><button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button></div>
        </div>
      </div>
    </div>
    
    <div class="modal fade" id="templateLoadModal" tabindex="-1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Load Template</h5>
            <button type="button" class="btn-close" data-mdb-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <div id="templateLibrary" style="text-align: center;">
              <p>Loading templates...</p>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>

    <script src='../packages/mdb/js/mdb.umd.min.js'></script>
    <script src='../packages/mdb/plugins/js/all.min.js'></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>

    <script>
      document.addEventListener("DOMContentLoaded", async () => { 
        const canvasElement = document.getElementById("drawingCanvas");
        const canvasContainer = document.getElementById("canvasContainer");
        const fabricCanvas = new fabric.Canvas(canvasElement, {
          isDrawingMode: false,
          backgroundColor: "#ffffff",
          width: 300,
          height: 200,
        });

        const lineColorInput = document.getElementById("lineColor");
        const shapeFillMode = document.getElementById("shapeFillMode");
        const lineWidthInput = document.getElementById("lineWidth");
        const lineWidthValue = document.getElementById("lineWidthValue");
        const toggleGridBtn = document.getElementById("toggleGrid");
        const textModalElement = document.getElementById("textModal");
        const textModal = new mdb.Modal(textModalElement);
        const addTextBtn = document.getElementById("addTextBtn");
        const textInput = document.getElementById("textInput");
        const iconModalElement = document.getElementById("iconModal");
        const iconModal = new mdb.Modal(iconModalElement);
        const iconLibraryContainer = document.getElementById("iconLibrary");
        const templateLoadModalElement = document.getElementById("templateLoadModal");
        const templateLoadModal = new mdb.Modal(templateLoadModalElement);
        const templateLibraryContainer = document.getElementById("templateLibrary");

        const clearCanvasBtn = document.getElementById("clearCanvas");
        const deleteSelectedBtn = document.getElementById("deleteSelected");
        const bringForwardBtn = document.getElementById("bringForward");
        const sendBackwardBtn = document.getElementById("sendBackward");
        const cloneSelectedBtn = document.getElementById("cloneSelected");
        const saveAsImageBtn = document.getElementById("saveAsImage");
        const downloadImageBtn = document.getElementById("downloadImage");
        const saveAsTemplateBtn = document.getElementById("saveAsTemplate");
        const loadTemplateBtn = document.getElementById("loadTemplateBtn"); // Updated load button ID
        const fullscreenBtn = document.getElementById("fullscreenBtn");
        const toolbarElement = document.getElementById("toolbar");
        const editorHint = document.getElementById("editorHint");
        const mobileToolbarToggle = document.getElementById("mobileToolbarToggle");
        const mobileToolbarBackdrop = document.getElementById("mobileToolbarBackdrop");

        let currentTool = "select";
        let currentColor = lineColorInput.value;
        let currentLineWidth = parseInt(lineWidthInput.value, 10);
        let selectedIconSrc = null;
        let isDrawingShape = false;
        let shapeStartX, shapeStartY;
        let textPlacementPos = null;
        let activeShapeBeingDrawn = null;
        let placementGridVisible = false;
        const placementGrid = document.createElement("div");
        placementGrid.className = "image-engine-grid";
        placementGrid.setAttribute("aria-hidden", "true");
        fabricCanvas.wrapperEl.appendChild(placementGrid);

        function updatePlacementGrid() {
          placementGrid.style.width = fabricCanvas.getWidth() + "px";
          placementGrid.style.height = fabricCanvas.getHeight() + "px";
          placementGrid.style.display = placementGridVisible ? "block" : "none";
          toggleGridBtn.setAttribute("aria-pressed", placementGridVisible ? "true" : "false");
          toggleGridBtn.classList.toggle("btn-info", placementGridVisible);
          toggleGridBtn.classList.toggle("btn-light", !placementGridVisible);
          toggleGridBtn.title = placementGridVisible ? "Hide placement grid" : "Show placement grid";
          setEditorHint(placementGridVisible ? "Placement grid is on — it is never included in saved images" : "Placement grid is off", "fa-grid-4");
        }

        let icons = []; 

        function selectToolAfterPlacement() {
          selectedIconSrc = null;
          currentTool = "select";
          fabricCanvas.isDrawingMode = false;
          fabricCanvas.selection = true;
          updateActiveToolButton(document.querySelector('.tool-btn[data-tool="select"]'));
          updateCursorState();
          fabricCanvas.requestRenderAll();
        }

        function setEditorHint(message, icon) {
          if (!editorHint) return;
          editorHint.innerHTML = `<i class="fad ${icon || 'fa-mouse-pointer'} me-1"></i>${message}`;
        }

        function isCompactEditor() {
          return window.matchMedia("(max-width: 1199.98px)").matches;
        }

        function setMobileToolbarOpen(open) {
          if (!isCompactEditor()) return;
          toolbarElement.classList.toggle("is-open", open);
          mobileToolbarBackdrop.classList.toggle("is-open", open);
          mobileToolbarToggle.setAttribute("aria-expanded", open ? "true" : "false");
          mobileToolbarToggle.title = open ? "Close editor tools" : "Open editor tools";
        }

        function askForName(title, label, initialValue, confirmLabel, callback) {
          const id = "imageEngineNamePrompt";
          const html = `<div class="mb-0"><label class="form-label" for="${id}Input">${label}</label><input type="text" class="form-control" id="${id}Input" maxlength="80" value="${String(initialValue).replace(/[&<>\"]/g, function(c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c]); })}" /></div>`;
          loadModalContent(html, id, "modal-sm", 1080, "true", title, "cancelConfirm", function() {
            const input = document.getElementById(id + "Input");
            const value = input ? input.value.trim() : "";
            if (!value) {
              showResponse("warning", "Please enter a name.");
              return;
            }
            killModal(id);
            callback(value);
          });
        }

        fabric.Object.prototype.set({
          transparentCorners: false,
          cornerColor: "#007bff",
          cornerStrokeColor: "#ffffff",
          borderColor: "#007bff",
          cornerSize: 10,
          borderScaleFactor: 1.5,
          centeredScaling: true,
          centeredRotation: true,
        });
        // Fabric's default rotation control uses a crosshair. Use a distinct circular-arrow cursor
        // so the rotate handle is immediately recognisable without changing resize-control cursors.
        if (fabric.Object.prototype.controls && fabric.Object.prototype.controls.mtr) {
          fabric.Object.prototype.controls.mtr.cursorStyle = 'url("data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2728%27 height=%2728%27 viewBox=%270 0 28 28%27%3E%3Cpath d=%27M22 11a8.5 8.5 0 1 0 1.1 6.8%27 fill=%27none%27 stroke=%27%2319324a%27 stroke-width=%273%27 stroke-linecap=%27round%27/%3E%3Cpath d=%27M22 4v7h-7%27 fill=%27none%27 stroke=%27%2319324a%27 stroke-width=%273%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27/%3E%3C/svg%3E") 14 14, auto';
        }

        function updateActiveToolButton(activeButton) {
          document.querySelectorAll("#toolbar .tool-btn").forEach((btn) => {
            btn.classList.remove("btn-info", "active");
            btn.classList.add("btn-light");
          });
          if (activeButton) {
            activeButton.classList.remove("btn-light");
            activeButton.classList.add("btn-info", "active");
          } else {
            const selectBtn = document.querySelector('.tool-btn[data-tool="select"]');
            if (selectBtn) {
              selectBtn.classList.remove("btn-light");
              selectBtn.classList.add("btn-info", "active");
            }
          }
        }

        updateCursorState = function () {
          let cursorStyle = "default";
          if (currentTool !== "select") {
            cursorStyle = fabricCanvas.isDrawingMode ? "crosshair" : "crosshair";
          } else if (fabricCanvas.getActiveObject()) {
            cursorStyle = "default";
          }
          if (currentTool === "icon" && selectedIconSrc) {
            cursorStyle = "copy";
          }
          fabricCanvas.defaultCursor = cursorStyle;
          fabricCanvas.hoverCursor = currentTool === "select" ? "move" : cursorStyle;
        };

        updateControlsForSelection = function () {
          const activeObject = fabricCanvas.getActiveObject();
          if (activeObject) {
            if (activeObject.type === "activeSelection") {
              lineColorInput.value = currentColor;
              lineWidthInput.value = currentLineWidth;
              lineWidthValue.textContent = currentLineWidth;
              return;
            }
            let colorVal, widthVal;
            if (activeObject.type === "i-text" || activeObject.type === "textbox") {
              colorVal = activeObject.fill || currentColor;
              widthVal = currentLineWidth;
            } else {
              colorVal = activeObject.stroke || activeObject.fill || currentColor;
              if (activeObject.fill && activeObject.fill !== "transparent" && (!activeObject.stroke || activeObject.stroke === "transparent" || activeObject.strokeWidth === 0)) {
                colorVal = activeObject.fill;
              }
              widthVal = activeObject.strokeWidth || currentLineWidth;
            }
            lineColorInput.value = typeof colorVal === "string" && colorVal.startsWith("#") ? colorVal : currentColor;
            lineWidthInput.value = widthVal || currentLineWidth;
            lineWidthValue.textContent = lineWidthInput.value;
            if (["rect", "circle", "triangle"].includes(activeObject.type)) {
              shapeFillMode.value = activeObject.fill && activeObject.fill !== "transparent" ? "filled" : "outline";
            }
          } else {
            lineColorInput.value = currentColor;
            lineWidthInput.value = currentLineWidth;
            lineWidthValue.textContent = currentLineWidth;
          }
        };

        // --- MODIFIED: populateIconLibrary ---
        populateIconLibrary = function () {
            if (!iconLibraryContainer) return;
            iconLibraryContainer.innerHTML = ""; // Clear previous content
            // Removed text-align style here, added it to the #iconLibrary div in HTML

            if (!icons || icons.length === 0) {
                iconLibraryContainer.textContent = "No icons loaded or defined.";
                return;
            }

            icons.forEach((icon) => {
                if (typeof icon.name !== 'string' || typeof icon.src !== 'string') {
                    console.warn('Skipping invalid icon object:', icon);
                    return; // Skip this invalid icon
                }

                // 1. Create a container div for each icon+label (using CSS class now)
                const iconContainer = document.createElement("div");
                iconContainer.className = "icon-entry"; // Apply styles from CSS

                // 2. Create the image element
                const img = document.createElement("img");
                img.src = icon.src;
                img.alt = icon.name;
                // Removed className = "icon-preview img-fluid" -> styles are in .icon-entry img now

                // 3. Create the label element
                const label = document.createElement("div");
                label.textContent = icon.name;

                // 4. Append image and label to the container
                iconContainer.appendChild(img);
                iconContainer.appendChild(label);

                // 5. Add click listener to the container
                iconContainer.title = `Select ${icon.name}`; // Tooltip for the whole item
                iconContainer.addEventListener("click", () => {
                    selectedIconSrc = icon.src;
                    currentTool = "icon";
                    iconModal.hide();
                    setMobileToolbarOpen(false);
                    showResponse("warning",`Icon "${icon.name}" selected. Click on the canvas to place it.`);
                    setEditorHint(`Click once to place ${icon.name}`, "fa-icons");
                    updateCursorState();
                });

                // 6. Append the container to the main library container
                iconLibraryContainer.appendChild(iconContainer);
            });
        };
        // --- END MODIFICATION ---

        async function loadIconsAndSetup() {
            try {
                const response = await fetch('icons.json'); 
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status} - Could not load icons.json. Ensure the file exists and the path is correct.`);
                }
                const loadedIcons = await response.json();
                if (!Array.isArray(loadedIcons)) {
                    throw new Error('Invalid format: icons.json should contain an array of icon objects.');
                }
                icons = loadedIcons.filter(icon => {
                    const isValid = typeof icon.name === 'string' && typeof icon.src === 'string';
                    if (!isValid) {
                        console.warn('Filtering out invalid icon object:', icon);
                    }
                    return isValid;
                });
                console.log("Icons loaded successfully from icons.json:", icons);
            } catch (error) {
                console.error("Failed to load or parse icons.json:", error);
                icons = [
                    { name: "Default Smiley", src: "https://img.icons8.com/ios-filled/50/007bff/smiling.png" },
                    { name: "Default Star", src: "https://img.icons8.com/ios-filled/50/007bff/star.png" }
                ];
                showResponse("danger","Could not load custom icons from 'icons.json'. Using a default set. \nError: " + error.message);
            } finally {
                populateIconLibrary(); 
            }
        }

        resizeCanvas = function () {
          if (!fabricCanvas || !canvasContainer) return;
          const style = window.getComputedStyle(canvasContainer);
          const paddingX = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
          const paddingY = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
          let newWidth = canvasContainer.clientWidth - paddingX - 2;
          let newHeight = canvasContainer.clientHeight - paddingY - 2;
          newWidth = newWidth > 50 ? Math.floor(newWidth) : 300;
          newHeight = newHeight > 50 ? Math.floor(newHeight) : 200;
          fabricCanvas.setWidth(newWidth);
          fabricCanvas.setHeight(newHeight);
           fabricCanvas.calcOffset();
           updatePlacementGrid();
           fabricCanvas.renderAll();
        };

        function setTool(tool) {
          currentTool = tool;
          fabricCanvas.isDrawingMode = currentTool === "freehand";
          fabricCanvas.selection = currentTool === "select";
          fabricCanvas.discardActiveObject();

          if (fabricCanvas.isDrawingMode) {
            fabricCanvas.freeDrawingBrush.color = currentColor;
            fabricCanvas.freeDrawingBrush.width = currentLineWidth;
          }
          updateActiveToolButton(document.querySelector(`.tool-btn[data-tool="${tool}"]`));
          isDrawingShape = false;
          activeShapeBeingDrawn = null;
          updateCursorState();
          const hints = {
            select: ["Select an object to move, resize or layer it", "fa-mouse-pointer"],
            freehand: ["Draw freehand; choose Select when finished", "fa-pencil-alt"],
            line: ["Drag once to draw a line", "fa-minus"],
            rectangle: ["Drag once to draw a rectangle", "fa-square"],
            circle: ["Drag once to draw a circle", "fa-circle"],
            triangle: ["Drag once to draw a triangle", "fa-triangle"],
            text: ["Click once to place text", "fa-font"]
          };
          if (hints[tool]) setEditorHint(hints[tool][0], hints[tool][1]);
          fabricCanvas.renderAll();
        }

        function updateDrawingShape(sX, sY, eX, eY) {
          if (!activeShapeBeingDrawn) return;
          switch (currentTool) {
            case "line":
              activeShapeBeingDrawn.set({ x2: eX, y2: eY });
              break;
            case "rectangle":
              activeShapeBeingDrawn.set({
                left: Math.min(sX, eX),
                top: Math.min(sY, eY),
                width: Math.abs(eX - sX),
                height: Math.abs(eY - sY),
              });
              break;
            case "circle":
              const cdx = eX - sX;
              const cdy = eY - sY;
              const cRadius = Math.sqrt(cdx * cdx + cdy * cdy) / 2;
              activeShapeBeingDrawn.set({
                left: sX + cdx / 2,
                top: sY + cdy / 2,
                radius: cRadius > 0 ? cRadius : 0.1,
              });
              break;
            case "triangle":
              activeShapeBeingDrawn.set({
                left: Math.min(sX, eX),
                top: Math.min(sY, eY),
                width: Math.abs(eX - sX),
                height: Math.abs(eY - sY),
              });
              break;
          }
        }
        // Function to list templates in the modal
        async function listTemplates() {
            templateLibraryContainer.innerHTML = '<p>Loading templates...</p>'; // Show loading indicator
            try {
                const response = await fetch('list_templates.php'); // Fetch list from PHP
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const result = await response.json();

                if (result.success && Array.isArray(result.templates)) {
                    populateTemplateModal(result.templates);
                } else {
                    throw new Error(result.message || 'Failed to list templates.');
                }
            } catch (error) {
                console.error("Error listing templates:", error);
                templateLibraryContainer.innerHTML = `<p class="text-danger">Error loading templates: ${error.message}</p>`;
            }
        }

        // Function to populate the template modal body
        function populateTemplateModal(filenames) {
            templateLibraryContainer.innerHTML = ''; // Clear loading/error message
            if (filenames.length === 0) {
                 templateLibraryContainer.innerHTML = '<p>No templates found in the directory.</p>';
                 return;
            }

            filenames.forEach(filename => {
                const templateContainer = document.createElement("div");
                templateContainer.className = "template-entry";
                templateContainer.title = `Load ${filename}`;

                const icon = document.createElement("i");
                icon.className = "fad fa-file-code"; // Or fa-file-alt

                const label = document.createElement("div");
                label.textContent = filename.replace('.json', ''); // Display name without extension

                templateContainer.appendChild(icon);
                templateContainer.appendChild(label);

                templateContainer.addEventListener("click", () => {
                    loadTemplate(filename); // Call load function on click
                });

                templateLibraryContainer.appendChild(templateContainer);
            });
        }

        // Function to load a specific template
        async function loadTemplate(filename) {
             console.log(`Requesting to load: ${filename}`);
             try {
                 // Send filename via query parameter (adjust PHP if using POST)
                 const response = await fetch(`load_template.php?filename=${encodeURIComponent(filename)}`);
                 if (!response.ok) {
                     throw new Error(`HTTP error! status: ${response.status}`);
                 }
                 const result = await response.json();

                 if (result.success && result.data) {
                     fabricCanvas.loadFromJSON(result.data, () => {
                         fabricCanvas.renderAll();
                         templateLoadModal.hide(); // Close modal on success
                         showResponse("success",`Template "${filename}" loaded.`);
                         updateControlsForSelection();
                     });
                 } else {
                     throw new Error(result.message || 'Failed to load template data.');
                 }
             } catch (error) {
                 console.error("Error loading template:", error);
                showResponse("danger",`Error loading template "${filename}":\n${error.message}`);
             }
        }

        fabricCanvas.on("mouse:down", (options) => {
          const pointer = fabricCanvas.getPointer(options.e);
          if (!pointer) return;

          shapeStartX = pointer.x;
          shapeStartY = pointer.y;

          if (["line", "rectangle", "circle", "triangle"].includes(currentTool)) {
            isDrawingShape = true;
            fabricCanvas.selection = false;

            const initialProps = {
              stroke: currentColor,
              strokeWidth: currentLineWidth,
              originX: "left",
              originY: "top",
              noScaleCache: false,
              strokeUniform: true,
            };

            switch (currentTool) {
              case "line":
                activeShapeBeingDrawn = new fabric.Line([shapeStartX, shapeStartY, shapeStartX, shapeStartY], { ...initialProps, fill: undefined });
                break;
              case "rectangle":
                activeShapeBeingDrawn = new fabric.Rect({ ...initialProps, fill: shapeFillMode.value === "filled" ? currentColor : "transparent", left: shapeStartX, top: shapeStartY, width: 0, height: 0 });
                break;
              case "circle":
                activeShapeBeingDrawn = new fabric.Circle({ ...initialProps, fill: shapeFillMode.value === "filled" ? currentColor : "transparent", left: shapeStartX, top: shapeStartY, radius: 0.1, originX: "center", originY: "center" });
                break;
              case "triangle":
                activeShapeBeingDrawn = new fabric.Triangle({ ...initialProps, fill: shapeFillMode.value === "filled" ? currentColor : "transparent", left: shapeStartX, top: shapeStartY, width: 0, height: 0 });
                break;
            }
            if (activeShapeBeingDrawn) {
              fabricCanvas.add(activeShapeBeingDrawn);
            }
          } else if (currentTool === "text") {
            textPlacementPos = { x: shapeStartX, y: shapeStartY };
            textInput.value = "";
            textModal.show();
          } else if (currentTool === "icon" && selectedIconSrc) {
            const srcToLoad = selectedIconSrc;
            fabric.Image.fromURL(
              srcToLoad,
              (img) => {
                if (!img) {
                  showResponse("danger","Error: Could not load image.");
                  setTool("select");
                  return;
                }
                img.set({ left: shapeStartX, top: shapeStartY, originX: "center", originY: "center" }).scaleToWidth(50);
                fabricCanvas.add(img);
                fabricCanvas.setActiveObject(img);
                fabricCanvas.requestRenderAll();
                selectToolAfterPlacement();
              },
              { crossOrigin: "Anonymous" }
            );
          }
        });

        fabricCanvas.on("mouse:move", (options) => {
          if (!isDrawingShape || !activeShapeBeingDrawn) return;
          const pointer = fabricCanvas.getPointer(options.e);
          if (!pointer) return;
          updateDrawingShape(shapeStartX, shapeStartY, pointer.x, pointer.y);
          fabricCanvas.renderAll();
        });

        fabricCanvas.on("mouse:up", (options) => {
          if (isDrawingShape && activeShapeBeingDrawn) {
            const pointer = fabricCanvas.getPointer(options.e);
            if (pointer) {
              updateDrawingShape(shapeStartX, shapeStartY, pointer.x, pointer.y);
              const minSizeThreshold = 5;
              let isTooSmall = false;
              if (activeShapeBeingDrawn.width !== undefined && activeShapeBeingDrawn.height !== undefined) {
                if (Math.abs(activeShapeBeingDrawn.width) < minSizeThreshold && Math.abs(activeShapeBeingDrawn.height) < minSizeThreshold) {
                  if (currentTool !== "line") isTooSmall = true;
                }
              } else if (activeShapeBeingDrawn.radius !== undefined) {
                if (activeShapeBeingDrawn.radius * 2 < minSizeThreshold) isTooSmall = true;
              }
              if (isTooSmall || (Math.abs(pointer.x - shapeStartX) < minSizeThreshold && Math.abs(pointer.y - shapeStartY) < minSizeThreshold && currentTool !== "line") ) {
                fabricCanvas.remove(activeShapeBeingDrawn);
              } else {
                activeShapeBeingDrawn.setCoords();
                fabricCanvas.setActiveObject(activeShapeBeingDrawn);
              }
            } else {
              if (activeShapeBeingDrawn) fabricCanvas.remove(activeShapeBeingDrawn);
            }
            activeShapeBeingDrawn = null;
            if (currentTool !== "freehand") selectToolAfterPlacement();
          }
          isDrawingShape = false;
          fabricCanvas.selection = currentTool === "select";
          updateCursorState();
        });

        fabricCanvas.on("selection:created", updateControlsForSelection);
        fabricCanvas.on("selection:updated", updateControlsForSelection);
        fabricCanvas.on("selection:cleared", updateControlsForSelection);
        fabricCanvas.on("object:modified", (e) => {
          updateControlsForSelection();
        });

        toolbarElement.addEventListener("click", (e) => {
          const toolButton = e.target.closest(".tool-btn");
          if (toolButton) {
            setTool(toolButton.dataset.tool);
            setMobileToolbarOpen(false);
          }
        });

        mobileToolbarToggle.addEventListener("click", () => {
          setMobileToolbarOpen(!toolbarElement.classList.contains("is-open"));
        });
        mobileToolbarBackdrop.addEventListener("click", () => setMobileToolbarOpen(false));
        document.addEventListener("keydown", (event) => {
          if (event.key === "Escape") setMobileToolbarOpen(false);
        });

        lineColorInput.addEventListener("input", (e) => {
          currentColor = e.target.value;
          const activeObject = fabricCanvas.getActiveObject();
          const applyColor = (obj, colorVal) => {
            if (!obj) return;
            if (obj.type === "line" || obj.type === "path") { 
              obj.set("stroke", colorVal);
            } else if (obj.type === "i-text" || obj.type === "textbox") {
              obj.set("fill", colorVal);
            } else if (["rect", "circle", "triangle"].includes(obj.type)) {
              obj.set("stroke", colorVal);
              if (obj.fill && obj.fill !== "transparent") {
                obj.set("fill", colorVal);
              } else {
                obj.set("fill", "transparent");
              }
            }
          };
          if (activeObject) {
            if (activeObject.type === "activeSelection") activeObject.forEachObject((obj) => applyColor(obj, currentColor));
            else applyColor(activeObject, currentColor);
            fabricCanvas.renderAll();
          } else if (currentTool === "freehand") fabricCanvas.freeDrawingBrush.color = currentColor;
        });

        shapeFillMode.addEventListener("change", () => {
          const activeObject = fabricCanvas.getActiveObject();
          if (!activeObject) return;
          const applyFillMode = (obj) => {
            if (["rect", "circle", "triangle"].includes(obj.type)) {
              obj.set("fill", shapeFillMode.value === "filled" ? currentColor : "transparent");
            }
          };
          if (activeObject.type === "activeSelection") activeObject.forEachObject(applyFillMode);
          else applyFillMode(activeObject);
          fabricCanvas.requestRenderAll();
        });

        lineWidthInput.addEventListener("input", (e) => {
          currentLineWidth = parseInt(e.target.value, 10);
          lineWidthValue.textContent = currentLineWidth;
          const activeObject = fabricCanvas.getActiveObject();
          const applyWidth = (obj, width) => {
            if (!obj) return;
            if (["line", "path", "rect", "circle", "triangle"].includes(obj.type)) {
              obj.set("strokeWidth", width);
            }
          };
          if (activeObject) {
            if (activeObject.type === "activeSelection") activeObject.forEachObject((obj) => applyWidth(obj, currentLineWidth));
            else applyWidth(activeObject, currentLineWidth);
            fabricCanvas.renderAll();
          } else if (currentTool === "freehand") fabricCanvas.freeDrawingBrush.width = currentLineWidth;
        });

        clearCanvasBtn.addEventListener("click", () => {
          loadModalContent('<p class="mb-0">Remove every object from this canvas?</p>', 'imageEngineClearConfirm', 'modal-sm', 1080, 'true', 'Clear canvas', 'cancelConfirm', function() {
            killModal('imageEngineClearConfirm');
            fabricCanvas.clear();
            fabricCanvas.backgroundColor = "#ffffff";
            fabricCanvas.renderAll();
            selectToolAfterPlacement();
          });
        });

        toggleGridBtn.addEventListener("click", () => {
          placementGridVisible = !placementGridVisible;
          updatePlacementGrid();
        });

        deleteSelectedBtn.addEventListener("click", () => {
          const activeObjects = fabricCanvas.getActiveObjects();
          if (activeObjects.length > 0) {
            activeObjects.forEach((obj) => fabricCanvas.remove(obj));
            fabricCanvas.discardActiveObject().renderAll();
          } else {
           showResponse("warning","No object selected.");
          }
          updateCursorState();
        });

        bringForwardBtn.addEventListener("click", () => {
          const active = fabricCanvas.getActiveObject();
          if (!active) return showResponse("warning", "Select an object first.");
          fabricCanvas.bringForward(active);
          active.setCoords();
          fabricCanvas.requestRenderAll();
        });

        sendBackwardBtn.addEventListener("click", () => {
          const active = fabricCanvas.getActiveObject();
          if (!active) return showResponse("warning", "Select an object first.");
          fabricCanvas.sendBackwards(active);
          active.setCoords();
          fabricCanvas.requestRenderAll();
        });

        cloneSelectedBtn.addEventListener("click", () => {
          const active = fabricCanvas.getActiveObject();
          if (!active) return showResponse("warning", "Select an object first.");
          active.clone(function(clone) {
            clone.set({ left: (active.left || 0) + 18, top: (active.top || 0) + 18, evented: true });
            fabricCanvas.add(clone);
            fabricCanvas.setActiveObject(clone);
            clone.setCoords();
            fabricCanvas.requestRenderAll();
          });
        });

        document.addEventListener("keydown", (e) => {
          if (e.key === "Delete" || e.key === "Backspace") {
            const activeEl = document.activeElement;
            if (activeEl.tagName !== "INPUT" && activeEl.tagName !== "TEXTAREA" && !activeEl.isContentEditable) {
              e.preventDefault();
              deleteSelectedBtn.click();
            }
          }
        });

        async function saveCanvasImage(name) {
            const format = 'png'; // Options: 'png', 'jpeg', 'webp' etc. (ensure PHP handles extension)
            // Ensure it has a valid image extension (PHP will also check)
            if (!/\.(png|jpe?g|gif|webp)$/i.test(name)) {
               const defaultExt = (format === 'jpeg') ? 'jpg' : format;
               showResponse("warning",`Invalid or missing extension. Appending '.${defaultExt}'.`);
               name = name.replace(/\.$/, '') + `.${defaultExt}`; // Remove trailing dot if any
            }

            try {console.log("Canvas background color right before saving:", fabricCanvas.backgroundColor);
                // Generate the data URL from Fabric canvas
                const dataURL = fabricCanvas.toDataURL({
                     format: format, // Match the format chosen above
                     quality: 0.9, // Relevant for 'jpeg' format (0.1 to 1.0)
                     // multiplier: 1 // Use multiplier > 1 for higher resolution output
                });

                console.log(`Attempting to save image via PHP: ${name}`);

                // Send filename and data URL to the PHP script
                const response = await fetch('save_image.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ filename: name, imageDataUrl: dataURL }),
                });

                // Get the response body regardless of HTTP status
                const resultText = await response.text();
                let result = null;
                try {
                    result = JSON.parse(resultText); // Try to parse as JSON
                } catch(e) {
                    // If PHP had an error and didn't output JSON
                    console.error("Failed to parse server response:", resultText);
                    throw new Error(`Server error or invalid response: ${response.status} ${response.statusText}`);
                }


                // Check the HTTP status and the success flag from PHP
                if (!response.ok || !result.success) {
                    throw new Error(result.message || `Failed to save image on server (HTTP ${response.status})`);
                }

                // Success
                showResponse("success",result.message || `Image saved successfully as ${name} on server!`);
                // Optionally use result.filepath here if needed
                // console.log("Server filepath:", result.filepath);


            } catch (error) {
                 console.error("Error saving image via PHP:", error);
                 showResponse("danger",`Error saving image: ${error.message}`);
                 // You could add a fallback to client-side download here if needed
            }
        }

        saveAsImageBtn.addEventListener("click", () => {
          askForName("Save image", "Image filename", `drawing-${Date.now()}.png`, "Save", saveCanvasImage);
        });

        downloadImageBtn.addEventListener("click", () => {
          const anchor = document.createElement("a");
          anchor.download = `drawing-${Date.now()}.png`;
          anchor.href = fabricCanvas.toDataURL({ format: "png", multiplier: 2 });
          anchor.click();
        });

        async function saveCanvasTemplate(name) {
                 // Basic cleanup - remove extension if user added it, trim whitespace
                 name = name.replace(/\.json$/i, '').trim();
                 if (!name) {
                    showResponse("warning","Invalid template name.");
                     return;
                 }
                 // Ensure .json extension (PHP script also does this, but good practice here too)
                 const filename = name + '.json'; 

                try {
                    const json = fabricCanvas.toJSON(); // Get canvas data
                    const dataStr = JSON.stringify(json); // Convert to string

                    console.log(`Attempting to save template: ${filename}`); // Debug log

                    // Send data to PHP script
                    const response = await fetch('save_template.php', {
                        method: 'POST',
                        headers: {
                            // Indicate we're sending JSON in the body
                            'Content-Type': 'application/json', 
                        },
                        // Structure the body as expected by save_template.php
                        body: JSON.stringify({ filename: filename, data: dataStr }), 
                    });

                    // Check if the HTTP request itself was okay
                    if (!response.ok) {
                         throw new Error(`HTTP error! Status: ${response.status}`);
                    }

                    // Parse the JSON response from PHP
                    const result = await response.json(); 

                    // Check the 'success' flag set by PHP
                    if (result.success) {
                        showResponse("success",result.message || "Template saved successfully on server!");
                    } else {
                         // Throw an error with the message from PHP
                         throw new Error(result.message || "Failed to save template on server.");
                    }

                } catch (error) {
                     // Catch fetch errors or errors thrown from the response check
                     console.error("Error saving template via PHP:", error);
                    showResponse("danger",`Error saving template: ${error.message}`);
                }
        }

        saveAsTemplateBtn.addEventListener("click", () => {
          askForName("Save template", "Template name", "lev-template", "Save", saveCanvasTemplate);
        });

        // --- MODIFIED: Load Template Button Listener ---
        loadTemplateBtn.addEventListener('click', () => {
            listTemplates(); // Call function to fetch list and populate modal
            templateLoadModal.show(); // Show the modal
        });

        addTextBtn.addEventListener("click", () => {
          const textVal = textInput.value.trim();
          if (textVal && textPlacementPos) {
            const fontSize = Math.max(12, currentLineWidth * 2 + 10);
            const textObject = new fabric.IText(textVal, {
              left: textPlacementPos.x,
              top: textPlacementPos.y,
              originX: "center",
              originY: "center",
              fill: currentColor,
              fontSize: fontSize,
              fontFamily: "Arial",
              padding: 5,
            });
            fabricCanvas.add(textObject);
            fabricCanvas.setActiveObject(textObject);
            textModal.hide();
            try {
              setTimeout(() => canvasElement.focus(), 0);
            } catch (focusErr) {}
            textPlacementPos = null;
            textInput.value = "";
            setTool("select");
          } else if (!textPlacementPos) {
            showResponse("warning","Click on the canvas where you want to place the text first.");
            textModal.hide();
          } else {
            showResponse("warning","Please enter some text.");
          }
        });

        fullscreenBtn.addEventListener("click", () => {
          const container = document.getElementById("drawingAppContainer");
          if (!document.fullscreenElement) {
            container.requestFullscreen().catch((err) => showResponse("danger",`Fullscreen error: ${err.message}`));
          } else {
            if (document.exitFullscreen) document.exitFullscreen();
          }
        });

        document.addEventListener("fullscreenchange", () => {
          const icon = fullscreenBtn.querySelector("i");
          if (icon) icon.className = document.fullscreenElement ? "fad fa-compress" : "fad fa-expand";
          setTimeout(resizeCanvas, 150);
        });

        await loadIconsAndSetup(); 

        updateActiveToolButton(document.querySelector('.tool-btn[data-tool="select"]'));
        updateCursorState();
        textModalElement.addEventListener('hidden.mdb.modal', () => {
          if (textPlacementPos) {
            textPlacementPos = null;
            selectToolAfterPlacement();
          }
        });

        setTimeout(() => {
          resizeCanvas();
        }, 100);
        window.addEventListener("resize", resizeCanvas);
      });
    </script>
  </body>
</html>
