<?php
require __DIR__ . '/helpers.php';

try {
    $allRecipes = load_recipes();
} catch (DatabaseUnavailableException $e) {
    handle_database_unavailable($e);
}

$lang = (isset($_GET['lang']) && strtolower($_GET['lang']) === 'de') ? 'de' : 'en';

$copy = [
    'en' => [
        'page_title'     => 'My Profile & Favorites | FlixCooks',
        'meta_desc'      => 'Manage your profile, dietary goals, and saved seasonal recipes on FlixCooks.',
        'login'          => 'Login',
        'signup'         => 'Register',
        'email'          => 'Email Address',
        'password'       => 'Password',
        'confirm_pass'   => 'Confirm Password',
        'goal'           => 'Dietary Goal',
        'goal_placeholder' => 'Select your dietary goal',
        'goal_loose'     => 'Weight Loss / Low-Carb',
        'goal_gain'      => 'Muscle Gain / High-Protein',
        'goal_healthy'   => 'Healthy & Balanced',
        'no_account'     => "Don't have an account yet?",
        'have_account'   => 'Already have an account?',
        'welcome'        => 'Welcome back,',
        'your_goal'      => 'Your dietary goal',
        'saved_recipes'  => 'Your Saved Favorites',
        'no_favorites'   => "You haven't saved any recipes yet. Explore our collection and tap the heart icon!",
        'save_goal'      => 'Save goal',
        'goal_saved'     => 'Dietary goal saved.',
        'local_note'     => 'Favorites and goals are stored in this browser only.',
    ],
    'de' => [
        'page_title'     => 'Mein Profil & Favoriten | FlixCooks',
        'meta_desc'      => 'Verwalte dein Profil, deine Ernährungsziele und gespeicherten Rezepte auf FlixCooks.',
        'login'          => 'Anmelden',
        'signup'         => 'Registrieren',
        'email'          => 'E-Mail-Adresse',
        'password'       => 'Passwort',
        'confirm_pass'   => 'Passwort bestätigen',
        'goal'           => 'Ernährungsziel',
        'goal_placeholder' => 'Wähle dein Ernährungsziel',
        'goal_loose'     => 'Abnehmen / Low-Carb',
        'goal_gain'      => 'Muskelaufbau / High-Protein',
        'goal_healthy'   => 'Gesund & Ausgewogen',
        'no_account'     => "Noch kein Konto?",
        'have_account'   => 'Bereits registriert?',
        'welcome'        => 'Willkommen zurück,',
        'your_goal'      => 'Dein Ernährungsziel',
        'saved_recipes'  => 'Deine gespeicherten Favoriten',
        'no_favorites'   => "Du hast noch keine Rezepte gespeichert. Entdecke unsere Küche und klicke auf das Herz-Symbol!",
        'save_goal'      => 'Ziel speichern',
        'goal_saved'     => 'Ernährungsziel gespeichert.',
        'local_note'     => 'Favoriten und Ziele werden nur in diesem Browser gespeichert.',
    ]
];

$t = $copy[$lang];
$pageTitle = $t['page_title'];
$description = $t['meta_desc'];

$allRecipesLocal = localize_recipes($allRecipes, $lang);

// Formatter helper for JS usage
$recipesJson = json_encode(array_values(array_map(function($r) use ($lang) {
    return [
        'slug' => $r['slug'],
        'title' => $r['title'],
        'hero' => $r['hero'],
        'difficulty' => $r['difficulty'],
        'total_time' => (int)($r['total_time'] ?? 0),
        'url' => '/recipe.php?slug=' . urlencode($r['slug']) . '&lang=' . $lang
    ];
}, $allRecipesLocal)));

include __DIR__ . '/partials/head.php';
include __DIR__ . '/partials/header.php';
?>

<style>
/* ── Premium Authentication Page Styling ── */
.auth-page {
  padding: clamp(6rem, 10vh, 10rem) var(--grid-margin) clamp(4rem, 8vh, 6rem);
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.auth-card {
  width: 100%;
  max-width: 500px;
  background: var(--surface-2);
  border: 1px solid var(--stroke);
  box-shadow: var(--shadow);
  border-radius: var(--radius);
  padding: clamp(2rem, 5vw, 3.5rem);
  position: relative;
  overflow: hidden;
  transition: transform 0.4s var(--ease-out-expo), opacity 0.4s ease;
}

.auth-tabs {
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin-bottom: 2.5rem;
  border-bottom: 1px solid var(--stroke);
  padding-bottom: 0.8rem;
}

.auth-tab {
  font-family: var(--font-serif-display);
  font-size: 1.5rem;
  color: var(--color-text-muted);
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  position: relative;
  transition: color 0.3s ease;
}

.auth-tab.active {
  color: var(--ink);
}

.auth-tab::after {
  content: '';
  position: absolute;
  bottom: -0.9rem;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: var(--color-accent-gold);
  transform: scaleX(0);
  transform-origin: center;
  transition: transform 0.4s var(--ease-out-expo);
}

.auth-tab.active::after {
  transform: scaleX(1);
}

.auth-form {
  display: none;
  flex-direction: column;
  gap: 1.5rem;
}

.auth-form.active {
  display: flex;
  animation: authFadeIn 0.5s var(--ease-out-expo) both;
}

@keyframes authFadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.auth-field {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.auth-field label {
  font-family: var(--font-sans-clean);
  font-size: 0.8rem;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  font-weight: 700;
  color: var(--muted);
}

.auth-field input, .auth-field select {
  padding: 1rem 1.25rem;
  border-radius: 10px;
  border: 1px solid var(--stroke);
  background: var(--surface);
  color: var(--ink);
  font-family: var(--font-sans-clean);
  font-size: 0.95rem;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  outline: none;
}

.auth-field input:focus, .auth-field select:focus {
  border-color: var(--color-accent-gold);
  box-shadow: 0 0 0 3px var(--accent-soft);
}

.auth-btn-row {
  margin-top: 1rem;
}

.auth-btn-row button {
  width: 100%;
  justify-content: center;
}

.auth-switch-text {
  text-align: center;
  font-size: 0.9rem;
  color: var(--muted);
  margin-top: 1.5rem;
}

.auth-switch-text button {
  background: none;
  border: none;
  color: var(--ink);
  font-weight: 700;
  cursor: pointer;
}

/* ── Profile & Dashboard Styling ── */
.profile-shell {
  width: 100%;
  max-width: 1100px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 3rem;
}

@media (min-width: 850px) {
  .profile-shell {
    grid-template-columns: 320px 1fr;
  }
}

.profile-sidebar {
  background: var(--surface-2);
  border: 1px solid var(--stroke);
  border-radius: var(--radius);
  padding: 2.5rem;
  display: flex;
  flex-direction: column;
  gap: 2rem;
  height: fit-content;
  box-shadow: var(--shadow);
}

.profile-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: var(--accent-soft);
  color: var(--color-accent-gold);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: var(--font-serif-display);
  font-size: 2.5rem;
  border: 1px solid rgba(195,166,119,0.3);
}

.profile-meta h2 {
  font-size: 1.75rem;
  margin-bottom: 0.25rem;
  font-family: var(--font-serif-display);
}

.profile-meta p {
  font-size: 0.9rem;
  color: var(--muted);
}

.profile-details {
  border-top: 1px solid var(--stroke);
  padding-top: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
}

.profile-stat-box {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}

.profile-stat-label {
  font-size: 0.72rem;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  font-weight: 700;
  color: var(--muted);
}

.profile-stat-val {
  font-size: 1rem;
  font-weight: 600;
  color: var(--ink);
}

.profile-main {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.profile-favorites-title {
  font-family: var(--font-serif-display);
  font-size: 2rem;
  border-bottom: 1px solid var(--stroke);
  padding-bottom: 0.8rem;
  margin-bottom: 1rem;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--grid-gap);
}

.favorites-empty {
  text-align: center;
  padding: 4rem 2rem;
  background: var(--surface-2);
  border: 1px dashed var(--stroke);
  border-radius: var(--radius);
  color: var(--muted);
}

/* Alert styling */
.auth-alert {
  background: #fdf2f2;
  border: 1px solid #fbd5d5;
  color: #9b1c1c;
  padding: 1rem;
  border-radius: 8px;
  font-size: 0.9rem;
  margin-bottom: 1.5rem;
  display: none;
  animation: authFadeIn 0.3s ease;
}

[data-theme="dark"] .auth-alert {
  background: #2b1515;
  border-color: #5a1818;
  color: #ff9b9b;
}

/* Loading state spinner */
.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255,255,255,0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 0.8s linear infinite;
  display: none;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-reveal:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-reveal:disabled .spinner {
  display: inline-block;
}

.btn-reveal:disabled .btn-reveal-text {
  display: none;
}
</style>

<main class="auth-page">
  <div class="auth-alert" id="authAlert"></div>

  <div class="profile-shell" id="profileShell" style="display: grid;">
    <aside class="profile-sidebar">
      <div class="profile-meta">
        <p><?php echo $t['welcome']; ?></p>
        <p style="font-size: 0.9rem; color: var(--muted); margin-top: 0.5rem;"><?php echo e($t['local_note']); ?></p>
      </div>

      <form class="auth-form active" id="goalForm" onsubmit="handleSaveGoal(event)" style="margin-top: 1.5rem;">
        <div class="auth-field">
          <label for="profileGoal"><?php echo $t['goal']; ?></label>
          <select id="profileGoal" required>
            <option value="" disabled><?php echo $t['goal_placeholder']; ?></option>
            <option value="weight_loss"><?php echo $t['goal_loose']; ?></option>
            <option value="muscle_gain"><?php echo $t['goal_gain']; ?></option>
            <option value="healthy"><?php echo $t['goal_healthy']; ?></option>
          </select>
        </div>
        <div class="auth-btn-row">
          <button class="btn-reveal" type="submit">
            <span class="btn-reveal-text"><?php echo $t['save_goal']; ?></span>
            <span class="btn-reveal-arrow">→</span>
          </button>
        </div>
      </form>

      <div class="profile-details" style="margin-top: 1.5rem;">
        <div class="profile-stat-box">
          <span class="profile-stat-label"><?php echo $t['your_goal']; ?></span>
          <span class="profile-stat-val" id="profileGoalVal">-</span>
        </div>
      </div>
    </aside>

    <section class="profile-main">
      <h3 class="profile-favorites-title"><?php echo $t['saved_recipes']; ?></h3>
      
      <div id="favoritesGrid" class="favorites-grid">
        <!-- JS inserts favorited recipe cards here -->
        <div class="spinner" style="display: block; margin: 4rem auto; border-top-color: var(--color-accent-gold);"></div>
      </div>
      
      <div id="favoritesEmpty" class="favorites-empty" style="display: none;">
        <p><?php echo $t['no_favorites']; ?></p>
        <a class="btn-reveal" href="/index.php?lang=<?php echo $lang; ?>#recipes-start" style="margin-top: 1.5rem;">
          <span class="btn-reveal-text"><?php echo $lang === 'de' ? 'Entdecken' : 'Explore Recipes'; ?></span>
          <span class="btn-reveal-arrow">→</span>
        </a>
      </div>
    </section>
  </div>
</main>

<script>
const recipeBank = <?php echo $recipesJson; ?>;
const langText = <?php echo json_encode($t); ?>;

function goalLabel(goal) {
  if (goal === 'weight_loss') return langText.goal_loose;
  if (goal === 'muscle_gain') return langText.goal_gain;
  if (goal === 'healthy') return langText.goal_healthy;
  return '-';
}

function showAlert(message) {
  const alertEl = document.getElementById('authAlert');
  alertEl.textContent = message;
  alertEl.style.display = 'block';
  window.scrollTo({ top: alertEl.offsetTop - 120, behavior: 'smooth' });
}

function handleSaveGoal(e) {
  e.preventDefault();
  if (!window.fcLocal) return;
  const goal = document.getElementById('profileGoal').value;
  window.fcLocal.setGoal(goal);
  document.getElementById('profileGoalVal').textContent = goalLabel(goal);
  showAlert(langText.goal_saved);
}

function renderFavorites() {
  const grid = document.getElementById('favoritesGrid');
  const emptyState = document.getElementById('favoritesEmpty');
  if (!window.fcLocal) return;

  const slugs = window.fcLocal.getFavorites();
  grid.innerHTML = '';

  if (slugs.length === 0) {
    grid.style.display = 'none';
    emptyState.style.display = 'block';
    return;
  }

  emptyState.style.display = 'none';
  grid.style.display = 'grid';

  slugs.forEach(function(slug) {
    const recipe = recipeBank.find(function(r) { return r.slug === slug; });
    if (!recipe) return;
    const card = document.createElement('article');
    card.className = 'card card--bare reveal-target revealed';
    card.innerHTML =
      '<a href="' + recipe.url + '" class="card__image">' +
        '<img src="' + recipe.hero + '" alt="' + recipe.title + '" loading="lazy">' +
      '</a>' +
      '<div class="card__body">' +
        '<h4><a href="' + recipe.url + '">' + recipe.title + '</a></h4>' +
        '<div class="meta">' +
          '<span>⏱ ' + recipe.total_time + ' min</span>' +
          '<span>🙂 ' + recipe.difficulty + '</span>' +
        '</div>' +
      '</div>';
    grid.appendChild(card);
  });

  if (grid.children.length === 0) {
    grid.style.display = 'none';
    emptyState.style.display = 'block';
  }
}

window.addEventListener('DOMContentLoaded', function() {
  if (!window.fcLocal) return;
  const goal = window.fcLocal.getGoal();
  const select = document.getElementById('profileGoal');
  if (goal && select) select.value = goal;
  document.getElementById('profileGoalVal').textContent = goalLabel(goal);
  renderFavorites();
});
</script>

<?php include __DIR__ . '/partials/footer.php'; ?>
