<div class="card-body">
  <div class="row">
    <!-- English Announcement Name Input -->
    <div class="col-sm-6 col-md-6">
      <div class="form-group mb-3">
        <label class="form-label" for="announcement_en">
          <%= trans.cruds.ANNOUNCEMENT.fields.title_en %> <span class="text-danger">*</span>
        </label>
        <input
          class="form-control"
          type="text"
          id="announcement_en"
          name="title_en"
          value="<%= announcement?.title?.en || '' %>"
          placeholder="<%= trans.global.enter_your %> <%= trans.cruds.ANNOUNCEMENT.fields.title_en %>"
        />
      </div>
    </div>

    <!-- Arabic Announcement Name Input -->
    <div class="col-sm-6 col-md-6">
      <div class="form-group mb-3">
        <label class="form-label" for="announcement_ar">
          <%= trans.cruds.ANNOUNCEMENT.fields.title_ar %> <span class="text-danger">*</span>
        </label>
        <input
          class="form-control"
          type="text"
          id="announcement_ar"
          name="title_ar"
          value="<%= announcement?.title?.ar || '' %>"
          placeholder="<%= trans.global.enter_your %> <%= trans.cruds.ANNOUNCEMENT.fields.title_ar %>"
        />
      </div>
    </div>

    <div class="col-sm-6 col-md-6">
      <div class="form-group mb-3">
        <label class="form-label" for="announcement-duration">
          <%= trans.cruds.ANNOUNCEMENT.fields.announcementDuration %>
        </label>
        <select name="durationType" id="announcement-duration" class="form-control">
          <option value="single" <%= (announcement?.durationType === 'single' || !announcement) ? 'selected' : '' %>>
            <%= trans.cruds.ANNOUNCEMENT.fields.oneDay %>
          </option>
          <option value="multiple" <%= announcement?.durationType === 'multiple' ? 'selected' : '' %>>
            <%= trans.cruds.ANNOUNCEMENT.fields.multipleDays %>
          </option>
        </select>
      </div>
    </div>



    <div class="col-sm-6 col-md-6">
      <div class="form-group mb-3">
        <label  class="form-label" for="range-date"><%= trans.cruds.ANNOUNCEMENT.fields.choose_date %></label>
        <div class="input-group flatpicker-calender">
          <input type="text" name="date-format" class="form-control flatpickr-input" id="range-date" value="<%= announcement?.durationType === 'single' ? announcement.start_date.toISOString().split('T')[0] : announcement.dateRange %>" readonly="readonly">        
        </div>
      </div>
    </div>

    <!-- Frequency -->
    <!-- <div class="col-sm-6 col-md-6">
      <div class="form-group mb-3">
        <label class="form-label" for="frequency_period"><%= trans.cruds.ANNOUNCEMENT.fields.frequency_period || 'Frequency Period' %></label>
        <select name="frequency_period" id="frequency_period" class="form-control">
          <option value="daily" <%= announcement?.frequency?.period === 'daily' ? 'selected' : '' %>>Daily</option>
          <option value="weekly" <%= announcement?.frequency?.period === 'weekly' ? 'selected' : '' %>>Weekly</option>
          <option value="monthly" <%= announcement?.frequency?.period === 'monthly' ? 'selected' : '' %>>Monthly</option>
        </select>
      </div>
    </div> -->

    <div class="col-sm-6 col-md-6">
      <div class="form-group mb-3">
        <label class="form-label" for="frequency_count"><%= trans.cruds.ANNOUNCEMENT.fields.frequency_count || 'Frequency Count' %></label>
        <input
          type="number"
          class="form-control"
          id="frequency_count"
          name="frequency_count"
          value="<%= announcement?.frequency?.count || 1 %>"
          min="1"
        />
      </div>
    </div>

    <!-- Hidden inputs for deleted files -->
    <input type="hidden" id="deleted_en_files" name="deleted_en_files" value="">
    <input type="hidden" id="deleted_ar_files" name="deleted_ar_files" value="">

    <!-- English Banner -->
    <div class="col-sm-6 col-md-6">
      <div class="d-flex gap-3 align-items-center">
        <div class="flex-grow-1">
          <div class="form-group mb-3">
            <label class="form-label" for="announcement_banner_en">
              <%= trans.cruds.ANNOUNCEMENT.fields.banner +' ('+ trans.global.english +')' %>
            </label>
            <input class="form-control" id="announcement_banner_en" type="file" name="banner_en" 
              accept=".jpeg,.jpg,.png,.gif,.mp4,.mkv,.avi,.mov,.webm" onchange="previewFiles(this, 'banner_preview_en')"
            multiple/>
          </div>
        </div>
        <!-- SINGLE CHECKBOX TO SHOW/HIDE ARABIC BANNER -->
        <div class="copy-image-upload checkmark-box copy-btn" title="Same image for Arabic">
          <input 
            class="form-check-input primary" 
            id="sameAsClone" 
            name="sameAsClone" 
            type="checkbox" 
            data-type="checkboximage" 
            checked
            onclick="toggleArabicBanner(this)"
          >
        </div>
      </div>
      <div id="banner_preview_en" class="d-flex flex-wrap gap-2">
        <% if (announcement?.announcement_banner_en?.length) { %>
          <% announcement.announcement_banner_en.forEach(file => { %>
            <div class="preview-item position-relative" data-file-id="<%= file._id %>">
              <% if (file.file_type?.startsWith('image/')) { %>
                <img 
                  class="img-100 image-preview-item" 
                  alt="English Banner" 
                  src="<%= file.file_path ? '/' + file.file_path.replace('public/', '') : '/backend/images/dummy-image.jpg' %>"
                />
              <% } else if (file.file_type?.startsWith('video/')) { %>
                <video class="img-100 image-preview-item" controls>
                  <source src="<%= file.file_path ? '/' + file.file_path.replace('public/', '') : '#' %>" type="<%= file.file_type %>">
                </video>
              <% } %>
              <button type="button" class="btn btn-danger btn-sm position-absolute top-0 end-0 m-1" 
                      onclick="removeExistingFile(this, 'en', '<%= file._id %>')" title="Remove">
                <i class="fas fa-times"></i>
              </button>
            </div>
          <% }) %>
        <% } else { %>
          <img class="img-100 default-placeholder" alt="No files" src="/backend/images/dummy-image.jpg" />
        <% } %>
      </div>
    </div>

    <!-- Arabic Banner (Initially Hidden) -->
    <div class="col-sm-6 col-md-6" id="arabic_banner_section" style="display:none;">
      <div class="d-flex gap-5 align-items-center">
        <div class="flex-grow-1">
          <div class="form-group mb-3">
            <label class="form-label" for="announcement_banner_ar">
              <%= trans.cruds.ANNOUNCEMENT.fields.banner +' ('+ trans.global.arabic +')' %>
            </label>
            <input class="form-control" id="announcement_banner_ar" type="file" name="banner_ar" multiple accept=".jpeg,.jpg,.png,.gif,.mp4,.mkv,.avi,.mov,.webm" onchange="previewFiles(this, 'banner_preview_ar')"/>
          </div>
        </div>

      </div>
      <div id="banner_preview_ar" class="d-flex flex-wrap gap-2">
        <% if (announcement?.announcement_banner_ar?.length) { %>
          <% announcement.announcement_banner_ar.forEach(file => { %>
            <div class="preview-item position-relative" data-file-id="<%= file._id %>">
              <% if (file.file_type?.startsWith('image/')) { %>
                <img 
                  class="img-100 image-preview-item"  
                  alt="Arabic Banner" 
                  src="<%= file.file_path ? '/' + file.file_path.replace('public/', '') : '/backend/images/dummy-image.jpg' %>"
                />
              <% } else if (file.file_type?.startsWith('video/')) { %>
                <video class="img-100 image-preview-item" controls>
                  <source src="<%= file.file_path ? '/' + file.file_path.replace('public/', '') : '#' %>" type="<%= file.file_type %>">
                </video>
              <% } %>
              <button type="button" class="btn btn-danger btn-sm position-absolute top-0 end-0 m-1" 
                      onclick="removeExistingFile(this, 'ar', '<%= file._id %>')" title="Remove">
                <i class="fas fa-times"></i>
              </button>
            </div>
          <% }) %>
        <% } else { %>
          <img class="img-100 default-placeholder" alt="Arabic Banner" src="/backend/images/dummy-image.jpg" />
        <% } %>
      </div>
    </div>

    <!-- Description (English) -->
    <div class="col-md-12">
      <div class="form-group mb-3">
        <label class="form-label" for="description_en">
          <%= trans.cruds.ANNOUNCEMENT.fields.description_en %>
        </label>
        <div class="input-group">
          <div class="description_editor richtexteditor" id="description_en">
            <%- announcement?.description?.en || '' %>
          </div>
        </div>
      </div>
    </div>

    <!-- Description (Arabic) -->
    <div class="col-md-12">
      <div class="form-group mb-3">
        <label class="form-label" for="description_ar">
          <%= trans.cruds.ANNOUNCEMENT.fields.description_ar %>
        </label>
        <div class="input-group">
          <div class="description_editor1 richtexteditor" id="description_ar">
            <%- announcement?.description?.ar || '' %>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
    window.bannerEnFiles = [];
    window.bannerArFiles = [];
    window.deletedEnFiles = [];
    window.deletedArFiles = [];

    window.previewFiles = function(input, previewContainerId) {
        const container = document.getElementById(previewContainerId);
        const maxSize = 100 * 1024 * 1024;
        const maxFiles = 100;

        const allowedImageTypes = ['image/jpeg','image/jpg','image/png','image/gif'];
        const allowedVideoTypes = ['video/mp4','video/mkv','video/avi','video/mov','video/webm'];

        const isEnglish = input.id === "announcement_banner_en";
        const isArabic  = input.id === "announcement_banner_ar";
        const checkbox  = document.getElementById("sameAsClone");

        let targetFiles = isEnglish ? window.bannerEnFiles : window.bannerArFiles;
        const newFiles = Array.from(input.files);

        $(`#${input.id}_error`).remove();

        for (const file of newFiles) {
            const type = file.type.split('/')[0];

            if (type === "image" && !allowedImageTypes.includes(file.type)) {
                window.showError(input, "Invalid image format");
                return;
            }
            if (type === "video" && !allowedVideoTypes.includes(file.type)) {
                window.showError(input, "Invalid video format");
                return;
            }
            if (file.size > maxSize) {
                window.showError(input, "File must be under 5MB");
                return;
            }
        }

        const defaultPlaceholder = container.querySelector('.default-placeholder');
        if (defaultPlaceholder) {
            defaultPlaceholder.remove();
        }

        targetFiles.push(...newFiles);

        const dataTransfer = new DataTransfer();
        targetFiles.forEach(f => dataTransfer.items.add(f));
        input.files = dataTransfer.files;

        newFiles.forEach(file => {
            const previewItem = document.createElement('div');
            previewItem.className = 'preview-item position-relative';
            
            let el;
            const type = file.type.split('/')[0];

            if (type === "image") {
                el = document.createElement("img");
                el.src = URL.createObjectURL(file);
                el.className = "img-100";
            } else {
                el = document.createElement("video");
                el.src = URL.createObjectURL(file);
                el.controls = true;
                el.className = "img-100";
            }
            
            previewItem.appendChild(el);
            
            const removeBtn = document.createElement('button');
            removeBtn.type = 'button';
            removeBtn.className = 'btn btn-danger btn-sm position-absolute top-0 end-0 m-1';
            removeBtn.innerHTML = '<i class="fas fa-times"></i>';
            removeBtn.title = 'Remove';
            removeBtn.onclick = function() {
                window.removeNewFile(this, isEnglish ? 'en' : 'ar', file);
            };
            previewItem.appendChild(removeBtn);
            
            container.appendChild(previewItem);
        });

        if (checkbox && checkbox.checked && isEnglish) {
            window.syncArabic(); 
        }
    };
    
    window.removeNewFile = function(button, type, fileToRemove) {
        const containerId = type === 'en' ? 'banner_preview_en' : 'banner_preview_ar';
        const container = document.getElementById(containerId);
        const targetFiles = type === 'en' ? window.bannerEnFiles : window.bannerArFiles;
        const inputId = type === 'en' ? 'announcement_banner_en' : 'announcement_banner_ar';
        const input = document.getElementById(inputId);
        
        const fileIndex = targetFiles.findIndex(f => f === fileToRemove);
        if (fileIndex > -1) {
            targetFiles.splice(fileIndex, 1);
        }
        
        const dataTransfer = new DataTransfer();
        targetFiles.forEach(f => dataTransfer.items.add(f));
        input.files = dataTransfer.files;
        
        button.parentElement.remove();
        
        if (container.children.length === 0) {
            const defaultImg = document.createElement('img');
            defaultImg.className = 'img-100 default-placeholder';
            defaultImg.alt = 'No files';
            defaultImg.src = '/backend/images/dummy-image.jpg';
            container.appendChild(defaultImg);
        }
        
        const checkbox = document.getElementById("sameAsClone");
        if (checkbox && checkbox.checked && type === 'en') {
            window.syncArabic();
        }
    };
    
    window.removeExistingFile = function(button, type, fileId) {
        const containerId = type === 'en' ? 'banner_preview_en' : 'banner_preview_ar';
        const container = document.getElementById(containerId);
        
        if (type === 'en') {
            window.deletedEnFiles.push(fileId);
            document.getElementById('deleted_en_files').value = window.deletedEnFiles.join(',');
        } else {
            window.deletedArFiles.push(fileId);
            document.getElementById('deleted_ar_files').value = window.deletedArFiles.join(',');
        }
        
        button.parentElement.remove();
        
        if (container.children.length === 0) {
            const defaultImg = document.createElement('img');
            defaultImg.className = 'img-100 default-placeholder';
            defaultImg.alt = 'No files';
            defaultImg.src = '/backend/images/dummy-image.jpg';
            container.appendChild(defaultImg);
        }
        
        const checkbox = document.getElementById("sameAsClone");
        if (checkbox && checkbox.checked && type === 'en') {
            window.syncArabic();
        }
    };

    window.showError = function(input, msg) {
        const errorHtml = `<span id="${input.id}_error" class="error invalid-feedback d-block">${msg}</span>`;
        $(input).after(errorHtml);
        input.value = "";
    };

    window.toggleArabicBanner = function(checkbox) {
        const arSection = document.getElementById("arabic_banner_section");
        const arInput   = document.getElementById("announcement_banner_ar");
        const arPreview = document.getElementById("banner_preview_ar");
        
        if (checkbox.checked) {
            arSection.style.display = "none";
            window.bannerArFiles = [...window.bannerEnFiles];
            window.syncArabic();
        } else {
            arSection.style.display = "block";
            arInput.value = "";
        }
    };

    window.syncArabic = function () {
      const checkbox = document.getElementById("sameAsClone");
      if (!checkbox || !checkbox.checked) return;

      const enPreview = document.getElementById("banner_preview_en");
      const arPreview = document.getElementById("banner_preview_ar");

      arPreview.innerHTML = "";

      const enItems = enPreview.querySelectorAll(".preview-item");

      if (enItems.length === 0) {
          arPreview.innerHTML =
              '<img class="img-100 default-placeholder" alt="Arabic Banner" src="/backend/images/dummy-image.jpg" />';
          return;
      }

      enItems.forEach(item => {
          const wrapper = document.createElement("div");
          wrapper.className = "preview-item position-relative";

          const media = item.querySelector("img, video").cloneNode(true);
          wrapper.appendChild(media);

          const removeBtn = document.createElement("button");
          removeBtn.type = "button";
          removeBtn.className = "btn btn-danger btn-sm position-absolute top-0 end-0 m-1";
          removeBtn.innerHTML = '<i class="fas fa-times"></i>';
          removeBtn.onclick = function () {
              item.querySelector("button")?.click();
          };

          wrapper.appendChild(removeBtn);
          arPreview.appendChild(wrapper);
      });
  };
</script>