<?php
  $langCode   = (isset($lang) && $lang === 'de') ? 'de' : 'en';
  $langSuffix = $langCode === 'de' ? '?lang=de' : '';
  $settings   = function_exists('load_site_settings') ? load_site_settings() : null;
  $contactEmail = $settings['imprint'][$langCode]['email'] ?? 'contact@flixcooks.at';
?>
<footer class="site-footer" role="contentinfo">
  <section class="footer-newsletter">
    <div class="newsletter-content">
      <h3><?php echo $langCode === 'de' ? 'Bleib inspiriert' : 'Stay Inspired'; ?></h3>
      <p><?php echo $langCode === 'de' ? 'Melde dich für unseren Newsletter an und erhalte saisonale Rezepte direkt in dein Postfach.' : 'Sign up for our newsletter and get seasonal recipes delivered straight to your inbox.'; ?></p>
    </div>
    <form class="newsletter-form" id="newsletterForm" onsubmit="handleSubscribe(event)">
      <div class="newsletter-input-group">
        <input type="email" id="newsletterEmail" placeholder="<?php echo $langCode === 'de' ? 'Deine E-Mail-Adresse...' : 'Your email address...'; ?>" required>
        <button type="submit" aria-label="Subscribe">
          <span class="btn-text">→</span>
          <span class="btn-success-check">✓</span>
        </button>
      </div>
      <div class="newsletter-feedback" id="newsletterFeedback"></div>
    </form>
  </section>

  <div class="footer-meta">
    <p><?php echo $langCode === 'de' ? 'Designed &amp; entwickelt von Felix Brockers' : 'Designed &amp; built by Felix Brockers'; ?></p>
    <a class="contact-link underline-link" href="mailto:<?php echo e($contactEmail); ?>">
      <?php echo e($contactEmail); ?>
    </a>
    <small>© <?php echo date('Y'); ?> FlixCooks</small>
  </div>
  <div class="footer-links">
    <a class="underline-link" href="/impressum.php<?php echo $langSuffix; ?>">
      <?php echo $langCode === 'de' ? 'Impressum' : 'Imprint'; ?>
    </a>
    <a class="underline-link" href="/datenschutz.php<?php echo $langSuffix; ?>">
      <?php echo $langCode === 'de' ? 'Datenschutz' : 'Privacy'; ?>
    </a>
  </div>
</footer>

<button id="backToTop" aria-label="<?php echo $langCode === 'de' ? 'Nach oben' : 'Back to top'; ?>">↑</button>



<script>
// ── Back to top ────────────────────────────────────────────────
(function(){
  var btn = document.getElementById('backToTop');
  if (!btn) return;
  var check = function() { btn.classList.toggle('show', window.scrollY > 280); };
  window.addEventListener('scroll', check, { passive: true });
  btn.addEventListener('click', function() {
    if (window.lenis) {
      window.lenis.scrollTo(0, { duration: 1.4 });
    } else {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  });
  check();
})();


// ── Newsletter subscription logic ──────────────────────────
function handleSubscribe(e) {
  e.preventDefault();
  var emailInput = document.getElementById('newsletterEmail');
  var feedback = document.getElementById('newsletterFeedback');
  var form = document.getElementById('newsletterForm');
  var btn = form.querySelector('button');
  var email = emailInput.value.trim();

  if (!email) return;

  btn.disabled = true;
  feedback.className = 'newsletter-feedback';
  feedback.textContent = '';

  window.db.collection('subscribers').doc(email.toLowerCase()).set({
    email: email.toLowerCase(),
    subscribedAt: firebase.firestore.FieldValue.serverTimestamp(),
    status: 'active'
  })
  .then(function() {
    form.classList.add('success');
    emailInput.disabled = true;
    feedback.className = 'newsletter-feedback success';
    feedback.textContent = '<?php echo $langCode === "de" ? "Erfolgreich abonniert!" : "Successfully subscribed!"; ?>';
  })
  .catch(function(error) {
    btn.disabled = false;
    feedback.className = 'newsletter-feedback error';
    feedback.textContent = '<?php echo $langCode === "de" ? "Fehler: " : "Error: "; ?>' + error.message;
  });
}

// ── Guest Modal Logic ──────────────────────────────────────
function openGuestModal() {
  var modal = document.getElementById('guestFavModal');
  if (modal) {
    modal.classList.add('open');
    modal.setAttribute('aria-hidden', 'false');
    document.body.style.overflow = 'hidden';
  }
}

function closeGuestModal() {
  var modal = document.getElementById('guestFavModal');
  if (modal) {
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
  }
}

// Close guest modal if clicking backdrop
document.addEventListener('click', function(e) {
  var modal = document.getElementById('guestFavModal');
  if (modal && e.target === modal) {
    closeGuestModal();
  }
});

// ── Favorites Toggle & Management ───────────────────────────
var currentUser = null;
var userFavSlugs = new Set();

function syncFavorites(uid) {
  window.db.collection('user_favorites').where('userId', '==', uid).get()
    .then(function(snapshot) {
      userFavSlugs.clear();
      snapshot.forEach(function(doc) {
        userFavSlugs.add(doc.data().recipeSlug);
      });
      updateHeartStates();
    })
    .catch(function(err) {
      console.error("Error syncing favorites: ", err);
    });
}

function clearFavorites() {
  userFavSlugs.clear();
  updateHeartStates();
}

function updateHeartStates() {
  document.querySelectorAll('.btn-favorite').forEach(function(btn) {
    var slug = btn.getAttribute('data-slug');
    if (userFavSlugs.has(slug)) {
      btn.classList.add('active');
    } else {
      btn.classList.remove('active');
    }
  });
}

function toggleFavorite(slug, btn) {
  if (!currentUser) {
    openGuestModal();
    return;
  }

  var docId = currentUser.uid + '_' + slug;
  var docRef = window.db.collection('user_favorites').doc(docId);

  if (userFavSlugs.has(slug)) {
    // Optimistic UI update
    userFavSlugs.delete(slug);
    btn.classList.remove('active');
    
    docRef.delete()
      .catch(function(err) {
        console.error("Error removing favorite: ", err);
        // Rollback
        userFavSlugs.add(slug);
        btn.classList.add('active');
      });
  } else {
    // Optimistic UI update
    userFavSlugs.add(slug);
    btn.classList.add('active');

    docRef.set({
      userId: currentUser.uid,
      recipeSlug: slug,
      createdAt: firebase.firestore.FieldValue.serverTimestamp()
    })
    .catch(function(err) {
      console.error("Error adding favorite: ", err);
      // Rollback
      userFavSlugs.delete(slug);
      btn.classList.remove('active');
    });
  }
}

// Hook up event listeners to all favorite buttons dynamically
document.addEventListener('click', function(e) {
  var btn = e.target.closest('.btn-favorite');
  if (btn) {
    var slug = btn.getAttribute('data-slug');
    if (slug) {
      toggleFavorite(slug, btn);
    }
  }
});

// Setup Auth state observer for favorites
window.addEventListener('DOMContentLoaded', function() {
  if (window.auth) {
    window.auth.onAuthStateChanged(function(user) {
      currentUser = user;
      if (user) {
        syncFavorites(user.uid);
      } else {
        clearFavorites();
      }
    });
  }
});
})();
</script>

<!-- Guest Favoriting Prompt Modal -->
<div class="guest-modal-backdrop" id="guestFavModal" aria-hidden="true" role="dialog">
  <div class="guest-modal-card">
    <button class="guest-modal-close" onclick="closeGuestModal()" aria-label="Close modal">×</button>
    <div class="guest-modal-icon">❤️</div>
    <h3><?php echo $langCode === 'de' ? 'Lieblingsrezept speichern' : 'Save your favorite recipe'; ?></h3>
    <p><?php echo $langCode === 'de' ? 'Erstelle ein kostenloses Konto oder melde dich an, um Rezepte in deinen Favoriten zu speichern und deine Ernährungsziele zu verwalten.' : 'Create a free account or login to save recipes to your favorites and manage your dietary goals.'; ?></p>
    <div class="guest-modal-actions">
      <a class="btn-reveal" href="/login.php<?php echo $langSuffix; ?>">
        <span class="btn-reveal-text"><?php echo $langCode === 'de' ? 'Jetzt Anmelden' : 'Login / Register'; ?></span>
        <span class="btn-reveal-arrow">→</span>
      </a>
      <button class="underline-link" onclick="closeGuestModal()"><?php echo $langCode === 'de' ? 'Später' : 'Maybe later'; ?></button>
    </div>
  </div>
</div>

</body>
</html>
