/* ===== Base ===== */
:root{
  --bg:#fff;
  --text:#111;
  --muted:#6b6b6b;
  --line:#ececec;
  --primary:#d54f21;
  --primary-hover:#bf431a;
  --radius:16px;
  --container:1100px;
}

*{box-sizing:border-box}
html,body{
  margin:0;
  background:var(--bg);
  color:var(--text);
  font:16px/1.5 "Inter", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
}

.container{max-width:var(--container);margin-inline:auto;padding:0 20px}
.muted{color:var(--muted)}

/* Skip to content (a11y) */
.skip-link{position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden}
.skip-link:focus{left:16px;top:12px;width:auto;height:auto;background:#111;color:#fff;padding:8px 12px;border-radius:8px;z-index:1000}

/* ===== Header (unique) ===== */
.site-header{position:sticky;top:0;background:#fff;border-bottom:1px solid #eee;z-index:50}
.header-inner{display:flex;align-items:center;justify-content:space-between;gap:16px;height:72px}
.logo{display:flex;align-items:center;gap:10px;text-decoration:none;color:#111}
.logo img{border-radius:8px}
.logo-text{font-weight:800;letter-spacing:.4px}

.main-nav{display:flex;gap:28px;align-items:center}
.main-nav a{color:#333;text-decoration:none;font-weight:500}
.main-nav a[aria-current="page"]{color:#000;font-weight:700}

/* Burger */
.nav-toggle{display:none;border:0;background:#fff;font-size:22px;padding:8px;border-radius:8px}
@media (max-width:900px){
  .nav-toggle{display:inline-block}
  .main-nav{position:absolute;inset:72px 0 auto 0;background:#fff;border-bottom:1px solid #eee;
            display:none;flex-direction:column;padding:12px 20px}
  .main-nav.is-open{display:flex}
}

/* ===== Hero ===== */
.hero{background:linear-gradient(#fff,#fbf8f5);border-bottom:1px solid var(--line)}
.hero__inner{padding:48px 0 32px}
.hero__text h1{font-size:clamp(36px,6vw,64px);line-height:1.02;letter-spacing:-.4px;margin:0 0 10px}
.hero__text p{color:var(--muted);max-width:600px;margin:0 0 24px}
.btn{display:inline-block;padding:14px 22px;border-radius:14px;text-decoration:none;font-weight:600;border:1px solid transparent}
.btn--primary{background:var(--primary);color:#fff}
.btn--primary:hover{background:var(--primary-hover)}
.btn--ghost{background:#fff;border-color:var(--line);color:#222}

/* ===== Layout 2 colonnes ===== */
.layout{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(280px,1fr);gap:40px;padding:36px 0}
@media (max-width:960px){ .layout{grid-template-columns:1fr;gap:22px} }
.layout__side{position:relative}
@media (min-width:981px){ .layout__side{position:sticky;top:96px;align-self:start} }

/* ===== Sections ===== */
.section{margin-bottom:40px}
.section h2{font-size:26px;margin:0 0 14px}

/* ===== Cards (recettes) ===== */
.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:20px}
@media (max-width:960px){ .cards{grid-template-columns:repeat(2,1fr)} }
@media (max-width:640px){ .cards{grid-template-columns:1fr} }

.card{border:1px solid var(--line);border-radius:18px;background:#fff;overflow:hidden;display:block;
      color:inherit;text-decoration:none;box-shadow:0 2px 12px rgba(17,17,17,.04)}
.card__img{width:100%;height:180px;object-fit:cover;display:block;background:#f3f3f3}
.card--featured .card__img{height:280px;border-bottom:1px solid var(--line)}
.card--compact .card__img{height:132px}
.card__body{padding:16px 18px}
.card__title{font-size:21px;margin:0 0 6px;font-weight:700}

/* Ratings */
.rating{display:flex;gap:8px;align-items:center}
.rating__stars{font-size:16px;color:#f5a000}
.rating__num{font-size:14px;color:#555}

/* ===== Sidebar ===== */
.asidecard{border:1px solid var(--line);border-radius:22px;padding:20px 18px;background:#fff;margin-bottom:22px}
.asidecard h3{margin:0 0 12px;font-size:22px}
.form label{display:block;font-size:14px;color:#444;margin-bottom:8px}
.form input,.form textarea{width:100%;border:1px solid #e9e9e9;border-radius:14px;padding:12px;margin:6px 0 12px;background:#fff;font-size:15px}
.form input::placeholder,.form textarea::placeholder{color:#a3a3a3}
.uploadfake{margin:6px 0 12px}
.chefs{list-style:none;margin:4px 0 0;padding:0}
.chef{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:12px;padding:12px 4px;border-bottom:1px solid var(--line)}
.chef:last-child{border-bottom:0}
.chef__avatar{width:36px;height:36px;border-radius:50%;object-fit:cover;background:#eee}
.chef__name{font-weight:600}
.chef__rank{font-weight:700;color:#222}

/* ===== Footer ===== */
.footer{margin-top:28px;background:#fafafa;border-top:1px solid var(--line)}
.footer .container{padding:16px 20px;color:#777;font-size:14px}

/* ===== Recipe page ===== */
.recipe-hero{background:linear-gradient(#fff,#faf8f6);border-bottom:1px solid var(--line)}
.recipe-hero__inner{display:grid;grid-template-columns:1.3fr 1fr;gap:28px;align-items:center;padding:32px 0}
@media (max-width:960px){ .recipe-hero__inner{grid-template-columns:1fr} }
.recipe-hero__text .crumb{color:#666;text-decoration:none}
.recipe-hero__text .crumb:hover{color:#111}
.recipe-title{font-size:44px;line-height:1.05;margin:6px 0 8px}
.recipe-meta{display:flex;align-items:center;gap:10px;color:#666}
.meta__avatar{width:28px;height:28px;border-radius:50%;object-fit:cover;background:#eee}
.meta__sep{opacity:.6}
.recipe-excerpt{color:var(--muted);max-width:720px}
.recipe-hero__img{width:100%;height:340px;object-fit:cover;border-radius:16px;border:1px solid var(--line);background:#f3f3f3}

.ratebox{display:flex;align-items:center;gap:6px;margin-top:10px}
.ratebox__star{border:0;background:none;font-size:22px;cursor:pointer;line-height:1;color:#f5a000;padding:6px 4px;border-radius:8px}
.ratebox__star:hover{background:rgba(245,160,0,.08)}
.ratebox__hint{margin-left:8px}

.card--soft{border-radius:16px;border:1px solid var(--line);padding:18px}
.list{margin:0;padding-left:18px}
.list--ingredients li{margin:6px 0}
.list--steps li{margin:10px 0}
.prose{white-space:pre-wrap}
.layout__side .cards .card__img{height:90px}


/* Filtres liste recettes */
.filters{display:grid;grid-template-columns:1fr auto;gap:12px;align-items:center}
.filters__input{border:1px solid #e9e9e9;border-radius:14px;padding:12px 14px;font-size:15px}
.filters__tabs{display:flex;gap:10px;flex-wrap:wrap}
.filters__tab{border:1px solid var(--line);background:#fff;padding:10px 12px;border-radius:12px;
              text-decoration:none;color:#333;font-weight:500}
.filters__tab.is-active{border-color:#ffd7c7;background:#fff3ec}
.filters__submit{justify-self:start}
@media (max-width:720px){ .filters{grid-template-columns:1fr} }

/* Pagination */
.pagination{display:flex;gap:8px;align-items:center;justify-content:center;margin:26px 0 6px}
.page{display:inline-flex;align-items:center;justify-content:center;min-width:38px;height:38px;
      padding:0 10px;border:1px solid var(--line);border-radius:10px;text-decoration:none;color:#333}
.page:is(:hover,.is-current){background:#fff3ec;border-color:#ffd7c7}
.page.is-current{font-weight:700}
.page.is-disabled{opacity:.4;pointer-events:none}
.page.gap{border:none;min-width:auto;padding:0;background:transparent}

/* Stats bar (recettes.php) */
.statsbar{
  display:flex; align-items:center; gap:10px;
  padding:10px 0 6px; color:#444; font-size:15px;
}
.statsbar__item strong{font-weight:700; color:#111}
.statsbar__sep{opacity:.45}
@media (max-width:640px){
  .statsbar{font-size:14px}
}

.list--steps {
  list-style: none;
  counter-reset: step;
  padding-left: 0;
}
.list--steps li {
  counter-increment: step;
  margin: 10px 0;
}
.list--steps li::before {
  content: counter(step) ". ";
  font-weight: 600;
  color: #d54f21;
}

.list--steps li {
  margin: 10px 0;
  line-height: 1.6;
}
.list--steps li::marker {
  color: #d54f21;
  font-weight: 700;
}


/* numérotation des étapes et meilleure lisibilité */
.list--steps li { margin:10px 0; line-height:1.65; }
.list--steps li::marker { color:#d54f21; font-weight:700; }

/* bloc de notation */
.ratebox{display:flex;align-items:center;gap:6px;margin-top:12px}
.ratebox__star{border:0;background:none;font-size:22px;cursor:pointer;line-height:1;color:#f5a000;padding:6px 4px;border-radius:8px}
.ratebox__star:hover{background:rgba(245,160,0,.08)}
.ratebox__star:disabled{opacity:.45;cursor:not-allowed}

.sharebar{display:flex;gap:10px;margin-top:10px}
.sharebar__btn{padding:10px 12px;border-radius:12px;border:1px solid var(--line)}

/* Toast */
.toast{
  position:fixed;left:50%;bottom:24px;transform:translateX(-50%) translateY(16px);
  background:#111;color:#fff;padding:10px 14px;border-radius:10px;
  opacity:0;pointer-events:none;transition:opacity .2s, transform .2s; z-index:1000;
  font-size:14px; box-shadow:0 4px 16px rgba(0,0,0,.18);
}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}

<?php
declare(strict_types=1);
session_start();
require __DIR__ . '/config/db.php';
include __DIR__ . '/partials/header.php';

/* ---------------- Helpers ---------------- */
function slugify(string $text): string {
  $txt = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);
  $txt = preg_replace('~[^\pL\d]+~u', '-', $txt);
  $txt = preg_replace('~[^-\w]+~', '', $txt);
  $txt = trim($txt, '-');
  $txt = preg_replace('~-+~', '-', $txt);
  $txt = strtolower($txt);
  return $txt ?: uniqid('recette-');
}
function flash($msg=null,$type='info'){
  if($msg!==null){ $_SESSION['flash']=['m'=>$msg,'t'=>$type]; return; }
  if(empty($_SESSION['flash'])) return '';
  [$m,$t]=[$_SESSION['flash']['m'],$_SESSION['flash']['t']];
  unset($_SESSION['flash']);
  $colors=['success'=>'#16a34a','error'=>'#dc2626','info'=>'#2563eb'];
  return '<div style="margin:12px 0;padding:10px 12px;border-radius:10px;color:#fff;background:'.$colors[$t].';">'.$m.'</div>';
}

/* CSRF + CAPTCHA + rate limit simple */
if (empty($_SESSION['csrf']))     $_SESSION['csrf']     = bin2hex(random_bytes(16));
if (empty($_SESSION['last_post'])) $_SESSION['last_post'] = 0;

function make_captcha(): array {
  $a = random_int(1,9); $b = random_int(1,9);
  $_SESSION['captcha'] = $a + $b;
  return [$a,$b];
}
[$capA,$capB] = make_captcha();

/* ---------------- Handle POST ---------------- */
if ($_SERVER['REQUEST_METHOD']==='POST') {
  try{
    // Anti-refresh (10s)
    if (time() - (int)$_SESSION['last_post'] < 10) {
      throw new Exception("Trop de tentatives. Réessayez dans quelques secondes.");
    }
    $_SESSION['last_post'] = time();

    // CSRF
    if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
      throw new Exception("Session expirée. Merci de recharger la page.");
    }

    // Honeypot (champ caché)
    if (!empty($_POST['website'])) {
      throw new Exception("Détection anti-bot.");
    }

    // CAPTCHA
    $captchaOk = isset($_POST['captcha']) && (int)$_POST['captcha'] === (int)($_SESSION['captcha'] ?? -1);
    if (!$captchaOk) {
      throw new Exception("Captcha invalide.");
    }

    // Champs
    $title = trim($_POST['title'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $ingredients = trim($_POST['ingredients'] ?? '');
    $steps = trim($_POST['steps'] ?? '');

    if ($title==='' || $ingredients==='' || $steps==='') {
      throw new Exception("Merci de renseigner au minimum le titre, les ingrédients et les étapes.");
    }

    // Slug unique
    $slug = slugify($title);
    $check = $pdo->prepare("SELECT COUNT(*) FROM recipes WHERE slug=:s");
    $i=0; $candidate=$slug;
    do{
      $check->execute([':s'=>$candidate]);
      $exists = (int)$check->fetchColumn() > 0;
      if($exists) $candidate = $slug.'-'.(++$i);
    }while($exists);
    $slug = $candidate;

    // Upload image (facultatif)
    $coverPath = null;
    if (!empty($_FILES['cover']['name']) && $_FILES['cover']['error']===UPLOAD_ERR_OK) {
      $tmp = $_FILES['cover']['tmp_name'];
      $size = (int)$_FILES['cover']['size'];
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mime = finfo_file($finfo, $tmp) ?: '';
      finfo_close($finfo);

      if ($size > 3*1024*1024) throw new Exception("Image trop lourde (max 3 Mo).");
      $allowed = ['image/jpeg'=>'.jpg','image/png'=>'.png','image/webp'=>'.webp'];
      if (!isset($allowed[$mime])) throw new Exception("Format image non supporté (jpg, png, webp).");

      $dir = __DIR__ . '/assets/recettes';
      if (!is_dir($dir)) mkdir($dir, 0775, true);
      $fname = $slug . '-' . time() . $allowed[$mime];
      $dest = $dir . '/' . $fname;
      if (!move_uploaded_file($tmp, $dest)) throw new Exception("Échec de l’upload de l’image.");
      $coverPath = '/assets/recettes/' . $fname;
    }

    // On attribue la recette au user #1 (admin) par défaut.
    // (Tu pourras changer pour un vrai système de comptes plus tard)
    $userId = 1;

    // Insertion en brouillon (modération)
    $sql = "INSERT INTO recipes
            (user_id,title,slug,category,ingredients,steps,cover,is_featured,status,created_at,updated_at)
            VALUES (:uid,:title,:slug,:category,:ingredients,:steps,:cover,0,'draft',NOW(),NOW())";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
      ':uid'=>$userId,
      ':title'=>$title,
      ':slug'=>$slug,
      ':category'=>$category ?: null,
      ':ingredients'=>$ingredients,
      ':steps'=>$steps,
      ':cover'=>$coverPath
    ]);

    flash("Merci ! Votre recette a été soumise et sera publiée après validation 👌", 'success');
    // On régénère un nouveau captcha pour le prochain affichage
    [$capA,$capB] = make_captcha();
  }catch(Throwable $e){
    flash($e->getMessage(), 'error');
    // régénérer un captcha en cas d'erreur
    [$capA,$capB] = make_captcha();
  }
}
?>

.hero--submit {
  background: linear-gradient(180deg, #fffaf6 0%, #ffe6d8 100%);
  border-bottom: 1px solid #f0d0b6;
}
.hero--submit .hero__text h1 {
  color: #b63a12;
}
.hero--submit .hero__text p {
  color: #743112;
}

.hero--submit {
  background: #fff3ea; /* fond doux */
  border-bottom: 1px solid #f0d0b6;
}

.hero--submit .hero__text h1 {
  color: #111; /* noir */
}

.hero--submit .hero__text p {
  color: #333; /* gris foncé */
}


/* ===== Footer — Thème Option B (crème moderne, terre cuite) ===== */
.site-footer {
  background: linear-gradient(180deg, #f8eee7 0%, #f2dfd3 100%);
  color: #3d2a1a;
  border-top: 1px solid #e4cdbd;
  text-align: center;
  padding: 32px 20px;
  font-size: 15px;
  font-family: "Inter", system-ui, sans-serif;
}

.site-footer p {
  margin: 0 0 10px;
}

.site-footer .links {
  margin-top: 8px;
}

.site-footer a,
.site-footer a:visited {
  color: #c46033;                /* terre cuite */
  text-decoration: none;
  font-weight: 600;
  transition: color .2s ease;
}

.site-footer a:hover {
  color: #9c4117;                /* terre cuite foncé au survol */
  text-decoration: underline;
}

/* Bonus : ligne de séparation douce au-dessus du footer */
body::after {
  content: "";
  display: block;
  height: 1px;
  background: linear-gradient(to right, transparent, #e6d4c6, transparent);
}


/* ===== Footer — Thème Option B (crème moderne + ombre douce) ===== */
.site-footer {
  background: linear-gradient(180deg, #f8eee7 0%, #f2dfd3 100%); /* fond crème rosé */
  color: #3d2a1a;                       /* brun doux */
  border-top: 1px solid #e4cdbd;
  text-align: center;
  padding: 32px 20px;
  font-size: 15px;
  font-family: "Inter", system-ui, sans-serif;
  box-shadow: 0 -6px 16px rgba(205, 180, 155, 0.25); /* ombre légère vers le haut */
}

.site-footer p {
  margin: 0 0 10px;
}

.site-footer .links {
  margin-top: 8px;
}

.site-footer a,
.site-footer a:visited {
  color: #c46033;                /* terre cuite */
  text-decoration: none;
  font-weight: 600;
  transition: color .25s ease, text-decoration .25s ease;
}

.site-footer a:hover {
  color: #9c4117;                /* terre cuite foncé */
  text-decoration: underline;
}

/* Ligne de transition douce entre le contenu et le footer */
body::after {
  content: "";
  display: block;
  height: 1px;
  background: linear-gradient(to right, transparent, #e6d4c6, transparent);
}
