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

$lang = (isset($_GET['lang']) && strtolower($_GET['lang']) === 'de') ? 'de' : 'en';
$copy = [
    'en' => [
        'not_found'     => 'Recipe not found',
        'not_found_sub' => 'Try searching for something else.',
        'back_home'     => '← Back to all recipes',
        'nutrition'     => 'Nutrition',
        'calories'      => 'Calories',
        'protein'       => 'Protein',
        'carbs'         => 'Carbs',
        'fat'           => 'Fat',
        'ingredients'   => 'Ingredients',
        'utensils'      => 'Utensils',
        'steps'         => 'Steps',
        'also_tasty'    => 'Also tasty',
        'more_dishes'   => 'More dishes to keep you cooking.',
        'prep'          => 'Prep',
        'cook'          => 'Cook',
        'total'         => 'Total',
        'serves'        => 'Serves',
        'level'         => 'Level',
    ],
    'de' => [
        'not_found'     => 'Rezept nicht gefunden',
        'not_found_sub' => 'Versuche eine andere Suche.',
        'back_home'     => '← Zurück zu allen Rezepten',
        'nutrition'     => 'Nährwerte',
        'calories'      => 'Kalorien',
        'protein'       => 'Protein',
        'carbs'         => 'Kohlenhydrate',
        'fat'           => 'Fett',
        'ingredients'   => 'Zutaten',
        'utensils'      => 'Küchenwerkzeug',
        'steps'         => 'Schritte',
        'also_tasty'    => 'Auch lecker',
        'more_dishes'   => 'Noch mehr zum Nachkochen.',
        'prep'          => 'Vorbereitung',
        'cook'          => 'Garen',
        'total'         => 'Gesamt',
        'serves'        => 'Portionen',
        'level'         => 'Level',
    ],
];
$t = $copy[$lang];

$allRecipes       = load_recipes();
$slug             = isset($_GET['slug']) ? trim($_GET['slug']) : '';
$recipeRaw        = $slug ? find_recipe_by_slug($allRecipes, $slug) : null;
$recipe           = $recipeRaw ? localize_recipe($recipeRaw, $lang) : null;
$allRecipesLocal  = localize_recipes($allRecipes, $lang);

$langSwitchLabel = $lang === 'de' ? 'EN' : 'DE';
$langSwitchHref  = lang_url($lang === 'de' ? 'en' : 'de');

if (!$recipe) {
    http_response_code(404);
    $pageTitle   = $t['not_found'] . ' | FlixCooks';
    $description = $t['not_found_sub'];
    include __DIR__ . '/partials/head.php';
    include __DIR__ . '/partials/header.php';
    ?>
    <main class="not-found">
      <h1><?php echo e($t['not_found']); ?></h1>
      <p><?php echo e($t['not_found_sub']); ?></p>
      <a class="btn-reveal" href="/index.php?lang=<?php echo e($lang); ?>#recipes-start">
        <span class="btn-reveal-text"><?php echo e($t['back_home']); ?></span>
        <span class="btn-reveal-arrow">→</span>
      </a>
    </main>
    <?php
    include __DIR__ . '/partials/footer.php';
    exit;
}

$pageTitle   = e($recipe['title']) . ' | FlixCooks';
$description = $recipe['description'] ?? '';
include __DIR__ . '/partials/head.php';
include __DIR__ . '/partials/header.php';
?>

<article class="recipe">
  <div class="recipe__hero">
    <img src="<?php echo e($recipe['hero']); ?>" alt="<?php echo e($recipe['title']); ?>">
    <div class="recipe__hero__copy">
      <?php if (!empty($recipe['category'])): ?>
        <p class="pill pill--gold"><?php echo e($recipe['category']); ?></p>
      <?php endif; ?>
      <div class="recipe__title-row">
        <h1><?php echo e($recipe['title']); ?></h1>
        <button class="btn-favorite btn-favorite--large" data-slug="<?php echo e($recipe['slug']); ?>" aria-label="Save to favorites">
          <svg viewBox="0 0 24 24" stroke="currentColor" fill="none">
            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
          </svg>
        </button>
      </div>
      <p class="lede"><?php echo e($recipe['description']); ?></p>
      <div class="meta meta--row">
        <span><?php echo e($t['prep']); ?>: <?php echo format_minutes((int)$recipe['prep_time']); ?></span>
        <span><?php echo e($t['cook']); ?>: <?php echo format_minutes((int)$recipe['cook_time']); ?></span>
        <span><?php echo e($t['total']); ?>: <?php echo format_minutes((int)$recipe['total_time']); ?></span>
        <span><?php echo e($t['serves']); ?>: <?php echo e($recipe['servings']); ?></span>
        <span><?php echo e($t['level']); ?>: <?php echo e($recipe['difficulty']); ?></span>
      </div>
      <a class="btn-reveal" href="/index.php?lang=<?php echo e($lang); ?>#recipes-start">
        <span class="btn-reveal-text"><?php echo e($t['back_home']); ?></span>
        <span class="btn-reveal-arrow">←</span>
      </a>
    </div>
  </div>

  <div class="recipe__body">

    <?php if (isset($recipe['nutrition']) && ($recipe['nutrition']['calories'] > 0 || $recipe['nutrition']['protein'] > 0 || $recipe['nutrition']['carbs'] > 0 || $recipe['nutrition']['fat'] > 0)): ?>
    <section class="panel reveal-target" id="nutrition-panel">
      <h2><?php echo e($t['nutrition']); ?></h2>
      <div class="g-row nutrition-widget">
        <?php 
          $nutri = $recipe['nutrition'];
          $macros = [
            ['label' => $t['calories'], 'value' => $nutri['calories'], 'unit' => 'kcal', 'pct' => min(100, round(($nutri['calories']/2000)*100))],
            ['label' => $t['protein'], 'value' => $nutri['protein'], 'unit' => 'g', 'pct' => min(100, round(($nutri['protein']/50)*100))],
            ['label' => $t['carbs'], 'value' => $nutri['carbs'], 'unit' => 'g', 'pct' => min(100, round(($nutri['carbs']/260)*100))],
            ['label' => $t['fat'], 'value' => $nutri['fat'], 'unit' => 'g', 'pct' => min(100, round(($nutri['fat']/70)*100))]
          ];
        ?>
        <?php foreach ($macros as $m): ?>
          <div class="g-col nutrition-item">
            <div class="nutrition-item__header">
              <span class="nutrition-label"><?php echo e($m['label']); ?></span>
              <span class="nutrition-value"><?php echo e($m['value']); ?><?php echo $m['unit']; ?></span>
            </div>
            <div class="nutrition-bar">
              <div class="nutrition-fill" data-width="<?php echo $m['pct']; ?>%" style="width: 0;"></div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>

    <section class="panel">
      <h2><?php echo e($t['ingredients']); ?></h2>
      <ul class="ingredients">
        <?php foreach ($recipe['ingredients'] as $item): ?>
          <li><?php echo e($item); ?></li>
        <?php endforeach; ?>
      </ul>
    </section>

    <?php if (!empty($recipe['utensils'])): ?>
    <section class="panel">
      <h2><?php echo e($t['utensils']); ?></h2>
      <ul class="ingredients">
        <?php foreach ($recipe['utensils'] as $item): ?>
          <li><?php echo e($item); ?></li>
        <?php endforeach; ?>
      </ul>
    </section>
    <?php endif; ?>

    <section class="panel">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h2 style="margin: 0;"><?php echo e($t['steps']); ?></h2>
        <button id="btn-start-cooking" class="btn-reveal">
          <span class="btn-reveal-text"><?php echo $lang === 'de' ? 'Kochmodus starten' : 'Start Cooking Mode'; ?></span>
        </button>
      </div>
      <ol class="steps">
        <?php foreach ($recipe['steps'] as $step): ?>
          <li><?php echo e($step); ?></li>
        <?php endforeach; ?>
      </ol>
    </section>
  </div>

  <section class="more">
    <div class="section-header section-header--stack">
      <p class="eyebrow"><?php echo e($t['also_tasty']); ?></p>
      <h3><?php echo e($t['more_dishes']); ?></h3>
    </div>
    <div class="grid grid--tight">
      <?php foreach ($allRecipesLocal as $other): ?>
        <?php if ($other['slug'] === $recipe['slug'] || !empty($other['coming_soon'])) continue; ?>
        <article class="card card--bare reveal-target">
          <a href="/recipe.php?<?php echo http_build_query(['slug' => $other['slug'], 'lang' => $lang]); ?>" class="card__image">
            <img src="<?php echo e($other['hero']); ?>" alt="<?php echo e($other['title']); ?>" loading="lazy">
            <button class="btn-favorite" data-slug="<?php echo e($other['slug']); ?>" aria-label="Save to favorites" onclick="event.preventDefault(); event.stopPropagation();">
              <svg viewBox="0 0 24 24" stroke="currentColor" fill="none">
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
              </svg>
            </button>
          </a>
          <div class="card__body">
            <h4><a href="/recipe.php?<?php echo http_build_query(['slug' => $other['slug'], 'lang' => $lang]); ?>"><?php echo e($other['title']); ?></a></h4>
            <p><?php echo e($other['description']); ?></p>
            <div class="meta">
              <span>⏱ <?php echo format_minutes((int)($other['total_time'] ?? 0)); ?></span>
              <span>🙂 <?php echo e($other['difficulty']); ?></span>
            </div>
          </div>
        </article>
      <?php endforeach; ?>
    </div>
  </section>
</article>

<?php if (!empty($recipe['steps'])): ?>
<div id="cooking-overlay" class="cooking-overlay" hidden>
  <div class="cooking-slider" id="cooking-slider">
    <?php foreach ($recipe['steps'] as $idx => $stepText): 
      $vid = $recipe['step_videos'][$idx] ?? '';
      $timer = (int)($recipe['step_timers'][$idx] ?? 0);
    ?>
    <div class="cooking-slide <?php echo $idx === 0 ? 'active' : ''; ?>" data-index="<?php echo $idx; ?>">
      <?php if ($vid): ?>
        <video class="cooking-video" src="<?php echo e($vid); ?>" loop muted playsinline <?php echo $idx === 0 ? 'autoplay' : ''; ?>></video>
      <?php endif; ?>
      <div class="cooking-content">
        <p class="cooking-step-indicator"><?php echo $lang === 'de' ? 'Schritt' : 'Step'; ?> <?php echo $idx + 1; ?> / <?php echo count($recipe['steps']); ?></p>
        <h3 class="cooking-step-text"><?php echo e($stepText); ?></h3>
        
        <?php if ($timer > 0): ?>
          <div class="cooking-timer" data-time="<?php echo $timer * 60; ?>">
            <span class="timer-display"><?php echo sprintf('%02d:00', $timer); ?></span>
            <div class="timer-controls">
              <button class="btn-timer start"><?php echo $lang === 'de' ? 'Start' : 'Start'; ?></button>
              <button class="btn-timer pause" hidden><?php echo $lang === 'de' ? 'Pause' : 'Pause'; ?></button>
              <button class="btn-timer reset"><?php echo $lang === 'de' ? 'Reset' : 'Reset'; ?></button>
            </div>
          </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  
  <div class="cooking-nav">
    <button id="btn-prev-step" class="btn-circle" disabled>←</button>
    <button id="btn-next-step" class="btn-circle">→</button>
    <button id="btn-close-cooking" class="btn-circle" style="background: rgba(220, 38, 38, 0.5); border-color: rgba(220, 38, 38, 0.8);" aria-label="Close">
      <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2.5" fill="none"><path d="M18 6L6 18M6 6l12 12"></path></svg>
    </button>
  </div>
</div>
<?php endif; ?>

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

<script>
// Scroll reveal on recipe page
if ('IntersectionObserver' in window) {
  var obs = new IntersectionObserver(function(entries) {
    entries.forEach(function(e) {
      if (e.isIntersecting) { 
        e.target.classList.add('revealed'); 
        obs.unobserve(e.target); 
        
        // Trigger nutrition bar animations if this is the nutrition panel
        if (e.target.id === 'nutrition-panel') {
          e.target.querySelectorAll('.nutrition-fill').forEach(function(fill) {
            fill.style.width = fill.getAttribute('data-width');
          });
        }
      }
    });
  }, { threshold: 0.08 });
  document.querySelectorAll('.reveal-target').forEach(function(el) { obs.observe(el); });
}
// Lenis init for recipe page
if (typeof Lenis !== 'undefined') {
  var lenis = new Lenis({ duration: 1.2, smooth: true, smoothTouch: false });
  window.lenis = lenis;
  function raf(time) { lenis.raf(time); requestAnimationFrame(raf); }
  requestAnimationFrame(raf);
}

// Cooking Mode Logic
document.addEventListener('DOMContentLoaded', () => {
  const btnStart = document.getElementById('btn-start-cooking');
  const btnClose = document.getElementById('btn-close-cooking');
  const overlay = document.getElementById('cooking-overlay');
  
  if (!btnStart || !overlay) return;

  const slides = overlay.querySelectorAll('.cooking-slide');
  const btnPrev = document.getElementById('btn-prev-step');
  const btnNext = document.getElementById('btn-next-step');
  let currentSlide = 0;
  
  // Audio context for timer
  const beep = new Audio('data:audio/mp3;base64,//NExAAAAANIAAAAAExBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq'); // Fallback empty if needed, or simple beep

  function updateSlider() {
    slides.forEach((slide, idx) => {
      if (idx === currentSlide) {
        slide.classList.add('active');
        const vid = slide.querySelector('video');
        if (vid) vid.play().catch(e=>console.log(e));
      } else {
        slide.classList.remove('active');
        const vid = slide.querySelector('video');
        if (vid) { vid.pause(); vid.currentTime = 0; }
      }
    });
    btnPrev.disabled = currentSlide === 0;
    btnNext.disabled = currentSlide === slides.length - 1;
  }

  btnStart.addEventListener('click', () => {
    overlay.hidden = false;
    // trigger clip-path animation by adding a class in next frame
    requestAnimationFrame(() => overlay.classList.add('is-open'));
    if (window.lenis) window.lenis.stop();
    updateSlider();
  });

  btnClose.addEventListener('click', () => {
    overlay.classList.remove('is-open');
    setTimeout(() => {
      overlay.hidden = true;
      if (window.lenis) window.lenis.start();
      slides.forEach(s => {
        const vid = s.querySelector('video');
        if(vid) vid.pause();
      });
    }, 600); // match transition duration
  });

  btnNext.addEventListener('click', () => {
    if (currentSlide < slides.length - 1) { currentSlide++; updateSlider(); }
  });
  
  btnPrev.addEventListener('click', () => {
    if (currentSlide > 0) { currentSlide--; updateSlider(); }
  });

  // Timers
  document.querySelectorAll('.cooking-timer').forEach(timerEl => {
    let time = parseInt(timerEl.dataset.time, 10);
    let initialTime = time;
    let interval = null;
    const display = timerEl.querySelector('.timer-display');
    const btnStartTimer = timerEl.querySelector('.start');
    const btnPauseTimer = timerEl.querySelector('.pause');
    const btnResetTimer = timerEl.querySelector('.reset');
    
    function updateDisplay() {
      const m = Math.floor(time / 60);
      const s = time % 60;
      display.textContent = `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
    }
    
    btnStartTimer.addEventListener('click', () => {
      btnStartTimer.hidden = true;
      btnPauseTimer.hidden = false;
      interval = setInterval(() => {
        if (time > 0) {
          time--;
          updateDisplay();
        } else {
          clearInterval(interval);
          btnPauseTimer.hidden = true;
          // Play a simple beep
          try {
            const ctx = new (window.AudioContext || window.webkitAudioContext)();
            const osc = ctx.createOscillator();
            osc.connect(ctx.destination);
            osc.start();
            setTimeout(() => osc.stop(), 500);
          } catch(e) {}
        }
      }, 1000);
    });
    
    btnPauseTimer.addEventListener('click', () => {
      clearInterval(interval);
      btnStartTimer.hidden = false;
      btnPauseTimer.hidden = true;
    });
    
    btnResetTimer.addEventListener('click', () => {
      clearInterval(interval);
      time = initialTime;
      updateDisplay();
      btnStartTimer.hidden = false;
      btnPauseTimer.hidden = true;
    });
  });
});
</script>
