<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <title>Update Thyme Crunch Recipe</title>
    <link rel="stylesheet" th:href="@{/css/create-recipe.css}">
    <link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
	<script th:src="@{/js/bad-words-list.js}"></script>
</head>
<body>

<div class="header-wrap">
<a th:href="@{/explore}">
<header class="top-header">
    <img th:src="@{/images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
    <h1 class="site-name">
    Thyme Crunch
    </h1>
    <img th:src="@{/images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
</header>
</a>
</div>

<div class="form-wrap">
<div class="form-split">

  <!-- Main Content -->
  <div class="form-section">
    <div class="section-title">Update Recipe</div>

    <div class="field">
      <label for="title">Title <span class="required">*</span></label>
      <input type="text" id="title" placeholder="Your recipe title...">
    </div>

    <div class="field">
      <label for="desc">Description <span class="required">*</span></label>
      <textarea id="desc" rows="3" placeholder="Briefly describe your recipe. Who or where is it from?"></textarea>
    </div>

    <div class="field">
      <label>Ingredients <span class="required">*</span></label>
      <div id="ingredients-container"></div>
      <button class="btn-add" id="add-ingredient-btn" type="button">+ Add ingredient</button>
    </div>

    <div class="field">
      <label>Instructions <span class="required">*</span></label>
      <div id="steps-container"></div>
      <button class="btn-add" id="add-step-btn" type="button">+ Add step</button>
    </div>
  </div>

  <!-- Cover image / Right -->
  <div class="form-section">
    <div class="field">
      <div class="image-drop" id="drop-zone">
        <p class="upload-title">Click to upload or drag and drop an image.</p>
      </div>
      <div class="image-preview" id="preview" style="display: none;">
        <img id="preview-img" src="" alt="Cover preview">
        <button class="remove-img" id="remove-img-btn" type="button">Remove</button>
      </div>
      <input type="file" id="img-input" accept="image/*" style="display: none;">
    </div>

    <div class="field">
      <label for="prep">Preparation Time: <span class="required">*</span></label>
      <input type="text" id="prep" placeholder="0">
    </div>

    <div class="field">
      <label for="cooking">Cooking Time: <span class="required">*</span></label>
      <input type="text" id="cooking" placeholder="0">
    </div>

    <div class="field">
      <label for="servings">Servings: <span class="required">*</span></label>
      <input type="text" id="servings" placeholder="0">
    </div>

    <div class="field">
      <div class="field">
      <label>Estimated Cost: <span class="required">*</span></label>
  		<div class="cost-selector" id="cost-selector">
    	<span class="dollar" data-value="1">$</span>
    	<span class="dollar" data-value="2">$</span>
    	<span class="dollar" data-value="3">$</span>
    	<span class="dollar" data-value="4">$</span>
  	 </div>
  	 <input type="hidden" id="cost" value="0">
    </div>
  </div>
</div>

  <!-- Tags -->
  <div class="form-section">
    <div class="field">
      <label>Tags</label>
      <div class="tag-input-row">
        <input type="text" id="tag-input" placeholder="Type in a tag and click Add">
        <button class="btn" id="add-tag-btn" type="button">Add</button>
      </div>
      <div class="tag-wrap" id="tag-wrap"></div>
    </div>
  </div>

  <div id="form-message" class="form-message" style="display:none;"></div>

  <div class="actions">
    <button class="btn-create" id="publish-btn" type="button">UPDATE</button>
    <button class="btn-delete" id="delete-btn" type="button"><i class="fa fa-trash"></i></button>
  </div>
</div>

<script th:inline="javascript">
    const existingRecipe = /*[[${recipe}]]*/ null;
</script>

<script>
// ---- DOM refs ----

function isProfane(str) {
  const lower = str.toLowerCase().trim();
  return bannedWords.some(word => new RegExp(`\\b${word}\\b`).test(lower));
}


const ingredientContainer = document.getElementById('ingredients-container');
const stepsContainer = document.getElementById('steps-container');
const dropZone = document.getElementById('drop-zone');
const imgInput = document.getElementById('img-input');
const previewImg = document.getElementById('preview-img');
const previewBox = document.getElementById('preview');
const tags = [];
let imageRemoved = false;

// ---- Ingredients ----
document.getElementById('add-ingredient-btn').addEventListener('click', function (e) {
  e.preventDefault();
  addIngredient();
});

function addIngredient(data = {}) {
  const row = document.createElement('div');
  row.className = 'dynamic-row';
  row.innerHTML = `
    <input type="text" class="ing-name" placeholder="Ingredient (e.g. Sugar)" value="${escapeHtml(data.ingredientName || '')}">
    <input type="text" class="ing-qty" placeholder="Qty (e.g. 3)" value="${data.quantity ?? ''}">
    <input type="text" class="ing-unit" placeholder="Unit (e.g. tbsp)" value="${escapeHtml(data.unit || '')}">
    <input type="text" class="ing-notes" placeholder="Notes (optional)" value="${escapeHtml(data.notes || '')}">
    <button class="btn-remove" title="Remove" type="button">✕</button>`;
  row.querySelector('.btn-remove').addEventListener('click', function (e) {
    e.preventDefault();
    row.remove();
  });
  ingredientContainer.appendChild(row);
}

// ---- Steps ----
document.getElementById('add-step-btn').addEventListener('click', function (e) {
  e.preventDefault();
  addStep();
});

function addStep(data = {}) {
  const row = document.createElement('div');
  row.className = 'dynamic-row';
  row.innerHTML = `
    <div class="step-bubble">?</div>
    <textarea placeholder="Describe this step...">${escapeHtml(data.instruction || '')}</textarea>
    <button class="btn-remove" title="Remove" type="button">✕</button>
  `;
  row.querySelector('.btn-remove').addEventListener('click', function (e) {
    e.preventDefault();
    row.remove();
    renumberSteps();
  });
  stepsContainer.appendChild(row);
  renumberSteps();
}

function renumberSteps() {
  stepsContainer.querySelectorAll('.step-bubble').forEach((bubble, i) => {
    bubble.textContent = i + 1;
  });
}

// ---- Image upload preview ----
dropZone.addEventListener('click', () => imgInput.click());

imgInput.addEventListener('change', function () {
  if (!this.files || !this.files[0]) return;

  imageRemoved = false;

  const url = URL.createObjectURL(this.files[0]);
  previewImg.src = url;
  dropZone.style.display = 'none';
  previewBox.style.display = 'block';
});

document.getElementById('remove-img-btn').addEventListener('click', function (e) {
  e.preventDefault();
  imgInput.value = '';
  previewImg.src = '';
  previewBox.style.display = 'none';
  dropZone.style.display = 'block';
  imageRemoved = true;
});

// ---- Cost display ----
const dollars = document.querySelectorAll('.dollar');

dollars.forEach(dollar => {
  dollar.addEventListener('click', () => {
    const val = parseInt(dollar.dataset.value);
    document.getElementById('cost').value = val;
    dollars.forEach(d => {
      d.classList.toggle('active', parseInt(d.dataset.value) <= val);
    });
    clearError(document.getElementById('cost-selector'));
  });

  dollar.addEventListener('mouseover', () => {
    const val = parseInt(dollar.dataset.value);
    dollars.forEach(d => {
      d.classList.toggle('active', parseInt(d.dataset.value) <= val);
    });
  });

  dollar.addEventListener('mouseout', () => {
    const selected = parseInt(document.getElementById('cost').value);
    dollars.forEach(d => {
      d.classList.toggle('active', parseInt(d.dataset.value) <= selected);
    });
  });
});


// ---- Tags ----
document.getElementById('tag-input').addEventListener('keydown', function (e) {
  if (e.key === 'Enter') {
    e.preventDefault();
    addTag();
  }
});

document.getElementById('add-tag-btn').addEventListener('click', function (e) {
  e.preventDefault();
  addTag();
});

function addTag() {
	  const input = document.getElementById('tag-input');
	  const val = input.value.trim().toLowerCase().replace(/\s+/g, '-');
	  if (!val || tags.includes(val) || isProfane(val)) {
		    input.value = '';
		    return;
		  }
	  tags.push(val);
	  input.value = '';
	  renderTags();
	}

function removeTag(t) {
  tags.splice(tags.indexOf(t), 1);
  renderTags();
}

function renderTags() {
  document.getElementById('tag-wrap').innerHTML = tags
    .map(t => `<div class="tag">${escapeHtml(t)} <span class="remove-tag" data-tag="${escapeHtml(t)}">✕</span></div>`)
    .join('');

  document.querySelectorAll('.remove-tag').forEach(btn => {
    btn.addEventListener('click', () => removeTag(btn.dataset.tag));
  });
}

// ---- Helpers ----
function escapeHtml(str) {
  return String(str ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function showMessage(message, isError = false) {
  const box = document.getElementById('form-message');
  box.textContent = message;
  box.style.display = 'block';
  box.style.backgroundColor = isError ? '#ffd7d7' : '#dff5dd';
  box.style.color = isError ? '#7a0000' : '#1f5c2c';
  box.style.border = isError ? '1px solid #d88' : '1px solid #8bc48b';
  box.style.padding = '12px';
  box.style.marginTop = '20px';
  box.style.borderRadius = '8px';
}

function showSuccessAndRedirect(message) {
  showMessage(message, false);
  setTimeout(() => {
    window.location.href = '/explore';
  }, 1500);
}

function fillRecipeForm(recipe) {
  if (!recipe) return;

  document.getElementById('title').value = recipe.title || '';
  document.getElementById('desc').value = recipe.description || '';
  document.getElementById('prep').value = recipe.prepTimeMinutes ?? '';
  document.getElementById('cooking').value = recipe.cookTimeMinutes ?? '';
  document.getElementById('servings').value = recipe.servings ?? '';
  document.getElementById('cost').value = recipe.cost ?? '';

  ingredientContainer.innerHTML = '';
  if (recipe.ingredients && recipe.ingredients.length > 0) {
    recipe.ingredients.forEach(item => addIngredient(item));
  } else {
    addIngredient();
  }

  stepsContainer.innerHTML = '';
  if (recipe.steps && recipe.steps.length > 0) {
    recipe.steps.forEach(step => addStep(step));
  } else {
    addStep();
  }

  if (recipe.tags && recipe.tags.length > 0) {
    recipe.tags.forEach(tag => {
      if (tag.name && !tags.includes(tag.name.toLowerCase())) {
        tags.push(tag.name.toLowerCase());
      }
    });
    renderTags();
  }

  imageRemoved = false;

  if (recipe.images && recipe.images.length > 0 && recipe.images[0].imageUrl) {
    previewImg.src = recipe.images[0].imageUrl;
    dropZone.style.display = 'none';
    previewBox.style.display = 'block';
  } else {
    previewImg.src = '';
    previewBox.style.display = 'none';
    dropZone.style.display = 'block';
  }
}

// ---- Inline validation ----
function showError(input, message) {
  input.classList.add('invalid');

  let error = input.parentElement.querySelector('.error-message');
  if (!error) {
    error = document.createElement('p');
    error.className = 'error-message';
    error.style.color = 'red';
    error.style.fontSize = '0.9em';
    error.style.marginTop = '6px';
    input.parentElement.appendChild(error);
  }

  error.textContent = message;
}

function clearError(input) {
  input.classList.remove('invalid');
  const error = input.parentElement.querySelector('.error-message');
  if (error) error.remove();
}

function validateForm() {
  let valid = true;

  const title = document.getElementById('title');
  const desc = document.getElementById('desc');
  const prep = document.getElementById('prep');
  const cooking = document.getElementById('cooking');
  const servings = document.getElementById('servings');
  const cost = document.getElementById('cost');

  [title, desc, prep, cooking, servings, cost].forEach(clearError);

  if (!title.value.trim()) {
    showError(title, 'Title is required');
    valid = false;
  }
  
  if (isProfane(title.value)) {
	    showError(title, 'Title contains inappropriate language');
	    valid = false;
  }

  if (!desc.value.trim()) {
    showError(desc, 'Description is required');
    valid = false;
  }
  
  if (isProfane(desc.value)) {
	    showError(desc, 'Description contains inappropriate language');
	    valid = false;
}


  if (!prep.value.trim() || isNaN(Number(prep.value)) || Number(prep.value) <= 0) {
    showError(prep, 'Enter a valid prep time');
    valid = false;
  }

  if (!cooking.value.trim() || isNaN(Number(cooking.value)) || Number(cooking.value) <= 0) {
    showError(cooking, 'Enter a valid cook time');
    valid = false;
  }

  if (!servings.value.trim() || isNaN(Number(servings.value)) || Number(servings.value) <= 0) {
    showError(servings, 'Enter valid servings');
    valid = false;
  }

  if (!cost.value.trim() || isNaN(Number(cost.value)) || Number(cost.value) <= 0) {
    showError(cost, 'Enter a valid cost');
    valid = false;
  }

  const ingredientRows = [...document.querySelectorAll('#ingredients-container .dynamic-row')];
  const hasIngredient = ingredientRows.some(row => row.querySelector('.ing-name').value.trim() !== '');
  const filledIngredientRows = ingredientRows.filter(row => row.querySelector('.ing-name').value.trim() !== '');
  if (!hasIngredient && ingredientRows.length > 0) {
    showError(ingredientRows[0].querySelector('.ing-name'), 'Add at least one ingredient');
    valid = false;
  }
  
  filledIngredientRows.forEach(row => {
	    const nameInput = row.querySelector('.ing-name');
	    const qtyInput = row.querySelector('.ing-qty');
	    const unitInput = row.querySelector('.ing-unit');
	    const noteInput = row.querySelector('.ing-notes');
	    

	    clearError(nameInput);
	    clearError(qtyInput);

	    if (!nameInput.value.trim()) {
	      showError(nameInput, 'Ingredient name is required');
	      valid = false;
	    }
	    
	    if (isProfane(nameInput.value.trim())) {
		    showError(nameInput, 'Ingredient name contains inappropriate language');
		    valid = false;
	   }
	    
	    if (isProfane(unitInput.value.trim())) {
		    showError(noteInput, 'Ingredient unit contains inappropriate language');
		    valid = false;
	   }
	    
	    if (isProfane(noteInput.value.trim())) {
		    showError(noteInput, 'Ingredient note contains inappropriate language');
		    valid = false;
	   }

	    const qtyVal = qtyInput.value.trim();
	    if (!isValidQuantity(qtyVal)) {
	      showError(qtyInput, 'Enter a valid quantity (e.g. 2, 1.5, 1/2, 1 1/2) or leave blank');
	      valid = false;
	    }
	  });
  
  function isValidQuantity(val) {
	  const cleaned = String(val ?? '').replace(/\s+/g, ' ').trim();

	  if (cleaned === '') return true;

	  if (/^\d+(\.\d+)?$/.test(cleaned)) {
	    return true;
	  }

	  if (/^\d+\/\d+$/.test(cleaned)) {
	    const [numerator, denominator] = cleaned.split('/');
	    return Number(numerator) >= 0 && Number(denominator) > 0;
	  }

	  if (/^\d+\s\d+\/\d+$/.test(cleaned)) {
	    const [whole, fraction] = cleaned.split(' ');
	    const [numerator, denominator] = fraction.split('/');
	    return Number(whole) >= 0 && Number(numerator) >= 0 && Number(denominator) > 0;
	  }

	  return false;
	}

  const stepAreas = [...document.querySelectorAll('#steps-container textarea')];
  const filledSteps = stepAreas.filter(textarea => textarea.value.trim() !== '');
  const hasStep = stepAreas.some(textarea => textarea.value.trim() !== '');
  if (!hasStep && stepAreas.length > 0) {
    showError(stepAreas[0], 'Add at least one instruction step');
    valid = false;
  }
  
  filledSteps.forEach(textarea => {
	  if (isProfane(textarea.value)) {
	    showError(textarea, 'Step contains inappropriate language');
	    valid = false;
	  }});

  if (!valid) {
    document.querySelector('.invalid')?.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    });
  }

  return valid;
}

// ---- Initial fill ----
fillRecipeForm(existingRecipe);

// ---- Update recipe with multipart upload ----
document.getElementById('publish-btn').addEventListener('click', async function(e) {
  e.preventDefault();

  if (!existingRecipe || !existingRecipe.id) {
    showMessage('Recipe data was not loaded correctly.', true);
    return;
  }

  if (!validateForm()) {
    return;
  }

  const formData = new FormData();
  formData.append('title', document.getElementById('title').value.trim());
  formData.append('description', document.getElementById('desc').value.trim());
  formData.append('prepTimeMinutes', document.getElementById('prep').value.trim());
  formData.append('cookTimeMinutes', document.getElementById('cooking').value.trim());
  formData.append('servings', document.getElementById('servings').value.trim());
  formData.append('cost', document.getElementById('cost').value.trim());
  formData.append('removeImage', String(imageRemoved));

document.querySelectorAll('#ingredients-container .dynamic-row').forEach((row, index) => {
    const ingredientName = row.querySelector('.ing-name').value.trim();
    if (!ingredientName) return;

    formData.append('ingredientName', ingredientName);
    const qty = row.querySelector('.ing-qty').value.trim();
    const unit = row.querySelector('.ing-unit').value.trim();
    const notes = row.querySelector('.ing-notes').value.trim();

    formData.append('ingredientQuantity', qty);
    if (unit) formData.append('ingredientUnit', unit);
    if (notes) formData.append('ingredientNotes', notes);
    formData.append('ingredientOrder', index);
});

  document.querySelectorAll('#steps-container textarea').forEach(textarea => {
    const instruction = textarea.value.trim();
    if (instruction) {
      formData.append('stepInstruction', instruction);
    }
  });

  tags.forEach(tag => formData.append('tags', tag));

  if (imgInput.files && imgInput.files[0]) {
    formData.append('image', imgInput.files[0]);
  }

  try {
    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

    const res = await fetch(`/api/recipes/${existingRecipe.id}/upload`, {
      method: 'POST',
      headers: {
        [csrfHeader]: csrfToken
      },
      body: formData,
      credentials: 'include'
    });

    const responseText = await res.text();

    if (res.ok) {
      showSuccessAndRedirect('Recipe updated successfully!');
    } else {
      console.error('Recipe update failed:', responseText);
      showMessage(responseText || 'Failed to update recipe.', true);
    }
  } catch (err) {
    console.error('Network error:', err);
    showMessage('Network error. Check console for details.', true);
  }
});

//delete function for button
document.getElementById('delete-btn').addEventListener('click', async function (e) {
  e.preventDefault();

  if (!existingRecipe || !existingRecipe.id) {
    showMessage("Recipe ID not found.", true);
    return;
  }

  // confirm delete
  const confirmDelete = confirm("Are you sure you want to delete this recipe?");
  if (!confirmDelete) return;

  try {
    // CSRF (required by Spring Security)
    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

    const response = await fetch(`/api/recipes/${existingRecipe.id}`, {
      method: "DELETE",
      headers: {
        [csrfHeader]: csrfToken
      },
      credentials: "include"
    });

    const text = await response.text();

    if (response.ok) {
      showSuccessAndRedirect("Recipe deleted successfully!");
    } else {
      showMessage(text || "Failed to delete recipe.", true);
    }

  } catch (error) {
    console.error("Delete error:", error);
    showMessage("Network error while deleting recipe.", true);
  }
});
</script>
</body>
</html>