<%# Ruby Calculator - Favorite Calculations Manager %>
<%# Author: RSK World (Molla Samser, Founder | Rima Khatun, Designer & Tester) %>
<%# Contact: help@rskworld.in | +91 93305 39277 %>
<%# Website: https://rskworld.in %>
<%# Year: 2026 %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Favorite Calculations - RSK World</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">
    <style>
        :root {
            --theme-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --theme-secondary: #4a5568;
            --theme-accent: #ed8936;
            --theme-success: #48bb78;
            --theme-danger: #e53e3e;
            --theme-warning: #ecc94b;
            --theme-info: #4299e1;
            --theme-background: #f7fafc;
            --theme-text: #2d3748;
            --theme-display: #2d3748;
        }
        
        body {
            background: var(--theme-background);
            color: var(--theme-text);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            transition: all 0.3s ease;
        }
        
        .favorites-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .favorites-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        .favorites-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }
        
        .section-header {
            background: var(--theme-primary);
            color: white;
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .favorite-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 15px 0;
            cursor: pointer;
            transition: all 0.3s ease;
            border-left: 4px solid var(--theme-info);
        }
        
        .favorite-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
            border-left-color: var(--theme-accent);
        }
        
        .favorite-expression {
            font-family: 'Courier New', monospace;
            font-size: 1.1em;
            font-weight: bold;
            color: var(--theme-display);
        }
        
        .category-badge {
            background: var(--theme-info);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8em;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .btn-favorite {
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-favorite:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .modal-content {
            border-radius: 15px;
            border: none;
        }
        
        .modal-header {
            background: var(--theme-primary);
            color: white;
            border-radius: 15px 15px 0 0;
        }
        
        .footer-info {
            background: var(--theme-secondary);
            color: white;
            padding: 25px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }
        
        @media (max-width: 768px) {
            .favorites-container {
                padding: 10px;
            }
            
            .favorites-card {
                padding: 20px;
                margin-bottom: 15px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid favorites-container">
        <!-- Header -->
        <div class="text-center mb-4 animate__animated animate__fadeInDown">
            <h1 class="display-4">
                <i class="fas fa-star text-warning"></i> Favorite Calculations
            </h1>
            <p class="lead">Save and Reuse Your Most Used Calculations</p>
        </div>

        <!-- Add New Favorite -->
        <div class="favorites-card animate__animated animate__fadeIn">
            <div class="section-header">
                <h4><i class="fas fa-plus-circle"></i> Add New Favorite</h4>
            </div>
            
            <div class="row">
                <div class="col-md-8">
                    <div class="mb-3">
                        <label class="form-label">Calculation Name:</label>
                        <input type="text" class="form-control" id="favorite-name" placeholder="e.g., Pythagorean Theorem">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Expression:</label>
                        <input type="text" class="form-control" id="favorite-expression" placeholder="e.g., a^2 + b^2">
                    </div>
                    
                    <div class="row">
                        <div class="col-6">
                            <label class="form-label">Category:</label>
                            <select class="form-select" id="favorite-category">
                                <option value="mathematics">Mathematics</option>
                                <option value="physics">Physics</option>
                                <option value="finance">Finance</option>
                                <option value="engineering">Engineering</option>
                                <option value="statistics">Statistics</option>
                                <option value="conversion">Conversion</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Result:</label>
                            <input type="text" class="form-control" id="favorite-result" placeholder="Result (optional)">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description:</label>
                        <textarea class="form-control" id="favorite-description" rows="2" 
                                  placeholder="Brief description of this calculation..."></textarea>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="d-grid gap-2">
                        <button class="btn btn-primary btn-lg" onclick="saveFavorite()">
                            <i class="fas fa-save"></i> Save Favorite
                        </button>
                        
                        <button class="btn btn-outline-info" onclick="addFromCurrent()">
                            <i class="fas fa-download"></i> From Current Calculation
                        </button>
                        
                        <div class="alert alert-info mt-3">
                            <i class="fas fa-info-circle"></i> <strong>Tip:</strong> Save frequently used calculations for quick access!
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search and Filter -->
        <div class="favorites-card animate__animated animate__fadeIn">
            <div class="row">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" class="form-control" id="search-favorites" 
                               placeholder="Search favorites..." onkeyup="searchFavorites()">
                    </div>
                </div>
                <div class="col-md-6">
                    <select class="form-select" id="filter-category" onchange="filterFavorites()">
                        <option value="">All Categories</option>
                        <option value="mathematics">Mathematics</option>
                        <option value="physics">Physics</option>
                        <option value="finance">Finance</option>
                        <option value="engineering">Engineering</option>
                        <option value="statistics">Statistics</option>
                        <option value="conversion">Conversion</option>
                        <option value="other">Other</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Favorites List -->
        <div class="favorites-card animate__animated animate__fadeInUp">
            <div class="section-header">
                <h4><i class="fas fa-list"></i> Your Favorite Calculations</h4>
            </div>
            
            <div id="favorites-list">
                <!-- Sample favorites -->
                <div class="favorite-item" data-category="mathematics">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h5><i class="fas fa-calculator text-primary"></i> Pythagorean Theorem</h5>
                            <div class="favorite-expression">a^2 + b^2 = c^2</div>
                            <p class="text-muted mb-2">Calculate the hypotenuse of a right triangle</p>
                            <span class="category-badge">Mathematics</span>
                        </div>
                        <div class="action-buttons">
                            <button class="btn btn-success btn-favorite btn-sm" onclick="useFavorite('a^2 + b^2')">
                                <i class="fas fa-play"></i> Use
                            </button>
                            <button class="btn btn-warning btn-favorite btn-sm" onclick="editFavorite(1)">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn btn-danger btn-favorite btn-sm" onclick="deleteFavorite(1)">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="favorite-item" data-category="finance">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h5><i class="fas fa-dollar-sign text-success"></i> Compound Interest</h5>
                            <div class="favorite-expression">P * (1 + r/n)^(n*t)</div>
                            <p class="text-muted mb-2">Calculate compound interest on investments</p>
                            <span class="category-badge">Finance</span>
                        </div>
                        <div class="action-buttons">
                            <button class="btn btn-success btn-favorite btn-sm" onclick="useFavorite('P * (1 + r/n)^(n*t)')">
                                <i class="fas fa-play"></i> Use
                            </button>
                            <button class="btn btn-warning btn-favorite btn-sm" onclick="editFavorite(2)">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn btn-danger btn-favorite btn-sm" onclick="deleteFavorite(2)">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="favorite-item" data-category="physics">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h5><i class="fas fa-atom text-info"></i> Einstein's E=mc²</h5>
                            <div class="favorite-expression">E = m * c^2</div>
                            <p class="text-muted mb-2">Mass-energy equivalence formula</p>
                            <span class="category-badge">Physics</span>
                        </div>
                        <div class="action-buttons">
                            <button class="btn btn-success btn-favorite btn-sm" onclick="useFavorite('m * 299792458^2')">
                                <i class="fas fa-play"></i> Use
                            </button>
                            <button class="btn btn-warning btn-favorite btn-sm" onclick="editFavorite(3)">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn btn-danger btn-favorite btn-sm" onclick="deleteFavorite(3)">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer-info animate__animated animate__fadeInUp">
            <h6><i class="fas fa-gem text-danger"></i> Ruby Calculator Pro</h6>
            <p class="mb-1">Professional Favorite Calculations Manager</p>
            <p class="mb-1">© 2026 <a href="https://rskworld.in" target="_blank" class="text-white">RSK World</a></p>
            <p class="mb-0">Developed by: Molla Samser (Founder) | Rima Khatun (Designer & Tester)</p>
            <p class="mb-0">Contact: <a href="mailto:help@rskworld.in" class="text-white">help@rskworld.in</a> | +91 93305 39277</p>
        </div>
    </div>

    <!-- Edit Favorite Modal -->
    <div class="modal fade" id="editFavoriteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Edit Favorite</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Name:</label>
                        <input type="text" class="form-control" id="edit-name">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Expression:</label>
                        <input type="text" class="form-control" id="edit-expression">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Category:</label>
                        <select class="form-select" id="edit-category">
                            <option value="mathematics">Mathematics</option>
                            <option value="physics">Physics</option>
                            <option value="finance">Finance</option>
                            <option value="engineering">Engineering</option>
                            <option value="statistics">Statistics</option>
                            <option value="conversion">Conversion</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description:</label>
                        <textarea class="form-control" id="edit-description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="updateFavorite()">Save Changes</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentEditId = null;

        // Save new favorite
        function saveFavorite() {
            const name = document.getElementById('favorite-name').value;
            const expression = document.getElementById('favorite-expression').value;
            const category = document.getElementById('favorite-category').value;
            const result = document.getElementById('favorite-result').value;
            const description = document.getElementById('favorite-description').value;
            
            if (!name || !expression) {
                alert('Please enter at least a name and expression');
                return;
            }
            
            fetch('/favorites', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    name, 
                    expression, 
                    category, 
                    result, 
                    description 
                })
            }).then(response => response.json())
              .then(data => {
                  if (data.id) {
                      addFavoriteToList(data);
                      clearForm();
                      alert('Favorite saved successfully!');
                  } else {
                      alert('Error saving favorite: ' + (data.error || 'Unknown error'));
                  }
              })
              .catch(error => {
                  alert('Error: ' + error.message);
              });
        }

        // Add favorite to the list
        function addFavoriteToList(favorite) {
            const favoritesList = document.getElementById('favorites-list');
            const favoriteItem = document.createElement('div');
            favoriteItem.className = 'favorite-item animate__animated animate__fadeIn';
            favoriteItem.setAttribute('data-category', favorite.category);
            favoriteItem.setAttribute('data-id', favorite.id);
            
            favoriteItem.innerHTML = `
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h5><i class="fas fa-calculator text-primary"></i> ${favorite.name}</h5>
                        <div class="favorite-expression">${favorite.expression}</div>
                        <p class="text-muted mb-2">${favorite.description || 'No description'}</p>
                        <span class="category-badge">${favorite.category}</span>
                    </div>
                    <div class="action-buttons">
                        <button class="btn btn-success btn-favorite btn-sm" onclick="useFavorite('${favorite.expression}')">
                            <i class="fas fa-play"></i> Use
                        </button>
                        <button class="btn btn-warning btn-favorite btn-sm" onclick="editFavorite(${favorite.id})">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button class="btn btn-danger btn-favorite btn-sm" onclick="deleteFavorite(${favorite.id})">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </div>
                </div>
            `;
            
            favoritesList.appendChild(favoriteItem);
        }

        // Use favorite in calculator
        function useFavorite(expression) {
            // Store in session storage to use in main calculator
            sessionStorage.setItem('favoriteExpression', expression);
            window.location.href = '/';
        }

        // Edit favorite
        function editFavorite(id) {
            currentEditId = id;
            // In a real app, you would fetch the favorite data
            // For now, we'll use sample data
            document.getElementById('edit-name').value = 'Sample Favorite';
            document.getElementById('edit-expression').value = 'x^2 + y^2';
            document.getElementById('edit-category').value = 'mathematics';
            document.getElementById('edit-description').value = 'Sample description';
            
            const modal = new bootstrap.Modal(document.getElementById('editFavoriteModal'));
            modal.show();
        }

        // Update favorite
        function updateFavorite() {
            if (!currentEditId) return;
            
            const name = document.getElementById('edit-name').value;
            const expression = document.getElementById('edit-expression').value;
            const category = document.getElementById('edit-category').value;
            const description = document.getElementById('edit-description').value;
            
            fetch(`/favorites/${currentEditId}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name, expression, category, description })
            }).then(response => response.json())
              .then(data => {
                  if (data.success) {
                      alert('Favorite updated successfully!');
                      location.reload();
                  } else {
                      alert('Error updating favorite');
                  }
              });
        }

        // Delete favorite
        function deleteFavorite(id) {
            if (confirm('Are you sure you want to delete this favorite?')) {
                fetch(`/favorites/${id}`, {
                    method: 'DELETE'
                }).then(response => response.json())
                  .then(data => {
                      if (data.success) {
                          // Remove from DOM
                          const element = document.querySelector(`[data-id="${id}"]`);
                          if (element) {
                              element.remove();
                          }
                          alert('Favorite deleted successfully!');
                      } else {
                          alert('Error deleting favorite');
                      }
                  });
            }
        }

        // Search favorites
        function searchFavorites() {
            const searchTerm = document.getElementById('search-favorites').value.toLowerCase();
            const favorites = document.querySelectorAll('.favorite-item');
            
            favorites.forEach(favorite => {
                const text = favorite.textContent.toLowerCase();
                if (text.includes(searchTerm)) {
                    favorite.style.display = 'block';
                } else {
                    favorite.style.display = 'none';
                }
            });
        }

        // Filter by category
        function filterFavorites() {
            const category = document.getElementById('filter-category').value;
            const favorites = document.querySelectorAll('.favorite-item');
            
            favorites.forEach(favorite => {
                if (!category || favorite.getAttribute('data-category') === category) {
                    favorite.style.display = 'block';
                } else {
                    favorite.style.display = 'none';
                }
            });
        }

        // Add from current calculation
        function addFromCurrent() {
            const currentExpression = sessionStorage.getItem('currentExpression') || '';
            const currentResult = sessionStorage.getItem('currentResult') || '';
            
            document.getElementById('favorite-expression').value = currentExpression;
            document.getElementById('favorite-result').value = currentResult;
            document.getElementById('favorite-name').focus();
        }

        // Clear form
        function clearForm() {
            document.getElementById('favorite-name').value = '';
            document.getElementById('favorite-expression').value = '';
            document.getElementById('favorite-result').value = '';
            document.getElementById('favorite-description').value = '';
            document.getElementById('favorite-category').selectedIndex = 0;
        }

        // Load favorites on page load
        window.addEventListener('load', function() {
            fetch('/favorites')
                .then(response => response.json())
                .then(data => {
                    data.forEach(favorite => addFavoriteToList(favorite));
                })
                .catch(error => {
                    console.log('Using sample favorites due to:', error);
                });
        });
    </script>
</body>
</html>
