<!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 th:text="${recipe != null ? recipe.title : 'Recipe'}">Recipe</title>
    <link rel="stylesheet" th:href="@{/css/view-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">
</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="body">

    <div class="body-left">
        <nav class="sidebar-left">
            <ul>
                <li><a th:href="@{/explore}">Explore</a></li>
                <li th:unless="${guest}"><a th:href="@{/favorites}">Saved</a></li>
                <li th:unless="${guest}"><a th:href="@{/my-profile}">Profile</a></li>

                <li th:if="${guest}" class="login-link">
                    <a th:href="@{/login}">Login</a> or <a th:href="@{/register}">Sign Up</a> to create and save recipes
                </li>

                <li th:unless="${guest}">
                    <form th:action="@{/logout}" method="post">
                        <input type="image" th:src="@{/images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
                    </form>
                </li>
            </ul>
        </nav>
        <a th:href="@{/create}" class="create_icon">
            <img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
        </a>
    </div>

    <main class="main-content">
    	<div th:if="${recipe != null}" class="recipe-container">
        	<section class="recipe-section">
        		<div class="left-view">
            	<h1 th:text="${recipe.title}">Recipe Title</h1>

            	<p th:if="${recipe.userDto != null}" class="recipe-author">
                	<strong>Author:</strong>
                	<a th:href="@{/users/{id}(id=${recipe.userDto.id})}"
                   	th:text="${recipe.userDto.effectiveDisplayName}">Author Name</a>
            	</p>
            	
            	<div class="recipe-description">
                	<h2>Description</h2>
                	<p th:text="${recipe.description}">Recipe description</p>
            	</div>
            	
            	<div class="recipe-ingredients">
                	<h2>Ingredients</h2>
                	<ul th:if="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}">
                    	<li th:each="ingredient : ${recipe.ingredients}">
                        	<span th:text="${ingredient.quantity}">1</span>
                        	<span th:text="${ingredient.unit}">cup</span>
                        	<span th:text="${ingredient.ingredientName}">Ingredient</span>
                        	<span th:if="${ingredient.notes != null and !#strings.isEmpty(ingredient.notes)}"
                              th:text="${'(' + ingredient.notes + ')'}">(notes)</span>
                    	</li>
                	</ul>
                	<p th:unless="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}">No ingredients listed.</p>
            	</div>

            	<div class="recipe-steps">
                	<h2>Steps</h2>
                	<ol th:if="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}">
                    	<li th:each="step : ${recipe.steps}" th:text="${step.instruction}">Step instruction</li>
                	</ol>
                	<p th:unless="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}">No steps listed.</p>
            	</div>

            	</div>
            	
            	<div class="right-view">
            	
            	<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}" class="recipe-image-wrap">
                	<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
            	</div>

            	<p th:unless="${recipe.images != null and !#lists.isEmpty(recipe.images)}" class="recipe-no-image">
                	No image uploaded for this recipe.
            	</p>

            	<div class="recipe-meta">
                	<p><strong>Prep Time:</strong> <span th:text="${recipe.prepTimeMinutes}">0</span> minutes</p>
                	<p><strong>Cook Time:</strong> <span th:text="${recipe.cookTimeMinutes}">0</span> minutes</p>
                	<p><strong>Servings:</strong> <span th:text="${recipe.servings}">0</span></p>
                	<p><strong>Cost:</strong> <span th:text="${recipe.cost >= 4 ? '$$$$' : #strings.repeat('$', recipe.cost)}">$</span></p>
            	</div>

            	<div class="recipe-tags">
                	<h2>Tags: </h2>
                	<div th:if="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}" class="tag-list">
                    	<span th:each="tag : ${recipe.tags}" th:text="${tag.name}">Tag</span>
                	</div>
                	<p th:unless="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}">No tags listed.</p>
            	</div>

            	<div class="recipe-links">
                	<a th:if="${recipe.userDto != null}"
                   	th:href="@{/users/{id}(id=${recipe.userDto.id})}">View author's profile</a>
            	</div>
        	</section>
        	
        	<button type="button" class="save-btn" th:data-recipe-id="${recipe.id}">Save Recipe</button>
    	</div>

    	<div th:unless="${recipe != null}" class="recipe-not-found">
        	<section>
            	<h1>Recipe not found</h1>
        	</section>
    	</div>
	</main>
</div>

<script>
async function getCurrentUser() {
    const response = await fetch('/api/users/me', {
        credentials: 'same-origin'
    });

    if (!response.ok) {
        return null;
    }

    const user = await response.json();
    return user || null;
}

async function saveRecipe(recipeId, button) {
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.content;
    const csrfToken = document.querySelector('meta[name="_csrf"]')?.content;

    const user = await getCurrentUser();

    if (!user || !user.id) {
        window.location.href = '/login';
        return;
    }

    const response = await fetch(`/api/users/${user.id}/favorites/${recipeId}`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            ...(csrfHeader && csrfToken ? { [csrfHeader]: csrfToken } : {})
        }
    });

    if (!response.ok) {
        const text = await response.text();
        alert(text || 'Could not save recipe.');
        return;
    }

    button.textContent = 'Saved';
    button.disabled = true;
}

document.querySelectorAll('.save-btn').forEach(button => {
    button.addEventListener('click', async () => {
        const recipeId = button.dataset.recipeId;
        await saveRecipe(recipeId, button);
    });
});
</script>

</body>
</html>