
<style>
/* comment-avatar */
.comment-avatar, .comment .user-badge, .comment .badge {
  width: 32px; height: 32px; border-radius: 50%;
  overflow: hidden; padding: 0; background: none;
  flex: 0 0 32px;
}
.comment-avatar img, .comment .user-badge img, .comment .badge img {
  width: 100%; height: 100%; border-radius: 50%; object-fit: cover; display: block;
}
.comment-row { display:flex; gap:10px; align-items:flex-start; }
</style>

<?php if (!function_exists('avatar_img')) { @include_once '../../helpers.php'; } ?>
<?php if(!$post): ?>
  <div class="card">
    <div style="text-align:center;padding:40px 20px">
      <i class="fas fa-exclamation-triangle" style="font-size:3rem;color:var(--error);margin-bottom:16px"></i>
      <h3 style="margin:0 0 12px 0">Publicación no encontrada</h3>
      <p class="muted">La publicación que buscas no existe o no tienes acceso a ella.</p>
      <a href="./?r=posts" class="btn primary" style="margin-top:16px">
        <i class="fas fa-arrow-left"></i> Volver a mis publicaciones
      </a>
    </div>
  </div>
<?php else: ?>
  <div class="grid grid-2" style="margin-top:40px">
    <div class="card">
      <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px">
        <?php if (!empty($post['avatar_url'])): ?>
          <img src="<?php echo h($post['avatar_url']); ?>" alt="Avatar" style="width:40px;height:40px;border-radius:50%;object-fit:cover">
        <?php else: ?>
          <div style="width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent2));display:flex;align-items:center;justify-content:center;color:white;font-weight:bold">
            <?php echo strtoupper(substr($post['username'], 0, 1)); ?>
          </div>
        <?php endif; ?>
        <div>
          <div style="font-weight:500">@<?php echo h($post['username']); ?></div>
          <div class="muted" style="font-size:0.85rem">
            <i class="fas fa-calendar"></i> <?php echo h(fdt_madrid($post['created_at'])); ?>
          </div>
        </div>
        
        <!-- Botón de reporte (solo para no autores) -->
        <?php if (!$is_author): ?>
        <a href="./?r=reports/form&type=post&id=<?php echo h($post['id']); ?>" class="btn sm" style="color:var(--error);margin-left:auto">
          <i class="fas fa-flag"></i> Reportar
        </a>
        <?php endif; ?>
      </div>
      
      <?php if($photo): ?>
        <div id="photoBox" style="position:relative;margin:16px 0;border-radius:var(--radius);overflow:hidden">
          <img id="photo" src="<?php echo h($photo['url']); ?>" alt="foto" style="width:100%;display:block">
          <?php foreach($tags as $t): ?>
            <span class="tag" style="position:absolute;left:<?php echo h($t['x']); ?>%;top:<?php echo h($t['y']); ?>%;transform:translate(-50%,-100%);background:var(--accent);color:white;padding:4px 10px;border-radius:999px;font-size:12px;font-weight:700;pointer-events:none">
              @<?php echo h($t['name']); ?>
            </span>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
      
      <div style="margin:16px 0;padding:16px;background:rgba(15,18,24,0.3);border-radius:var(--radius-sm);word-break:break-word">
        <?php echo !empty($post['caption']) ? h($post['caption']) : '<span class="muted">Sin descripción</span>'; ?>
      </div>

      <!-- Acciones de like y comentario -->
      <div class="post-actions" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:16px">
        <form method="post" action="?r=posts/like&id=<?php echo h($post['id']); ?>" class="like-form" style="margin:0">
<?= csrf_field() ?>
          <input type="hidden" name="like_action" value="<?php echo $user_like ? 'unlike' : 'like'; ?>">
          <button type="submit" class="thirty-btn like-button" style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;border-radius:10px;border:1px solid var(--border);background:transparent;color:<?php echo $user_like ? 'var(--accent)' : 'var(--text)'; ?>;cursor:pointer;transition:var(--transition);width:100%">
            <i class="fas fa-heart"></i>
            <span class="like-text"><?php echo $user_like ? 'Quitar like' : 'Dar like'; ?></span>
          </button>
        </form>
        <a href="#comment-form" class="thirty-btn" style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;border-radius:10px;border:1px solid var(--border);background:transparent;color:var(--text);cursor:pointer;transition:var(--transition);text-decoration:none">
          <i class="fas fa-comment"></i>
          <span>Comentar</span>
        </a>
      </div>

      <?php if ($is_author): ?>
        <form method="post" action="./?r=posts/delete&id=<?php echo h($post['id']); ?>" onsubmit="return confirm('¿Estás seguro de que quieres borrar esta publicación?');">
<?= csrf_field() ?>
  <button class="btn" type="submit" style="width:100%">    <i class="fas fa-trash"></i> Borrar publicación  </button>
</form>
      <?php endif; ?>
    </div>

    <div class="card">
      <?php if ($is_author): ?>
        <h3 style="margin:0 0 16px 0"><i class="fas fa-tag"></i> Etiquetar amigos</h3>
        <div class="muted" style="margin-bottom:16px">
          <i class="fas fa-info-circle"></i> Haz clic en la foto para colocar la etiqueta donde quieras.
        </div>
        
        <form id="tagForm" method="post">
<?= csrf_field() ?>
          <input type="hidden" name="add_tag" value="1">
          <input type="hidden" id="tagX" name="x" value="50">
          <input type="hidden" id="tagY" name="y" value="50">
          <div class="form-group">
            <label for="tag_username"><i class="fas fa-user"></i> Nombre de usuario</label>
            <input name="tag_username" placeholder="Usuario (ej. edgar)" required>
          </div>
          
          <div class="muted" style="margin-bottom:16px;padding:12px;background:rgba(15,18,24,0.3);border-radius:var(--radius-sm);font-size:0.9rem">
            <i class="fas fa-map-marker-alt"></i> Posición seleccionada: 
            <span id="positionIndicator">50%, 50%</span>
          </div>
          
          <button class="btn primary" type="submit" style="width:100%">
            <i class="fas fa-plus"></i> Añadir etiqueta
          </button>
        </form>
      <?php endif; ?>
      
      <?php if (!empty($tags)): ?>
        <div style="margin-top:24px">
          <h4 style="margin:0 0 12px 0"><i class="fas fa-users"></i> Personas etiquetadas</h4>
          <div style="display:flex;flex-wrap:wrap;gap:8px">
            <?php foreach($tags as $t): ?>
              <span style="display:inline-flex;align-items:center;gap:4px;padding:6px 12px;border-radius:20px;background:rgba(124,209,255,0.1);color:var(--accent);font-size:0.9rem">
                <i class="fas fa-tag"></i> @<?php echo h($t['name']); ?>
                <?php if ($is_author): ?>
                  <form method="post" action="./?r=posts/tag/delete&id=<?php echo h($t['id']); ?>" style="display:inline;margin:0" onsubmit="return confirm('¿Eliminar esta etiqueta?');">
<?= csrf_field() ?>
  <button type="submit" style="background:none;border:none;color:var(--error);cursor:pointer;padding:0;margin-left:4px">    <i class="fas fa-times"></i>  </button>
</form>
                <?php endif; ?>
              </span>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endif; ?>

      <?php if ($is_author): ?>
        <div style="margin-top:24px">
          <h4 style="margin:0 0 12px 0"><i class="fas fa-pencil-alt"></i> Editar descripción</h4>
          <form method="post">
<?= csrf_field() ?>
            <input type="hidden" name="update_caption" value="1">
            <div class="form-group">
              <textarea name="caption" placeholder="Nueva descripción..." rows="2" style="width:100%;padding:10px;border-radius:var(--radius-sm);border:1px solid var(--border);"><?php echo h($post['caption']); ?></textarea>
            </div>
            <button class="btn primary" type="submit" style="width:100%">
              <i class="fas fa-save"></i> Actualizar descripción
            </button>
          </form>
        </div>
      <?php endif; ?>

      <!-- Sistema de comentarios con respuestas -->
      <div style="margin-top: 24px;">
        <h4><i class="fas fa-comments"></i> Comentarios (<?php echo count($comments); ?>)</h4>
        
        <?php if (!empty($comments)): ?>
          <div style="margin-bottom: 16px;">
            <?php foreach($comments as $comment): ?>
              <div style="padding: 12px; border-bottom: 1px solid var(--border-light); position: relative;" id="comment-<?php echo h($comment['id']); ?>">
                <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                  <?php if (!empty($comment['avatar_url'])): ?>
                    <img src="<?php echo h($comment['avatar_url']); ?>" alt="Avatar" style="width:32px;height:32px;border-radius:50%;object-fit:cover">
                  <?php else: ?>
                    <div style="width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent2));display:flex;align-items:center;justify-content:center;color:white;font-size:0.8rem">
                      <?php echo strtoupper(substr($comment['username'], 0, 1)); ?>
                    </div>
                  <?php endif; ?>
                  <div>
                    <strong>@<?php echo h($comment['username']); ?></strong>
                    <div class="muted" style="font-size: 0.85rem;">
                      <?php echo h(fdt_madrid($comment['created_at'])); ?>
                    </div>
                  </div>
                </div>
                <p style="margin: 0; word-break: break-word;"><?php echo h($comment['comment']); ?></p>
                
                <div style="display: flex; gap: 8px; margin-top: 8px;">
                  <button type="button" class="btn sm" style="font-size: 0.8rem;" 
                          onclick="setReply('<?php echo h($comment['id']); ?>', '@<?php echo h($comment['username']); ?>')">
                    <i class="fas fa-reply"></i> Responder
                  </button>
                  
                  <?php if ($comment['can_delete']): ?>
                    <form method="post" action="./?r=posts/deleteComment&id=<?php echo h($comment['id']); ?>" style="display: inline;" onsubmit="return confirm('¿Eliminar este comentario?');">
<?= csrf_field() ?>
  <button type="submit" class="btn sm muted">    <i class="fas fa-trash"></i> Eliminar  </button>
</form>
                  <?php endif; ?>
                  
                  <!-- Botón de reportar comentario (solo para no autores del comentario) -->
                  <?php if (!$is_author && $comment['user_id'] != $_SESSION['user']['id']): ?>
                  <a href="./?r=reports/form&type=comment&id=<?php echo h($comment['id']); ?>" class="btn sm" style="color:var(--error);padding:4px 8px">
                    <i class="fas fa-flag"></i>
                  </a>
                  <?php endif; ?>
                </div>
                
                <?php if (!empty($comment['replies'])): ?>
                  <div style="margin-top: 12px; padding-left: 20px; border-left: 2px solid var(--border-light);">
                    <?php foreach($comment['replies'] as $reply): ?>
                      <div style="padding: 8px 0; border-bottom: 1px solid var(--border-light);">
                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
                          <?php if (!empty($reply['avatar_url'])): ?>
                            <img src="<?php echo h($reply['avatar_url']); ?>" alt="Avatar" style="width:24px;height:24px;border-radius:50%;object-fit:cover">
                          <?php else: ?>
                            <div style="width:24px;height:24px;border-radius:50%;background:linear-gradient(135deg,var(--accent2),var(--accent3));display:flex;align-items:center;justify-content:center;color:white;font-size:0.7rem">
                              <?php echo strtoupper(substr($reply['username'], 0, 1)); ?>
                            </div>
                          <?php endif; ?>
                          <div>
                            <strong style="font-size:0.9rem">@<?php echo h($reply['username']); ?></strong>
                            <div class="muted" style="font-size: 0.75rem;">
                              <?php echo h(fdt_madrid($reply['created_at'])); ?>
                            </div>
                          </div>
                        </div>
                        <p style="margin: 0; word-break: break-word; font-size: 0.9rem;"><?php echo h($reply['comment']); ?></p>
                        
                        <?php if ($reply['can_delete']): ?>
                          <form method="post" action="./?r=posts/deleteComment&id=<?php echo h($comment['id']); ?>" style="display: inline;" onsubmit="return confirm('¿Eliminar este comentario?');">
<?= csrf_field() ?>
  <button type="submit" class="btn sm muted">    <i class="fas fa-trash"></i> Eliminar  </button>
</form>
                        <?php endif; ?>
                        
                        <!-- Botón de reportar respuesta (solo para no autores de la respuesta) -->
                        <?php if ($reply['user_id'] != $_SESSION['user']['id']): ?>
                        <a href="./?r=reports/form&type=comment&id=<?php echo h($reply['id']); ?>" class="btn xs" style="color:var(--error);padding:2px 6px">
                          <i class="fas fa-flag"></i>
                        </a>
                        <?php endif; ?>
                      </div>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <p class="muted" style="text-align: center; padding: 20px;">No hay comentarios aún.</p>
        <?php endif; ?>
<form id="comment-form" method="post" action="./?r=posts/view&id=<?php echo h($post['id']); ?>">
<?= csrf_field() ?>

<input type="hidden" name="post_id" value="<?php echo h($post['id']); ?>"><input type="hidden" name="add_comment" value="1">
          <input type="hidden" id="reply-to" name="reply_to" value="">
          
          <div class="form-group">
            <textarea name="comment" placeholder="Escribe un comentario..." rows="2" 
                     style="width: 100%; padding: 10px; border-radius: var(--radius-sm); border: 1px solid var(--border);" 
                     required maxlength="300"></textarea>
          </div>
          
          <div id="reply-form" style="display: none; margin-bottom: 10px; padding: 8px; background: rgba(124, 209, 255, 0.1); border-radius: var(--radius-sm);">
            <span style="font-size: 0.9rem; color: var(--accent);">
              <i class="fas fa-reply"></i> Respondiendo a <span id="reply-username"></span>
              <button type="button" onclick="cancelReply()" 
                      style="margin-left: 10px; background: none; border: none; color: var(--muted); cursor: pointer;">
                <i class="fas fa-times"></i> Cancelar
              </button>
            </span>
          </div>
          
          <button type="submit" class="btn primary" style="width: 100%;">
            <i class="fas fa-paper-plane"></i> Publicar comentario
          </button>
        </form>
      </div>
    </div>
  </div>

  <script>
    // Funciones para el sistema de respuestas
    function setReply(commentId, username) {
      document.getElementById('reply-to').value = commentId;
      document.getElementById('reply-username').textContent = username;
      document.getElementById('reply-form').style.display = 'block';
      const form = document.getElementById('comment-form');
      form.scrollIntoView({ behavior: 'smooth', block: 'center' });
      document.querySelector('textarea[name="comment"]').focus();
    }
    
    function cancelReply() {
      document.getElementById('reply-to').value = '';
      document.getElementById('reply-form').style.display = 'none';
    }
    
    // Sistema de likes con AJAX
    document.querySelectorAll('.like-form').forEach(form => {
      form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const button = this.querySelector('.like-button');
        const likeText = this.querySelector('.like-text');
        const formData = new FormData(this);
        
        button.disabled = true;
        
        try {
          const response = await fetch(this.action, {
            method: 'POST',
            body: formData
          });
          
          const result = await response.json();
          
          if (result.success) {
            // Actualizar interfaz
            if (result.liked) {
              button.style.color = 'var(--accent)';
              likeText.textContent = 'Quitar like';
              this.querySelector('input[name="like_action"]').value = 'unlike';
            } else {
              button.style.color = 'var(--text)';
              likeText.textContent = 'Dar like';
              this.querySelector('input[name="like_action"]').value = 'like';
            }
            
            // Actualizar contador si existe
            const likeCount = document.querySelector('.like-count');
            if (likeCount) {
              likeCount.textContent = result.count;
            }
          }
        } catch (error) {
          console.error('Error:', error);
          alert('Error al procesar el like');
        }
        
        button.disabled = false;
      });
    });
    
    // Funciones para el sistema de etiquetas
    const ph = document.getElementById('photo');
    const tagX = document.getElementById('tagX');
    const tagY = document.getElementById('tagY');
    const positionIndicator = document.getElementById('positionIndicator');
    
    if (ph) {
      ph.style.cursor = 'crosshair';
      
      ph.addEventListener('click', (e) => {
        const rect = ph.getBoundingClientRect();
        const x = ((e.clientX - rect.left) / rect.width) * 100;
        const y = ((e.clientY - rect.top) / rect.height) * 100;
        
        tagX.value = x.toFixed(2);
        tagY.value = y.toFixed(2);
        
        positionIndicator.textContent = `${x.toFixed(0)}%, ${y.toFixed(0)}%`;
        
        const marker = document.createElement('div');
        marker.style.position = 'absolute';
        marker.style.left = `${x}%`;
        marker.style.top = `${y}%`;
        marker.style.transform = 'translate(-50%, -50%)';
        marker.style.width = '12px';
        marker.style.height = '12px';
        marker.style.borderRadius = '50%';
        marker.style.background = 'var(--accent)';
        marker.style.border = '2px solid white';
        marker.style.boxShadow = '0 0 0 2px var(--accent)';
        marker.style.pointerEvents = 'none';
        marker.style.zIndex = '10';
        
        const photoBox = document.getElementById('photoBox');
        photoBox.appendChild(marker);
        
        setTimeout(() => {
          photoBox.removeChild(marker);
        }, 1000);
      });
    }
  </script>
<?php endif; ?>