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

$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!",
        'logout'         => 'Log Out',
        'err_pass_match' => 'Passwords do not match.',
        'err_fill_fields'=> 'Please fill in all fields.',
    ],
    '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!",
        'logout'         => 'Abmelden',
        'err_pass_match' => 'Die Passwörter stimmen nicht überein.',
        'err_fill_fields'=> 'Bitte fülle alle Felder aus.',
    ]
];

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

// Check PHP session state
$user = $_SESSION['fc_user'] ?? null;

$allRecipes = load_recipes();
$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';
?>

<?php /* Auth page, profile dashboard, and favorites styles are in assets/style.css (Phase 2 section) */ ?>



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

  <!-- ── 1. UNAUTHENTICATED STATE (Login/Register Card) ── -->
  <div class="auth-card" id="authCard" style="display: <?php echo $user ? 'none' : 'block'; ?>;">
    <div class="auth-tabs">
      <button class="auth-tab active" onclick="switchTab('login')"><?php echo $t['login']; ?></button>
      <button class="auth-tab" onclick="switchTab('signup')"><?php echo $t['signup']; ?></button>
    </div>

    <!-- Login Form -->
    <form class="auth-form active" id="loginForm" onsubmit="handleLogin(event)">
      <div class="auth-field">
        <label for="loginEmail"><?php echo $t['email']; ?></label>
        <input type="email" id="loginEmail" placeholder="you@example.com" required autocomplete="username">
      </div>
      <div class="auth-field">
        <label for="loginPassword"><?php echo $t['password']; ?></label>
        <input type="password" id="loginPassword" placeholder="••••••••" required autocomplete="current-password">
      </div>
      <div class="auth-btn-row">
        <button class="btn-reveal" type="submit">
          <span class="btn-reveal-text"><?php echo $t['login']; ?></span>
          <span class="spinner"></span>
          <span class="btn-reveal-arrow">→</span>
        </button>
      </div>
      <p class="auth-switch-text">
        <?php echo $t['no_account']; ?> <button type="button" onclick="switchTab('signup')"><?php echo $t['signup']; ?></button>
      </p>
    </form>

    <!-- Sign-up Form -->
    <form class="auth-form" id="signupForm" onsubmit="handleSignup(event)">
      <div class="auth-field">
        <label for="signupEmail"><?php echo $t['email']; ?></label>
        <input type="email" id="signupEmail" placeholder="you@example.com" required autocomplete="username">
      </div>
      <div class="auth-field">
        <label for="signupPassword"><?php echo $t['password']; ?></label>
        <input type="password" id="signupPassword" placeholder="••••••••" required autocomplete="new-password">
      </div>
      <div class="auth-field">
        <label for="signupConfirm"><?php echo $t['confirm_pass']; ?></label>
        <input type="password" id="signupConfirm" placeholder="••••••••" required autocomplete="new-password">
      </div>
      <div class="auth-field">
        <label for="signupGoal"><?php echo $t['goal']; ?></label>
        <select id="signupGoal" required>
          <option value="" disabled selected><?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['signup']; ?></span>
          <span class="spinner"></span>
          <span class="btn-reveal-arrow">→</span>
        </button>
      </div>
      <p class="auth-switch-text">
        <?php echo $t['have_account']; ?> <button type="button" onclick="switchTab('login')"><?php echo $t['login']; ?></button>
      </p>
    </form>
  </div>

  <!-- ── 2. AUTHENTICATED STATE (Dashboard & Favorites) ── -->
  <div class="profile-shell" id="profileShell" style="display: <?php echo $user ? 'grid' : 'none'; ?>;">
    <aside class="profile-sidebar">
      <div style="display: flex; align-items: center; gap: 1.5rem;">
        <div class="profile-avatar" id="avatarChar">
          <?php echo $user ? strtoupper(substr($user['email'], 0, 1)) : ''; ?>
        </div>
        <div class="profile-meta">
          <p><?php echo $t['welcome']; ?></p>
          <h2 id="profileEmailVal"><?php echo $user ? e($user['email']) : ''; ?></h2>
        </div>
      </div>
      
      <div class="profile-details">
        <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>

      <button class="btn-reveal" onclick="handleLogout()" style="margin-top: 1rem; border-color: rgba(0,0,0,0.15);">
        <span class="btn-reveal-text"><?php echo $t['logout']; ?></span>
        <span class="btn-reveal-arrow">→</span>
      </button>
    </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>
// Expose recipe bank to JavaScript
const recipeBank = <?php echo $recipesJson; ?>;
const langText = <?php echo json_encode($t); ?>;

function switchTab(tab) {
  const tabs = document.querySelectorAll('.auth-tab');
  const forms = document.querySelectorAll('.auth-form');
  const alertEl = document.getElementById('authAlert');
  alertEl.style.display = 'none';

  if (tab === 'login') {
    tabs[0].classList.add('active');
    tabs[1].classList.remove('active');
    forms[0].classList.add('active');
    forms[1].classList.remove('active');
  } else {
    tabs[0].classList.remove('active');
    tabs[1].classList.add('active');
    forms[0].classList.remove('active');
    forms[1].classList.add('active');
  }
}

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

function handleLogin(e) {
  e.preventDefault();
  const email = document.getElementById('loginEmail').value;
  const pass = document.getElementById('loginPassword').value;
  const btn = e.target.querySelector('button[type="submit"]');
  const alertEl = document.getElementById('authAlert');
  
  alertEl.style.display = 'none';
  btn.disabled = true;

  window.auth.signInWithEmailAndPassword(email, pass)
    .then(userCredential => {
      // Sync happens automatically via onAuthStateChanged observer in head.php!
      // The observer will reload the page when it receives the new state
    })
    .catch(error => {
      btn.disabled = false;
      let errMsg = error.message;
      // Firebase v10 compat SDK consolidates wrong-password + user-not-found
      // into auth/invalid-credential. Handle all three for backwards compatibility.
      if (
        error.code === 'auth/invalid-credential' ||
        error.code === 'auth/wrong-password'     ||
        error.code === 'auth/user-not-found'
      ) {
        errMsg = 'Invalid email or password.';
      }
      showAlert(errMsg);
    });
}

function handleSignup(e) {
  e.preventDefault();
  const email = document.getElementById('signupEmail').value;
  const pass = document.getElementById('signupPassword').value;
  const confirm = document.getElementById('signupConfirm').value;
  const goal = document.getElementById('signupGoal').value;
  const btn = e.target.querySelector('button[type="submit"]');
  const alertEl = document.getElementById('authAlert');

  alertEl.style.display = 'none';

  if (pass !== confirm) {
    showAlert(langText.err_pass_match);
    return;
  }

  btn.disabled = true;

  window.auth.createUserWithEmailAndPassword(email, pass)
    .then(userCredential => {
      const user = userCredential.user;
      // Save profile details to Firestore
      return window.db.collection('users').doc(user.uid).set({
        email: email,
        goal: goal,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      });
    })
    .then(() => {
      // Sync is handled by observer in head.php!
    })
    .catch(error => {
      btn.disabled = false;
      showAlert(error.message);
    });
}

function handleLogout() {
  window.auth.signOut()
    .then(() => {
      // Sync observer takes care of PHP session termination and reloads page
    });
}

// ── Profile and Favorites dashboard renderer ──
function initDashboard(user) {
  if (!user) return;
  
  const goalVal = document.getElementById('profileGoalVal');
  const grid = document.getElementById('favoritesGrid');
  const emptyState = document.getElementById('favoritesEmpty');
  
  // Fetch user profile from Firestore
  window.db.collection('users').doc(user.uid).get()
    .then(doc => {
      if (doc.exists) {
        const data = doc.data();
        let goalString = '-';
        if (data.goal === 'weight_loss') goalString = langText.goal_loose;
        else if (data.goal === 'muscle_gain') goalString = langText.goal_gain;
        else if (data.goal === 'healthy') goalString = langText.goal_healthy;
        
        goalVal.textContent = goalString;
      }
    })
    .catch(err => console.error("Error loading profile: ", err));

  // Load Saved Favorites
  window.db.collection('user_favorites').where('userId', '==', user.uid).get()
    .then(snapshot => {
      grid.innerHTML = '';
      
      if (snapshot.empty) {
        grid.style.display = 'none';
        emptyState.style.display = 'block';
        return;
      }

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

      snapshot.forEach(doc => {
        const fav = doc.data();
        const recipe = recipeBank.find(r => r.slug === fav.recipeSlug);
        
        if (recipe) {
          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 none of the favorite slugs matched recipes in current language:
      if (grid.children.length === 0) {
        grid.style.display = 'none';
        emptyState.style.display = 'block';
      }
    })
    .catch(err => {
      console.error("Error fetching favorites: ", err);
      grid.innerHTML = '<p>Error loading favorites. Please try again.</p>';
    });
}

// Observe auth state for dashboard renderer
window.addEventListener('DOMContentLoaded', () => {
  window.auth.onAuthStateChanged(user => {
    const authCard = document.getElementById('authCard');
    const profileShell = document.getElementById('profileShell');
    
    if (user) {
      document.getElementById('profileEmailVal').textContent = user.email;
      document.getElementById('avatarChar').textContent = user.email.substr(0,1).toUpperCase();
      authCard.style.display = 'none';
      profileShell.style.display = 'grid';
      initDashboard(user);
    } else {
      authCard.style.display = 'block';
      profileShell.style.display = 'none';
    }
  });
});
</script>

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