<?php
require_once dirname(__DIR__) . '/inc/schema.php';
require_once __DIR__ . '/_layout.php';
init_schema();
$db = db();

$id = (int)($_GET['id'] ?? 0);
$flash = '';

if ($_SERVER['REQUEST_METHOD']==='POST' && csrf_check($_POST['csrf']??null)) {
    $titre     = trim($_POST['titre'] ?? '');
    $extrait   = trim($_POST['extrait'] ?? '');
    $contenu   = trim($_POST['contenu'] ?? '');
    // sécurité : retirer scripts/handlers, garder le HTML de mise en forme
    $contenu = preg_replace('#<script\b[^>]*>.*?</script>#is', '', $contenu);
    $contenu = preg_replace('#\son\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)#i', '', $contenu);
    // retirer un éventuel placeholder d'image resté (upload interrompu)
    $contenu = preg_replace('#<img[^>]*data-placeholder[^>]*>#i', '', $contenu);
    $contenu = preg_replace('#<img[^>]*src="data:image/svg\+xml[^"]*"[^>]*>#i', '', $contenu);
    // retirer la classe interne de sélection (éditeur)
    $contenu = preg_replace('/\s*\bimg-selected\b/', '', $contenu);
    $contenu = preg_replace('/\sclass="\s*"/', '', $contenu);
    $catId     = (int)($_POST['categorie_id'] ?? 0) ?: null;
    $imageId   = (int)($_POST['image_id'] ?? 0) ?: null;
    $statut    = ($_POST['statut'] ?? 'brouillon')==='publie' ? 'publie' : 'brouillon';
    $metaTitre = trim($_POST['meta_titre'] ?? '');
    $metaDesc  = trim($_POST['meta_desc'] ?? '');
    if ($id) {
        $db->prepare("UPDATE articles SET titre=?,extrait=?,contenu=?,categorie_id=?,image_id=?,statut=?,meta_titre=?,meta_desc=?,modifie_le=datetime('now') WHERE id=?")
           ->execute([$titre,$extrait,$contenu,$catId,$imageId,$statut,$metaTitre,$metaDesc,$id]);
        $flash = 'Modifications enregistrées.';
    }
}

$st = $db->prepare('SELECT * FROM articles WHERE id=?');
$st->execute([$id]);
$a = $st->fetch();
if (!$a) { layout_start('Article','articles'); echo '<div class="panel">Article introuvable. <a href="articles.php">Retour</a></div>'; layout_end(); exit; }

$cats = $db->query("SELECT id,nom FROM categories ORDER BY nom")->fetchAll();
// image actuelle
$imgUrl = '';
if (!empty($a['image_id'])) {
    $s2 = $db->prepare("SELECT url FROM medias WHERE id=?"); $s2->execute([$a['image_id']]);
    $imgUrl = $s2->fetchColumn() ?: '';
}

layout_start('Modifier : '.$a['titre'], 'articles');
$tok = csrf_token();
?>
<?php if($flash): ?><div class="panel" style="border-left:3px solid var(--ok)"><?= e($flash) ?>
  <?php if($a['statut']==='publie'): ?><a href="<?= SITE_URL ?>/articles/<?= e($a['slug']) ?>/" target="_blank" style="color:var(--blue);margin-left:1rem">Voir la page →</a><?php endif; ?>
</div><?php endif; ?>

<?php if(!empty($a['slug'])): ?>
<div class="edit-toplink">
  <a href="<?= SITE_URL ?>/articles/<?= e($a['slug']) ?>/?nocache=<?= time() ?>" target="_blank" rel="noopener" class="btn-voir-article">
    ↗ Voir l'article<?= $a['statut']!=='publie' ? ' (brouillon)' : '' ?>
  </a>
  <span class="edit-toplink-note">s'ouvre dans un nouvel onglet — pensez à actualiser (Ctrl+Maj+R) pour voir vos corrections</span>
</div>
<?php endif; ?>

<form method="post" class="panel">
  <input type="hidden" name="csrf" value="<?= e($tok) ?>">
  <input type="hidden" name="image_id" id="image_id" value="<?= (int)($a['image_id']??0) ?>">
  <div style="display:grid;grid-template-columns:1fr 300px;gap:2rem">
    <div>
      <label style="display:block;margin-bottom:1rem">
        <span class="lbl">Titre</span>
        <input type="text" name="titre" value="<?= e($a['titre']) ?>" style="width:100%;padding:.6rem;border:1px solid var(--line);border-radius:5px;font-size:1rem">
      </label>
      <label style="display:block;margin-bottom:1rem">
        <span class="lbl">Extrait (résumé court affiché dans la liste)</span>
        <textarea name="extrait" rows="2" style="width:100%;padding:.6rem;border:1px solid var(--line);border-radius:5px"><?= e($a['extrait']) ?></textarea>
      </label>
      <span class="lbl">Contenu de l'article</span>
      <div class="wysiwyg-toolbar">
        <button type="button" data-cmd="bold" title="Gras"><b>G</b></button>
        <button type="button" data-cmd="italic" title="Italique"><i>I</i></button>
        <span class="wt-sep"></span>
        <button type="button" data-cmd="formatBlock" data-val="h2" title="Titre">T</button>
        <button type="button" data-cmd="formatBlock" data-val="h3" title="Sous-titre">t</button>
        <button type="button" data-cmd="formatBlock" data-val="p" title="Paragraphe">¶</button>
        <span class="wt-sep"></span>
        <button type="button" data-cmd="insertUnorderedList" title="Liste à puces">•</button>
        <button type="button" data-cmd="insertOrderedList" title="Liste numérotée">1.</button>
        <span class="wt-sep"></span>
        <button type="button" data-cmd="justifyLeft" title="Gauche">⬅</button>
        <button type="button" data-cmd="justifyCenter" title="Centrer">⬌</button>
        <button type="button" data-cmd="justifyRight" title="Droite">➡</button>
        <span class="wt-sep"></span>
        <button type="button" data-cmd="createLink" title="Lien">🔗</button>
        <button type="button" id="btnInsertImg" title="Insérer une image">🖼 Image</button>
        <span class="wt-sep"></span>
        <span class="wt-colors" title="Couleur du texte">
          <button type="button" class="wtcolor" data-color="#20262b" style="background:#20262b" title="Encre"></button>
          <button type="button" class="wtcolor" data-color="#1f4e79" style="background:#1f4e79" title="Bleu"></button>
          <button type="button" class="wtcolor" data-color="#4f7d6e" style="background:#4f7d6e" title="Jade"></button>
          <button type="button" class="wtcolor" data-color="#b08d57" style="background:#b08d57" title="Or"></button>
          <label class="wtcolor-pick" title="Autre couleur"><input type="color" id="wysColorInput" value="#1f4e79"><span>🎨</span></label>
        </span>
        <span class="wt-sep"></span>
        <button type="button" data-cmd="removeFormat" title="Effacer la mise en forme">⌫</button>
      </div>
      <div id="wysiwyg" class="wysiwyg" contenteditable="true"><?= $a['contenu'] ?></div>
      <textarea name="contenu" id="contenuField" style="display:none"><?= e($a['contenu']) ?></textarea>
      <p class="note" style="font-size:.8rem;color:var(--ink2);margin-top:.4rem">Astuce : vous pouvez coller une image directement (Ctrl+V) dans l'éditeur.</p>
    </div>
    <div>
      <div class="panel" style="margin:0 0 1rem;background:var(--bg)">
        <label style="display:block;margin-bottom:1rem">
          <span class="lbl">Statut</span>
          <select name="statut" style="width:100%;padding:.5rem;border:1px solid var(--line);border-radius:5px">
            <option value="publie" <?= $a['statut']==='publie'?'selected':'' ?>>Publié</option>
            <option value="brouillon" <?= $a['statut']==='brouillon'?'selected':'' ?>>Brouillon</option>
          </select>
        </label>
        <label style="display:block">
          <span class="lbl">Catégorie</span>
          <select name="categorie_id" style="width:100%;padding:.5rem;border:1px solid var(--line);border-radius:5px">
            <option value="">— Aucune —</option>
            <?php foreach($cats as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= $a['categorie_id']==$c['id']?'selected':'' ?>><?= e($c['nom']) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
      </div>

      <div class="panel" style="margin:0 0 1rem;background:var(--bg)">
        <span class="lbl">Image à la une</span>
        <div id="imgPreview" style="margin:.5rem 0;border-radius:6px;overflow:hidden;aspect-ratio:16/10;background:#e6e1d6;display:flex;align-items:center;justify-content:center">
          <?php if($imgUrl): ?><img src="<?= SITE_URL ?>/<?= e($imgUrl) ?>" style="width:100%;height:100%;object-fit:cover"><?php else: ?><span style="color:#999;font-size:.85rem">Aucune image</span><?php endif; ?>
        </div>
        <button type="button" class="btn ghost sm" id="btnPickImg" style="width:100%">Choisir dans la médiathèque</button>
        <button type="button" class="btn ghost sm" id="btnUploadImg" style="width:100%;margin-top:.4rem">⬆ Téléverser une image</button>
        <input type="file" id="fileFeatured" accept="image/*" style="display:none">
        <button type="button" class="btn ghost sm" id="btnClearImg" style="width:100%;margin-top:.4rem;color:var(--err)">Retirer l'image</button>
      </div>

      <div class="panel" style="margin:0 0 1rem;background:var(--bg)">
        <div style="font-size:.82rem;color:var(--gold);letter-spacing:.1em;text-transform:uppercase;margin-bottom:.6rem">SEO</div>
        <label style="display:block;margin-bottom:.8rem">
          <span class="lbl">Méta-titre</span>
          <input type="text" name="meta_titre" value="<?= e($a['meta_titre']) ?>" style="width:100%;padding:.5rem;border:1px solid var(--line);border-radius:5px;font-size:.85rem">
        </label>
        <label style="display:block">
          <span class="lbl">Méta-description</span>
          <textarea name="meta_desc" rows="3" style="width:100%;padding:.5rem;border:1px solid var(--line);border-radius:5px;font-size:.85rem"><?= e($a['meta_desc']) ?></textarea>
        </label>
      </div>

      <button class="btn" style="width:100%">Enregistrer</button>
      <a href="articles.php" class="btn ghost sm" style="display:block;text-align:center;margin-top:.6rem">← Retour à la liste</a>
    </div>
  </div>
</form>

<!-- modale sélecteur d'image -->
<div id="imgModal" style="display:none;position:fixed;inset:0;background:rgba(16,23,26,.7);z-index:500;align-items:center;justify-content:center;padding:2rem">
  <div style="background:#fff;border-radius:10px;width:min(1000px,95vw);max-height:90vh;display:flex;flex-direction:column;overflow:hidden">
    <div style="display:flex;justify-content:space-between;align-items:center;padding:1rem 1.4rem;border-bottom:1px solid var(--line)">
      <b>Choisir une image</b>
      <button type="button" id="imgModalClose" style="background:none;border:none;font-size:1.6rem;cursor:pointer">&times;</button>
    </div>
    <div id="imgModalDrop" tabindex="0" style="margin:1rem 1.2rem 0;padding:1rem;border:2px dashed var(--line);border-radius:8px;text-align:center;color:var(--ink2);font-size:.9rem;cursor:pointer;outline:none">
      Coller une image (Ctrl+V), la glisser ici, ou cliquer pour en choisir une sur l'ordinateur
      <input type="file" id="imgModalFile" accept="image/*" style="display:none">
      <div id="imgModalDropStatus" style="margin-top:.4rem;font-size:.85rem"></div>
    </div>
    <div id="imgModalGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));grid-auto-rows:120px;gap:10px;padding:1.2rem;overflow-y:auto"></div>
  </div>
</div>

<style>
.lbl{display:block;font-size:.82rem;color:var(--ink2);margin-bottom:.3rem}
.imgtile{height:120px;border:1px solid var(--line);border-radius:6px;overflow:hidden;cursor:pointer;padding:0;background:#eee}
.imgtile img{width:100%;height:100%;object-fit:cover;display:block}
.imgtile:hover{border-color:var(--blue)}
</style>

<script>
(function(){
  var base='<?= SITE_URL ?>';
  var modal=document.getElementById('imgModal');
  var grid=document.getElementById('imgModalGrid');
  var field=document.getElementById('image_id');
  var preview=document.getElementById('imgPreview');
  var hidden=document.getElementById('contenuField');
  var wys=document.getElementById('wysiwyg');
  var mode='featured';

  // --- synchroniser l'éditeur visuel vers le champ caché avant envoi ---
  function sync(){ hidden.value = wys.innerHTML; }
  wys.addEventListener('input', sync);
  wys.addEventListener('blur', sync);
  var form = wys.closest('form');
  if (form) form.addEventListener('submit', sync);

  // --- barre d'outils ---
  document.querySelectorAll('.wysiwyg-toolbar button[data-cmd]').forEach(function(b){
    b.addEventListener('mousedown',function(e){
      e.preventDefault();
      var cmd=b.getAttribute('data-cmd'), val=b.getAttribute('data-val')||null;
      wys.focus();
      if(cmd==='createLink'){
        var url=prompt('Adresse du lien (https://…)');
        if(url) document.execCommand('createLink',false,url);
      } else {
        document.execCommand(cmd,false,val);
      }
      sync();
    });
  });

  // --- couleurs ---
  document.querySelectorAll('.wtcolor').forEach(function(b){
    b.addEventListener('mousedown',function(e){
      e.preventDefault(); wys.focus();
      document.execCommand('foreColor',false,b.getAttribute('data-color'));
      sync();
    });
  });
  (function(){
    var ci=document.getElementById('wysColorInput');
    if(!ci) return;
    var apply=function(){ wys.focus(); document.execCommand('foreColor',false,ci.value); sync(); };
    ci.addEventListener('input',apply); ci.addEventListener('change',apply);
    ci.closest('.wtcolor-pick').addEventListener('mousedown',function(e){ e.stopPropagation(); });
  })();

  // --- médiathèque (image à la une + insertion dans le contenu) ---
  function openModal(m){ mode=m; modal.style.display='flex'; load(); }
  document.getElementById('btnPickImg').addEventListener('click',function(){ openModal('featured'); });
  document.getElementById('btnInsertImg').addEventListener('mousedown',function(e){ e.preventDefault(); openModal('insert'); });
  document.getElementById('imgModalClose').addEventListener('click',function(){ modal.style.display='none'; });
  modal.addEventListener('click',function(e){ if(e.target===modal) modal.style.display='none'; });
  document.getElementById('btnClearImg').addEventListener('click',function(){
    field.value=''; preview.innerHTML='<span style="color:#999;font-size:.85rem">Aucune image</span>';
  });

  // téléverser une nouvelle image depuis l'ordinateur (image à la une)
  var fileInput = document.getElementById('fileFeatured');
  document.getElementById('btnUploadImg').addEventListener('click',function(){ fileInput.click(); });
  fileInput.addEventListener('change',function(){
    if(!fileInput.files || !fileInput.files[0]) return;
    var f = fileInput.files[0];
    preview.innerHTML='<span style="color:#888;font-size:.85rem">⏳ envoi…</span>';
    var fd = new FormData();
    fd.append('action','upload');
    fd.append('file', f);
    fetch('media_action.php',{method:'POST',body:fd,credentials:'same-origin'})
      .then(r=>r.json()).then(function(res){
        if(res && res.ok && res.id){
          field.value = res.id;
          preview.innerHTML='<img src="'+base+'/'+res.url+'" style="width:100%;height:100%;object-fit:cover">';
        } else {
          preview.innerHTML='<span style="color:var(--err);font-size:.85rem">Échec de l\'envoi</span>';
        }
        fileInput.value='';
      }).catch(function(){
        preview.innerHTML='<span style="color:var(--err);font-size:.85rem">Erreur réseau</span>';
        fileInput.value='';
      });
  });

  function insertHtmlAtCursor(html){
    wys.focus();
    document.execCommand('insertHTML',false,html);
    sync();
  }

  function load(){
    grid.innerHTML='<p style="color:#888">Chargement…</p>';
    fetch('media_action.php?action=list',{credentials:'same-origin'})
      .then(r=>r.json()).then(function(list){
        grid.innerHTML='';
        if(!list.length){ grid.innerHTML='<p style="color:#888;padding:1rem">Médiathèque vide.</p>'; return; }
        list.forEach(function(it){
          var b=document.createElement('button'); b.type='button'; b.className='imgtile';
          b.innerHTML='<img src="'+base+'/'+it.url+'" loading="lazy" alt="">';
          b.addEventListener('click',function(){
            var fullUrl = base+'/'+it.url;
            if(mode==='insert'){
              insertHtmlAtCursor('<img src="'+fullUrl+'" alt="">');
            } else {
              field.value=it.id;
              preview.innerHTML='<img src="'+fullUrl+'" style="width:100%;height:100%;object-fit:cover">';
            }
            modal.style.display='none';
          });
          grid.appendChild(b);
        });
      });
  }

  // --- appliquer un média choisi (selon le mode de la modale) ---
  function appliquerMedia(it){
    var fullUrl = base + '/' + it.url;
    if (mode === 'insert'){
      insertHtmlAtCursor('<img src="'+fullUrl+'" alt="">'); sync();
    } else {
      field.value = it.id;
      preview.innerHTML = '<img src="'+fullUrl+'" style="width:100%;height:100%;object-fit:cover">';
    }
    modal.style.display = 'none';
  }

  // --- zone coller / glisser / cliquer DANS la modale ---
  (function(){
    var drop = document.getElementById('imgModalDrop');
    var fileIn = document.getElementById('imgModalFile');
    var dstat = document.getElementById('imgModalDropStatus');
    if(!drop) return;
    function envoyer(f){
      dstat.textContent = '⏳ envoi…';
      // réduction côté navigateur, puis envoi binaire
      var rd = new FileReader();
      rd.onload = function(ev){
        var im = new Image();
        im.onload = function(){
          var MAX=1600, w=im.naturalWidth, h=im.naturalHeight;
          if(w>MAX||h>MAX){ if(w>=h){h=Math.round(h*MAX/w);w=MAX;} else {w=Math.round(w*MAX/h);h=MAX;} }
          var cv=document.createElement('canvas'); cv.width=w; cv.height=h;
          cv.getContext('2d').drawImage(im,0,0,w,h);
          cv.toBlob(function(blob){
            var fd=new FormData(); fd.append('action','upload'); fd.append('file', blob||f, 'collee.jpg');
            fetch('media_action.php',{method:'POST',body:fd,credentials:'same-origin'})
              .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
              .then(function(res){
                if(res && res.ok){ dstat.textContent=''; appliquerMedia({id:res.id, url:res.url}); }
                else { dstat.textContent = '✗ '+((res&&res.error)||'échec'); }
              })
              .catch(function(e){ dstat.textContent = '✗ '+e.message; });
          }, 'image/jpeg', 0.85);
        };
        im.onerror=function(){ dstat.textContent='✗ image illisible'; };
        im.src = ev.target.result;
      };
      rd.readAsDataURL(f);
    }
    drop.addEventListener('click', function(){ fileIn.click(); });
    fileIn.addEventListener('change', function(){ if(fileIn.files[0]) envoyer(fileIn.files[0]); fileIn.value=''; });
    drop.addEventListener('dragover', function(e){ e.preventDefault(); drop.style.borderColor='var(--blue)'; });
    drop.addEventListener('dragleave', function(){ drop.style.borderColor='var(--line)'; });
    drop.addEventListener('drop', function(e){
      e.preventDefault(); drop.style.borderColor='var(--line)';
      var f = e.dataTransfer.files[0]; if(f && f.type.indexOf('image')===0) envoyer(f);
    });
    drop.addEventListener('paste', function(e){
      var items=(e.clipboardData||window.clipboardData).items; if(!items) return;
      for(var i=0;i<items.length;i++){ if(items[i].type.indexOf('image')===0){ var f=items[i].getAsFile(); if(f){ e.preventDefault(); envoyer(f); } } }
    });
    // coller n'importe où quand la modale est ouverte
    document.addEventListener('paste', function(e){
      if(modal.style.display!=='flex') return;
      var items=(e.clipboardData||window.clipboardData).items; if(!items) return;
      for(var i=0;i<items.length;i++){ if(items[i].type.indexOf('image')===0){ var f=items[i].getAsFile(); if(f){ e.preventDefault(); envoyer(f); } } }
    });
  })();

  // --- COLLER une image (Ctrl+V) : upload auto puis insertion ---
  wys.addEventListener('paste', function(e){
    var items = (e.clipboardData || window.clipboardData).items;
    if(!items) return;
    for(var i=0;i<items.length;i++){
      if(items[i].type && items[i].type.indexOf('image')===0){
        e.preventDefault();
        var file = items[i].getAsFile();
        var reader = new FileReader();
        reader.onload = function(ev){
          var phId = 'ph-' + Date.now();
          insertHtmlAtCursor('<img id="'+phId+'" alt="" data-placeholder="1" src="data:image/svg+xml;utf8,'+encodeURIComponent('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"40\"><text x=\"6\" y=\"26\" font-family=\"sans-serif\" font-size=\"15\" fill=\"%23888\">image en cours…</text></svg>').replace(/#/g,'%23')+'">');

          // Réduire l'image AVANT l'envoi (canvas) pour un upload léger et fiable
          // Envoi d'un VRAI fichier binaire (Blob), comme le bouton « 🖼 Image » — pas de base64
          var sendBlob = function(blob){
            var fd = new FormData();
            fd.append('action','upload');
            fd.append('file', blob, 'collee-article.jpg');
            fetch('media_action.php',{method:'POST',body:fd,credentials:'same-origin'})
              .then(function(r){ return r.json(); })
              .then(function(res){
                var ph = document.getElementById(phId);
                if(res && res.ok && res.url){
                  if(ph){ ph.removeAttribute('data-placeholder'); ph.removeAttribute('id'); ph.src = base + '/' + res.url; }
                  else { insertHtmlAtCursor('<img src="'+base+'/'+res.url+'" alt="">'); }
                } else {
                  if(ph) ph.remove();
                  alert('Échec de l\'upload : ' + ((res && res.error) ? res.error : 'réponse inattendue'));
                }
                sync();
              })
              .catch(function(err){
                var ph = document.getElementById(phId);
                if(ph) ph.remove();
                alert('Échec de l\'envoi de l\'image. Réessayez, ou utilisez le bouton « 🖼 Image ».');
              });
          };

          var img = new Image();
          img.onload = function(){
            var MAX = 1600;
            var w = img.naturalWidth, h = img.naturalHeight;
            if (w > MAX || h > MAX){
              if (w >= h){ h = Math.round(h * MAX / w); w = MAX; }
              else { w = Math.round(w * MAX / h); h = MAX; }
            }
            try {
              var canvas = document.createElement('canvas');
              canvas.width = w; canvas.height = h;
              canvas.getContext('2d').drawImage(img, 0, 0, w, h);
              // export direct en Blob binaire (pas de base64), JPEG compressé
              canvas.toBlob(function(blob){
                if (blob) sendBlob(blob);
                else sendBlob(file);   // repli : le fichier collé d'origine
              }, 'image/jpeg', 0.85);
            } catch(e){
              sendBlob(file);          // repli : envoyer le fichier collé tel quel
            }
          };
          img.onerror = function(){ sendBlob(file); };
          img.src = ev.target.result;
        };
        reader.readAsDataURL(file);
        return;
      }
    }
    // sinon : coller en texte brut (évite le HTML sale de Word)
    e.preventDefault();
    var text=(e.clipboardData||window.clipboardData).getData('text/plain');
    document.execCommand('insertText',false,text);
    sync();
  });

  // ====== Gestion des images : alignement + redimensionnement ======
  // barre flottante
  var imgbar = document.createElement('div');
  imgbar.className = 'img-toolbar';
  imgbar.style.display = 'none';
  imgbar.innerHTML =
    '<button type="button" data-align="left" title="Aligner à gauche (texte à droite)">⬅</button>' +
    '<button type="button" data-align="center" title="Centrer">⬌</button>' +
    '<button type="button" data-align="right" title="Aligner à droite (texte à gauche)">➡</button>' +
    '<button type="button" data-align="full" title="Pleine largeur">▭</button>' +
    '<span class="ib-sep"></span>' +
    '<button type="button" data-size="small" title="Petite">S</button>' +
    '<button type="button" data-size="medium" title="Moyenne">M</button>' +
    '<button type="button" data-size="large" title="Grande">L</button>' +
    '<button type="button" data-size="reset" title="Taille d\'origine">↺</button>' +
    '<span class="ib-sep"></span>' +
    '<button type="button" data-forme="rond" title="Image ronde">●</button>' +
    '<button type="button" data-forme="normal" title="Image normale">▱</button>' +
    '<button type="button" data-bord="toggle" title="Bordure (contour blanc)">◳</button>';
  document.body.appendChild(imgbar);

  var selImg = null;

  function placeBar(img){
    var r = img.getBoundingClientRect();
    imgbar.style.display = 'flex';
    var top = window.scrollY + r.top - imgbar.offsetHeight - 8;
    if (top < window.scrollY + 4) top = window.scrollY + r.top + 8;
    imgbar.style.top = top + 'px';
    imgbar.style.left = (window.scrollX + r.left) + 'px';
  }
  function selectImg(img){
    if (selImg) selImg.classList.remove('img-selected');
    selImg = img;
    img.classList.add('img-selected');
    ensureHandle(img);
    placeBar(img);
  }
  function deselect(){
    if (selImg) selImg.classList.remove('img-selected');
    selImg = null;
    imgbar.style.display = 'none';
    removeHandle();
  }

  wys.addEventListener('click', function(e){
    if (e.target && e.target.tagName === 'IMG'){
      selectImg(e.target);
    } else {
      deselect();
    }
  });
  window.addEventListener('scroll', function(){ if (selImg) placeBar(selImg); }, {passive:true});

  // boutons alignement
  imgbar.querySelectorAll('button[data-align]').forEach(function(b){
    b.addEventListener('mousedown', function(e){
      e.preventDefault();
      if (!selImg) return;
      selImg.classList.remove('img-left','img-center','img-right','img-full');
      var a = b.getAttribute('data-align');
      selImg.classList.add('img-' + a);
      sync(); placeBar(selImg);
    });
  });
  // boutons taille
  imgbar.querySelectorAll('button[data-size]').forEach(function(b){
    b.addEventListener('mousedown', function(e){
      e.preventDefault();
      if (!selImg) return;
      var s = b.getAttribute('data-size');
      if (s === 'reset'){ selImg.style.width=''; selImg.removeAttribute('width'); }
      else if (s === 'small'){ selImg.style.width='30%'; }
      else if (s === 'medium'){ selImg.style.width='50%'; }
      else if (s === 'large'){ selImg.style.width='100%'; }
      sync(); placeBar(selImg);
    });
  });

  // boutons forme (rond / normal)
  imgbar.querySelectorAll('button[data-forme]').forEach(function(b){
    b.addEventListener('mousedown', function(e){
      e.preventDefault();
      if (!selImg) return;
      var f = b.getAttribute('data-forme');
      if (f === 'rond'){ selImg.classList.add('img-ronde'); }
      else { selImg.classList.remove('img-ronde'); }
      sync(); placeBar(selImg);
    });
  });
  // bouton bordure (bascule)
  imgbar.querySelectorAll('button[data-bord]').forEach(function(b){
    b.addEventListener('mousedown', function(e){
      e.preventDefault();
      if (!selImg) return;
      selImg.classList.toggle('img-bord');
      sync(); placeBar(selImg);
    });
  });

  // poignée de redimensionnement (coin bas-droit)
  var handle = null, dragging=false, startX=0, startW=0;
  function ensureHandle(img){
    removeHandle();
    handle = document.createElement('span');
    handle.className = 'img-resize-handle';
    document.body.appendChild(handle);
    positionHandle(img);
    handle.addEventListener('mousedown', function(e){
      e.preventDefault(); e.stopPropagation();
      dragging = true; startX = e.clientX; startW = img.getBoundingClientRect().width;
      document.body.style.userSelect='none';
    });
  }
  function positionHandle(img){
    if (!handle) return;
    var r = img.getBoundingClientRect();
    handle.style.display='block';
    handle.style.top = (window.scrollY + r.bottom - 14) + 'px';
    handle.style.left = (window.scrollX + r.right - 14) + 'px';
  }
  function removeHandle(){ if (handle){ handle.remove(); handle=null; } }
  document.addEventListener('mousemove', function(e){
    if (!dragging || !selImg) return;
    var parentW = wys.clientWidth;
    var newW = startW + (e.clientX - startX);
    if (newW < 60) newW = 60;
    if (newW > parentW) newW = parentW;
    var pct = Math.round(newW / parentW * 100);
    selImg.style.width = pct + '%';
    positionHandle(selImg); placeBar(selImg);
  });
  document.addEventListener('mouseup', function(){
    if (dragging){ dragging=false; document.body.style.userSelect=''; sync(); }
  });
  window.addEventListener('scroll', function(){ if (selImg) positionHandle(selImg); }, {passive:true});
})();
</script>
<?php layout_end(); ?>
