{% extends 'layouts/base.html' %}
{% load static %}
{% load i18n %}
{% load l10n %}
{% load social_tags %}

{% block title %} {% trans "Feed Social" %} {% endblock title %}

{% block extrastyle %}
<link rel="stylesheet" href="{% static 'css/social.css' %}">
{% endblock extrastyle %}

{% block extra_js %}
<script src="{% static 'js/social.js' %}"></script>
{% endblock extra_js %}

{% block content %}
<!-- Barra de navegação móvel (só aparece no mobile) -->
<div class="d-lg-none">
  <div class="bg-white shadow-sm border-bottom mb-3">
    <div class="container-fluid px-3 py-2">
      <div class="d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
          <div class="social-avatar-container me-2" style="width: 32px; height: 32px; border-radius: 50%; overflow: hidden;">
            {% if user.avatar %}
              <img src="{% url 'serve_files:serve_decrypted_file_with_timestamp' 'home' 'user' 'avatar' user.uuid timestamp %}" 
                   alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
            {% else %}
              <img src="{% static 'assets/img/team/generic_user.png' %}" 
                   alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
            {% endif %}
          </div>
          <span class="fw-bold small">{{ user.get_full_name|default:user.username }}{% verified_badge user "14px" %}</span>
        </div>
        <div class="d-flex gap-2">
          <a href="{% url 'social:search' %}" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-search"></i>
          </a>
          <a href="{% url 'social:user_profile' user.username %}" class="btn btn-outline-primary btn-sm">
            <i class="bi bi-person"></i>
          </a>
          {% if can_moderate %}
            <a href="{% url 'social:moderation_dashboard' %}" class="btn btn-outline-danger btn-sm">
              <i class="bi bi-shield-check"></i>
            </a>
          {% endif %}
        </div>
      </div>
    </div>
  </div>
</div>

<div class="container-fluid py-lg-4 py-2">
  <div class="row">
    <!-- Sidebar esquerda com perfil e links (oculta no mobile) -->
    <div class="col-lg-3 d-none d-lg-block">
      <!-- Card do perfil do usuário -->
      <div class="card mb-4">
        <div class="card-body text-center">
          <div class="social-avatar-container mb-3" style="width: 80px; height: 80px; border-radius: 50%; overflow: hidden; margin: 0 auto;">
            {% if user.avatar %}
              <img src="{% url 'serve_files:serve_decrypted_file_with_timestamp' 'home' 'user' 'avatar' user.uuid timestamp %}" 
                   alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
            {% else %}
              <img src="{% static 'assets/img/team/generic_user.png' %}" 
                   alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
            {% endif %}
          </div>
                  <h5 class="mb-1 user-name-title">{{ user.get_full_name|default:user.username }}{% verified_badge user "18px" %}</h5>
        <p class="text-muted small mb-3">@{{ user.username }}{% verified_badge user "14px" %}</p>
          
          <!-- Estatísticas do usuário -->
          <div class="row text-center mb-3">
            <div class="col-4">
              <div class="h6 mb-0 text-primary">{{ user_stats.posts_count }}</div>
              <small class="text-muted">{% trans "Posts" %}</small>
            </div>
            <div class="col-4">
              <div class="h6 mb-0 text-success">{{ user_stats.followers_count }}</div>
              <small class="text-muted">{% trans "Seguidores" %}</small>
            </div>
            <div class="col-4">
              <div class="h6 mb-0 text-info">{{ user_stats.following_count }}</div>
              <small class="text-muted">{% trans "Seguindo" %}</small>
            </div>
          </div>
          
          <!-- Botões de ação -->
          <div class="d-grid gap-2">
            <a href="{% url 'social:user_profile' user.username %}" class="btn btn-outline-primary btn-sm">
              <i class="bi bi-person"></i> {% trans "Ver Perfil" %}
            </a>
            <a href="{% url 'social:edit_profile' %}" class="btn btn-outline-secondary btn-sm">
              <i class="bi bi-pencil"></i> {% trans "Editar Perfil" %}
            </a>
          </div>
        </div>
      </div>
      
      <!-- Links úteis da rede social -->
      <div class="card mb-4">
        <div class="card-header">
          <h6 class="mb-0">
            <i class="bi bi-compass"></i> {% trans "Navegação" %}
          </h6>
        </div>
        <div class="card-body p-0">
          <div class="list-group list-group-flush">
            <a href="{% url 'social:feed' %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-house-door text-primary me-2"></i>
              {% trans "Feed Principal" %}
            </a>
            <a href="{% url 'social:my_posts' %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-collection text-success me-2"></i>
              {% trans "Meus Posts" %}
            </a>
            <a href="{% url 'social:search' %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-search text-info me-2"></i>
              {% trans "Buscar" %}
            </a>
            <a href="{% url 'social:user_profile' user.username %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-person text-warning me-2"></i>
              {% trans "Meu Perfil" %}
            </a>
            {% if can_moderate %}
              <a href="{% url 'social:moderation_dashboard' %}" class="list-group-item list-group-item-action d-flex align-items-center">
                <i class="bi bi-shield-check text-danger me-2"></i>
                {% trans "Moderação" %}
              </a>
            {% endif %}
          </div>
        </div>
      </div>
      
      <!-- Estatísticas de engajamento -->
      <div class="card mb-4">
        <div class="card-header">
          <h6 class="mb-0">
            <i class="bi bi-graph-up"></i> {% trans "Engajamento" %}
          </h6>
        </div>
        <div class="card-body">
          <div class="d-flex justify-content-between mb-2">
            <span class="small">{% trans "Curtidas recebidas" %}</span>
            <span class="small text-primary fw-bold">{{ user_stats.total_likes_received }}</span>
          </div>
          <div class="d-flex justify-content-between mb-2">
            <span class="small">{% trans "Comentários recebidos" %}</span>
            <span class="small text-success fw-bold">{{ user_stats.total_comments_received }}</span>
          </div>
          <div class="d-flex justify-content-between">
            <span class="small">{% trans "Taxa de engajamento" %}</span>
            <span class="small text-info fw-bold">
              {% if user_stats.posts_count > 0 %}
                {% widthratio user_stats.total_likes_received|add:user_stats.total_comments_received user_stats.posts_count 100 as engagement_rate %}
                {{ engagement_rate|floatformat:1 }}%
              {% else %}
                0%
              {% endif %}
            </span>
          </div>
        </div>
      </div>
      
      <!-- Links rápidos -->
      <div class="card">
        <div class="card-header">
          <h6 class="mb-0">
            <i class="bi bi-lightning"></i> {% trans "Ações Rápidas" %}
          </h6>
        </div>
        <div class="card-body p-0">
          <div class="list-group list-group-flush">
            <a href="{% url 'social:post_create' %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-plus-circle text-primary me-2"></i>
              {% trans "Novo Post" %}
            </a>
            <a href="{% url 'social:followers_list' user.username %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-people text-success me-2"></i>
              {% trans "Meus Seguidores" %}
            </a>
            <a href="{% url 'social:following_list' user.username %}" class="list-group-item list-group-item-action d-flex align-items-center">
              <i class="bi bi-person-check text-info me-2"></i>
              {% trans "Quem eu sigo" %}
            </a>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Coluna principal (ocupa toda largura no mobile) -->
    <div class="col-12 col-lg-6">
      
      <!-- Card para criar novo post -->
      <div class="card mb-4">
        <div class="card-body">
          <form method="post" enctype="multipart/form-data" id="post-form">
            {% csrf_token %}
            
            <!-- Campo de conteúdo sempre visível -->
            <div class="d-flex align-items-start mb-3">
              <div class="social-avatar-container me-2 me-lg-3" style="width: 32px; height: 32px; border-radius: 50%; overflow: hidden; flex-shrink: 0;">
                {% if user.avatar %}
                  <img src="{% url 'serve_files:serve_decrypted_file_with_timestamp' 'home' 'user' 'avatar' user.uuid timestamp %}" 
                       alt="Avatar" class="w-100 h-100" style="object-fit: cover; border-radius: 50%;">
                {% else %}
                  <img src="{% static 'assets/img/team/generic_user.png' %}" 
                       alt="Avatar" class="w-100 h-100" style="object-fit: cover; border-radius: 50%;">
                {% endif %}
              </div>
              <div class="flex-grow-1">
                <div class="form-group">
                  {{ form.content }}
                  {% if form.content.errors %}
                    <div class="text-danger small">{{ form.content.errors.0 }}</div>
                  {% endif %}
                </div>
              </div>
            </div>
            
            <!-- Layout Desktop (campos sempre visíveis) -->
            <div class="d-none d-lg-block">
              <!-- Preview de mídia -->
              <div id="media-preview" class="mt-3" style="display: none;">
                <div class="card border-0 bg-light">
                  <div class="card-body p-3">
                    <div class="d-flex align-items-center">
                      <div id="preview-content" class="flex-grow-1"></div>
                      <button type="button" class="btn btn-sm btn-outline-danger rounded-circle" onclick="clearMedia()" style="width: 32px; height: 32px; padding: 0;">
                        <i class="bi bi-x"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Barra de ações com menu suspenso estilo WhatsApp -->
              <div class="post-actions-bar mt-3 p-3 bg-light rounded-3 border">
                <div class="d-flex justify-content-between align-items-center">
                  <!-- Menu suspenso de mídia -->
                  <div class="dropdown">
                    <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" id="mediaDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                      <i class="bi bi-plus-circle me-1"></i> {% trans "Adicionar" %}
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="mediaDropdown">
                      <li>
                        <label for="{{ form.image.id_for_label }}" class="dropdown-item d-flex align-items-center">
                          <i class="bi bi-image text-primary me-2"></i>
                          <span>{% trans "Imagem" %}</span>
                          {{ form.image }}
                        </label>
                      </li>
                      <li>
                        <label for="{{ form.video.id_for_label }}" class="dropdown-item d-flex align-items-center">
                          <i class="bi bi-camera-video text-success me-2"></i>
                          <span>{% trans "Vídeo" %}</span>
                          {{ form.video }}
                        </label>
                      </li>
                                         </ul>
                   </div>
                   
                   <!-- Exibir erros dos campos de mídia -->
                   {% if form.image.errors %}
                     <div class="text-danger small">{{ form.image.errors.0 }}</div>
                   {% endif %}
                   {% if form.video.errors %}
                     <div class="text-danger small">{{ form.video.errors.0 }}</div>
                   {% endif %}
                   
                   <!-- Contadores e informações -->
                  <div class="d-flex gap-3 align-items-center">
                    <small class="text-muted d-flex align-items-center">
                      <i class="bi bi-text-paragraph me-1"></i>
                      <span id="char-count">0</span>/1000
                    </small>
                    <small class="text-muted d-flex align-items-center">
                      <i class="bi bi-hash me-1"></i>
                      <span id="hashtag-count">0</span> {% trans "hashtags" %}
                    </small>
                  </div>
                </div>
              </div>
              
              <div class="d-flex justify-content-between align-items-center mt-3">
                <div class="d-flex gap-3">
                  <small class="text-muted d-flex align-items-center">
                    <i class="bi bi-text-paragraph me-1"></i>
                    <span id="char-count">0</span>/1000 {% trans "caracteres" %}
                  </small>
                  <small class="text-muted d-flex align-items-center">
                    <i class="bi bi-hash me-1"></i>
                    <span id="hashtag-count">0</span> {% trans "hashtags" %}
                  </small>
                </div>
                <div class="d-flex gap-3 align-items-center">
                  <div class="form-check">
                    {{ form.is_public }}
                    <label class="form-check-label" for="{{ form.is_public.id_for_label }}">
                      <i class="bi bi-globe me-1"></i> {% trans "Post público" %}
                    </label>
                  </div>
                  <button type="submit" class="btn btn-primary px-4 btn-publish">
                    <i class="bi bi-send me-2"></i> {% trans "Publicar" %}
                  </button>
                </div>
              </div>
            </div>
            
            <!-- Layout Mobile Compacto -->
            <div class="d-lg-none">
              <!-- Preview de mídia -->
              <div id="media-preview-mobile" class="mt-2" style="display: none;">
                <div class="alert alert-info p-2 m-0">
                  <div class="d-flex align-items-center">
                    <div id="preview-content-mobile" class="flex-grow-1"></div>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearMediaMobile()">
                      <i class="bi bi-x"></i>
                    </button>
                  </div>
                </div>
              </div>
              
              <!-- Barra de ações mobile com menu suspenso -->
              <div class="d-flex justify-content-between align-items-center mt-2">
                <div class="d-flex gap-2 align-items-center">
                  <!-- Menu suspenso de mídia mobile -->
                  <div class="dropdown">
                    <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" id="mediaDropdownMobile" data-bs-toggle="dropdown" aria-expanded="false">
                      <i class="bi bi-plus-circle"></i>
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="mediaDropdownMobile">
                      <li>
                        <label for="{{ form.image.id_for_label }}" class="dropdown-item d-flex align-items-center">
                          <i class="bi bi-image text-primary me-2"></i>
                          <span>{% trans "Imagem" %}</span>
                          {{ form.image }}
                        </label>
                      </li>
                      <li>
                        <label for="{{ form.video.id_for_label }}" class="dropdown-item d-flex align-items-center">
                          <i class="bi bi-camera-video text-success me-2"></i>
                          <span>{% trans "Vídeo" %}</span>
                          {{ form.video }}
                        </label>
                      </li>
                                         </ul>
                   </div>
                   
                   <!-- Exibir erros dos campos de mídia -->
                   {% if form.image.errors %}
                     <div class="text-danger small">{{ form.image.errors.0 }}</div>
                   {% endif %}
                   {% if form.video.errors %}
                     <div class="text-danger small">{{ form.video.errors.0 }}</div>
                   {% endif %}
                   
                   <!-- Contador de caracteres compacto -->
                  <small class="text-muted">
                    <span id="char-count-mobile">0</span>/1000
                  </small>
                </div>
                
                <div class="d-flex gap-2 align-items-center">
                  <!-- Checkbox público compacto -->
                  <div class="form-check form-check-inline">
                    {{ form.is_public }}
                    <label class="form-check-label small" for="{{ form.is_public.id_for_label }}">
                      <i class="bi bi-globe" title="{% trans 'Post público' %}"></i>
                    </label>
                  </div>
                  
                  <!-- Botão publicar -->
                  <button type="submit" class="btn btn-primary btn-sm">
                    <i class="bi bi-send"></i>
                  </button>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- Feed de posts -->
      {% if page_obj %}
        {% for post in page_obj %}
          <div class="card mb-4 post-card" data-post-id="{{ post.id }}">
            <div class="card-header bg-transparent">
              <div class="d-flex align-items-center">
                <div class="social-avatar-container me-3" style="width: 40px; height: 40px; border-radius: 50%; overflow: hidden;">
                  {% if post.author.avatar %}
                    <img src="{% url 'serve_files:serve_decrypted_file_with_timestamp' 'home' 'user' 'avatar' post.author.uuid timestamp %}" 
                         alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
                  {% else %}
                    <img src="{% static 'assets/img/team/generic_user.png' %}" 
                         alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
                  {% endif %}
                </div>
                <div class="flex-grow-1">
                  <div class="d-flex align-items-center">
                                                      <h6 class="mb-0">
                          <a href="{% url 'social:user_profile' post.author.username %}" class="text-decoration-none">
                            {{ post.author.get_full_name|default:post.author.username }}{% verified_badge post.author "14px" %}
                          </a>
                        </h6>
                    {% if not post.is_public %}
                      <span class="badge bg-secondary ms-2">
                        <i class="bi bi-lock"></i> {% trans "Privado" %}
                      </span>
                    {% endif %}
                    {% if post.is_pinned %}
                      <span class="badge bg-warning ms-2">
                        <i class="bi bi-pin-angle"></i> {% trans "Fixado" %}
                      </span>
                    {% endif %}
                    {% if post.is_edited %}
                      <span class="badge bg-info ms-2">
                        <i class="bi bi-pencil-square"></i> {% trans "Editado" %}
                      </span>
                    {% endif %}
                    {% if post.is_flagged %}
                      <span class="badge bg-danger ms-2">
                        <i class="bi bi-flag"></i> {% trans "Denunciado" %}
                      </span>
                    {% endif %}
                    {% if post.is_hidden %}
                      <span class="badge bg-dark ms-2">
                        <i class="bi bi-eye-slash"></i> {% trans "Oculto" %}
                      </span>
                    {% endif %}
                  </div>
                  <small class="text-muted">
                    {{ post.created_at|timesince }} {% trans "atrás" %}
                    {% if post.is_edited %}
                      <i class="bi bi-pencil-square text-muted"></i>
                    {% endif %}
                  </small>
                </div>
                <div class="dropdown">
                  <button class="btn btn-link text-muted" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-three-dots-vertical"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'social:post_detail' post.id %}">
                      <i class="bi bi-eye"></i> {% trans "Ver post" %}
                    </a></li>
                    {% if post.author == user %}
                      <li><a class="dropdown-item" href="{% url 'social:post_edit' post.id %}">
                        <i class="bi bi-pencil"></i> {% trans "Editar" %}
                      </a></li>
                      <li><a class="dropdown-item pin-btn" href="#" data-post-id="{{ post.id }}">
                        <i class="bi bi-pin-angle{% if post.is_pinned %}-fill{% endif %}"></i> 
                        {% if post.is_pinned %}{% trans "Desfixar" %}{% else %}{% trans "Fixar" %}{% endif %}
                      </a></li>
                      <li><hr class="dropdown-divider"></li>
                      <li><a class="dropdown-item text-danger" href="{% url 'social:post_delete' post.id %}">
                        <i class="bi bi-trash"></i> {% trans "Deletar" %}
                      </a></li>
                    {% else %}
                      <li><hr class="dropdown-divider"></li>
                      <li><a class="dropdown-item text-warning report-btn" href="#" data-content-type="post" data-content-id="{{ post.id }}">
                        <i class="bi bi-flag"></i> {% trans "Denunciar" %}
                      </a></li>
                    {% endif %}
                    {% if can_moderate %}
                      <li><hr class="dropdown-divider"></li>
                      <li><a class="dropdown-item text-info" href="{% url 'social:moderation_dashboard' %}">
                        <i class="bi bi-shield-check"></i> {% trans "Moderação" %}
                      </a></li>
                    {% endif %}
                  </ul>
                </div>
              </div>
            </div>
            
            <div class="card-body">
              <!-- Aviso de conteúdo denunciado (apenas para moderadores) -->
              {% if post.is_flagged and can_moderate %}
                <div class="alert alert-warning alert-dismissible fade show mb-3">
                  <i class="bi bi-exclamation-triangle"></i>
                  <strong>{% trans "Conteúdo Denunciado" %}</strong>
                  <small class="d-block">{% trans "Este post foi denunciado e está aguardando revisão." %}</small>
                  <a href="{% url 'social:reports_list' %}?content_type=post&content_id={{ post.id }}" class="btn btn-sm btn-outline-warning mt-2">
                    <i class="bi bi-eye"></i> {% trans "Ver Denúncias" %}
                  </a>
                  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
              {% endif %}
              
              <!-- Aviso de conteúdo oculto (apenas para moderadores) -->
              {% if post.is_hidden and can_moderate %}
                <div class="alert alert-dark alert-dismissible fade show mb-3">
                  <i class="bi bi-eye-slash"></i>
                  <strong>{% trans "Conteúdo Oculto" %}</strong>
                  <small class="d-block">{% trans "Este post foi oculto por moderação." %}</small>
                  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
              {% endif %}
              
              <!-- Conteúdo do post -->
              <div class="post-content mb-3">
                {{ post.content|process_content|linebreaks }}
              </div>
              
              <!-- Mídia do post -->
              {% if post.has_media %}
                {% if post.image %}
                  <div class="post-media mb-3">
                    <img src="{{ post.image.url }}" alt="Post image" class="img-fluid rounded">
                  </div>
                {% endif %}
                {% if post.video %}
                  <div class="post-media mb-3">
                    <video controls class="w-100 rounded">
                      <source src="{{ post.video.url }}" type="video/mp4">
                      {% trans "Seu navegador não suporta vídeos." %}
                    </video>
                  </div>
                {% endif %}
              {% endif %}
              
              <!-- Link compartilhado -->
              {% if post.has_link %}
                <div class="shared-link mb-3">
                  <div class="card">
                    <div class="card-body">
                      {% if post.link_image %}
                        <img src="{{ post.link_image }}" alt="Link preview" class="img-fluid rounded mb-2">
                      {% endif %}
                      <h6 class="card-title">{{ post.link_title|default:post.link }}</h6>
                      {% if post.link_description %}
                        <p class="card-text text-muted">{{ post.link_description }}</p>
                      {% endif %}
                      <a href="{{ post.link }}" target="_blank" class="btn btn-sm btn-outline-primary">
                        <i class="bi bi-box-arrow-up-right"></i> {% trans "Abrir link" %}
                      </a>
                    </div>
                  </div>
                </div>
              {% endif %}
              
              <!-- Hashtags -->
              {% if post.hashtags.all %}
                <div class="hashtags mb-3">
                  {% for post_hashtag in post.hashtags.all %}
                    <a href="{% url 'social:hashtag_detail' post_hashtag.hashtag.name %}" 
                       class="badge bg-primary text-decoration-none me-1">
                      #{{ post_hashtag.hashtag.name }}
                    </a>
                  {% endfor %}
                </div>
              {% endif %}
              
              <!-- Estatísticas do post -->
              <div class="post-stats d-flex justify-content-between align-items-center text-muted small mb-3">
                <div>
                  <i class="bi bi-eye"></i> {{ post.views_count }} {% trans "visualizações" %}
                </div>
                <div>
                  <i class="bi bi-share"></i> {{ post.shares_count }} {% trans "compartilhamentos" %}
                </div>
                <div>
                  <i class="bi bi-graph-up"></i> {{ post.engagement_rate|floatformat:1 }}% {% trans "engajamento" %}
                </div>
              </div>
              
              <!-- Ações do post -->
              <div class="post-actions d-flex justify-content-between align-items-center">
                <div class="d-flex gap-2">
                  <!-- Botão de curtir padrão (sem reações) -->
                  <button class="btn btn-outline-primary btn-sm like-btn" 
                          type="button"
                          data-post-id="{{ post.id }}">
                    <i class="bi bi-heart{% if post.is_liked_by_current_user %}-fill text-danger{% endif %}"></i>
                    <span class="like-count">{{ post.likes_count }}</span>
                  </button>
                  
                  <!-- Botão de comentar -->
                  <a href="{% url 'social:post_detail' post.id %}" class="btn btn-outline-secondary btn-sm" title="{% trans 'Ver comentários' %}">
                    <i class="bi bi-chat"></i>
                    <span>{{ post.comments_count }}</span>
                  </a>
                  
                  <!-- Botão de compartilhar -->
                  <button class="btn btn-outline-success btn-sm share-btn" data-post-id="{{ post.id }}">
                    <i class="bi bi-share"></i>
                  </button>
                </div>
                
                <div class="dropdown">
                  <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-three-dots"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'social:post_detail' post.id %}">
                      <i class="bi bi-eye"></i> {% trans "Ver detalhes" %}
                    </a></li>
                    <li><a class="dropdown-item" href="{% url 'social:user_profile' post.author.username %}">
                      <i class="bi bi-person"></i> {% trans "Ver perfil" %}
                    </a></li>
                    {% if post.author != user %}
                      <li><hr class="dropdown-divider"></li>
                      <li><a class="dropdown-item follow-btn" href="#" data-user-id="{{ post.author.id }}">
                        <i class="bi bi-person-plus"></i> {% trans "Seguir" %}
                      </a></li>
                      <li><a class="dropdown-item text-warning report-btn" href="#" data-content-type="post" data-content-id="{{ post.id }}">
                        <i class="bi bi-flag"></i> {% trans "Denunciar" %}
                      </a></li>
                    {% endif %}
                  </ul>
                </div>
              </div>
            </div>
          </div>
        {% endfor %}
        
        <!-- Paginação -->
        {% if page_obj.has_other_pages %}
          <div class="mt-4">
            {% with query_params=request.GET.urlencode %}
              {% include 'includes/pagination.html' %}
            {% endwith %}
          </div>
        {% endif %}
        
      {% else %}
        <div class="card">
          <div class="card-body text-center py-5">
            <i class="bi bi-inbox display-1 text-muted"></i>
            <h5 class="mt-3">{% trans "Nenhum post encontrado" %}</h5>
            <p class="text-muted">{% trans "Siga alguns usuários para ver posts no seu feed" %}</p>
          </div>
        </div>
      {% endif %}
    </div>
    
    <!-- Sidebar direita com hashtags e sugestões (oculta no mobile) -->
    <div class="col-lg-3 d-none d-lg-block">
      <!-- Hashtags populares -->
      <div class="card mb-4">
        <div class="card-header">
          <h6 class="mb-0">
            <i class="bi bi-hash text-primary"></i> {% trans "Hashtags Populares" %}
          </h6>
        </div>
        <div class="card-body p-0">
          <div class="list-group list-group-flush">
            {% for hashtag in popular_hashtags|slice:":5" %}
              <a href="{% url 'social:hashtag_detail' hashtag.name %}" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                <span>#{{ hashtag.name }}</span>
                <span class="badge bg-primary rounded-pill">{{ hashtag.posts_count }}</span>
              </a>
            {% empty %}
              <div class="list-group-item text-muted small">
                {% trans "Nenhuma hashtag popular ainda" %}
              </div>
            {% endfor %}
          </div>
        </div>
      </div>
      
      <!-- Usuários sugeridos -->
      <div class="card mb-4">
        <div class="card-header">
          <h6 class="mb-0">
            <i class="bi bi-person-plus text-success"></i> {% trans "Quem Seguir" %}
          </h6>
        </div>
        <div class="card-body p-0">
          <div class="list-group list-group-flush">
            {% for suggested_user in suggested_users|slice:":5" %}
              <div class="list-group-item d-flex align-items-center">
                <div class="social-avatar-container me-2" style="width: 32px; height: 32px; border-radius: 50%; overflow: hidden;">
                  {% if suggested_user.avatar %}
                    <img src="{% url 'serve_files:serve_decrypted_file_with_timestamp' 'home' 'user' 'avatar' suggested_user.uuid timestamp %}" 
                         alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
                  {% else %}
                    <img src="{% static 'assets/img/team/generic_user.png' %}" 
                         alt="Avatar" class="w-100 h-100" style="object-fit: cover;">
                  {% endif %}
                </div>
                <div class="flex-grow-1">
                          <div class="small fw-bold">{{ suggested_user.get_full_name|default:suggested_user.username }}{% verified_badge suggested_user "12px" %}</div>
        <div class="small text-muted">@{{ suggested_user.username }}{% verified_badge suggested_user "10px" %}</div>
                </div>
                <button class="btn btn-sm btn-outline-primary follow-btn" data-user-id="{% localize off %}{{ suggested_user.id }}{% endlocalize %}">
                  <i class="bi bi-person-plus"></i>
                </button>
              </div>
            {% empty %}
              <div class="list-group-item text-muted small">
                {% trans "Nenhuma sugestão disponível" %}
              </div>
            {% endfor %}
          </div>
        </div>
      </div>
      
      <!-- Estatísticas da rede (apenas para superuser, staff e moderadores) -->
      {% if can_moderate %}
        <div class="card mb-4">
          <div class="card-header">
            <h6 class="mb-0">
              <i class="bi bi-graph-up text-info"></i> {% trans "Estatísticas" %}
            </h6>
          </div>
          <div class="card-body">
            <div class="d-flex justify-content-between mb-2">
              <span class="small">{% trans "Total de usuários" %}</span>
              <span class="small text-primary fw-bold">{{ network_stats.total_users }}</span>
            </div>
            <div class="d-flex justify-content-between mb-2">
              <span class="small">{% trans "Total de posts" %}</span>
              <span class="small text-success fw-bold">{{ network_stats.total_posts }}</span>
            </div>
            <div class="d-flex justify-content-between">
              <span class="small">{% trans "Posts hoje" %}</span>
              <span class="small text-info fw-bold">{{ network_stats.posts_today }}</span>
            </div>
          </div>
        </div>
      {% endif %}
      
      <!-- Estatísticas de Moderação (apenas para moderadores) -->
      {% if can_moderate %}
        <div class="card">
          <div class="card-header">
            <h6 class="mb-0">
              <i class="bi bi-shield-check text-danger"></i> {% trans "Moderação" %}
            </h6>
          </div>
          <div class="card-body">
            <div class="d-flex justify-content-between mb-2">
              <span class="small">{% trans "Denúncias pendentes" %}</span>
              <span class="small text-warning fw-bold">{{ moderation_stats.pending_reports }}</span>
            </div>
            <div class="d-flex justify-content-between mb-2">
              <span class="small">{% trans "Total de denúncias" %}</span>
              <span class="small text-danger fw-bold">{{ moderation_stats.total_reports }}</span>
            </div>
            <div class="d-flex justify-content-between mb-2">
              <span class="small">{% trans "Denúncias hoje" %}</span>
              <span class="small text-info fw-bold">{{ moderation_stats.reports_today }}</span>
            </div>
            <div class="d-flex justify-content-between">
              <span class="small">{% trans "Filtros ativos" %}</span>
              <span class="small text-success fw-bold">{{ moderation_stats.active_filters }}</span>
            </div>
            <div class="mt-3">
              <a href="{% url 'social:moderation_dashboard' %}" class="btn btn-sm btn-outline-danger w-100">
                <i class="bi bi-shield-check"></i> {% trans "Painel de Moderação" %}
              </a>
            </div>
          </div>
        </div>
      {% endif %}
    </div>
  </div>
</div>

<!-- Token CSRF para JavaScript -->
{% csrf_token %}

<!-- Modal de compartilhamento -->
<div class="modal fade" id="shareModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">{% trans "Compartilhar post" %}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="shareForm" method="post">
        {% csrf_token %}
        <div class="modal-body">
          <div class="mb-3">
            <label for="shareComment" class="form-label">{% trans "Adicione um comentário (opcional)" %}</label>
            <textarea class="form-control" id="shareComment" name="comment" rows="3" maxlength="500"></textarea>
            <small class="text-muted">
              <span id="shareCharCount">0</span>/500 {% trans "caracteres" %}
            </small>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="sharePublic" name="is_public" checked>
            <label class="form-check-label" for="sharePublic">
              {% trans "Compartilhar publicamente" %}
            </label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancelar" %}</button>
          <button type="submit" class="btn btn-primary">{% trans "Compartilhar" %}</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal de denúncia -->
<div class="modal fade" id="reportModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">{% trans "Denunciar Conteúdo" %}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="reportForm" method="post">
        {% csrf_token %}
        <div class="modal-body">
          <div class="mb-3">
            <label for="reportReason" class="form-label">{% trans "Motivo da denúncia" %}</label>
            <select class="form-select" id="reportReason" name="report_type" required>
              <option value="">{% trans "Selecione um motivo" %}</option>
              <option value="spam">{% trans "Spam ou conteúdo comercial não autorizado" %}</option>
              <option value="inappropriate">{% trans "Conteúdo inadequado ou ofensivo" %}</option>
              <option value="harassment">{% trans "Assédio ou bullying" %}</option>
              <option value="violence">{% trans "Violência ou ameaças" %}</option>
              <option value="fake_news">{% trans "Fake news ou desinformação" %}</option>
              <option value="copyright">{% trans "Violação de direitos autorais" %}</option>
              <option value="other">{% trans "Outro" %}</option>
            </select>
          </div>
          <div class="mb-3">
            <label for="reportDescription" class="form-label">{% trans "Descrição detalhada (opcional)" %}</label>
            <textarea class="form-control" id="reportDescription" name="description" rows="3" maxlength="1000" placeholder="{% trans 'Forneça mais detalhes sobre a denúncia...' %}"></textarea>
            <small class="text-muted">
              <span id="reportCharCount">0</span>/1000 {% trans "caracteres" %}
            </small>
          </div>
          <div class="alert alert-info">
            <i class="bi bi-info-circle"></i>
            <small>{% trans "Sua denúncia será analisada pela equipe de moderação. Obrigado por ajudar a manter nossa comunidade segura." %}</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancelar" %}</button>
          <button type="submit" class="btn btn-warning">{% trans "Enviar Denúncia" %}</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// JavaScript para interações
document.addEventListener('DOMContentLoaded', function() {
  // Validação do formulário
  const postForm = document.getElementById('post-form');
  if (postForm) {
    postForm.addEventListener('submit', function(e) {
      const contentField = document.getElementById('{{ form.content.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.content.name }}"]');
      const content = contentField ? contentField.value.trim() : '';
      
      if (!content) {
        e.preventDefault();
        alert('{% trans "O conteúdo do post não pode estar vazio." %}');
        if (contentField) {
          contentField.focus();
        }
        return false;
      }
      
      if (content.length > 1000) {
        e.preventDefault();
        alert('{% trans "O conteúdo não pode ter mais de 1000 caracteres." %}');
        if (contentField) {
          contentField.focus();
        }
        return false;
      }
      
                   // Verificar se pelo menos uma mídia foi selecionada ou há conteúdo
             const imageField = document.getElementById('{{ form.image.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.image.name }}"]');
             const videoField = document.getElementById('{{ form.video.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.video.name }}"]');
             const linkField = document.getElementById('{{ form.link.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.link.name }}"]');
             
             const hasImage = imageField && imageField.files.length > 0;
             const hasVideo = videoField && videoField.files.length > 0;
             const hasLink = linkField && linkField.value.trim();
             
             // Removido: não forçar conteúdo mínimo quando não há mídia/link
             // Agora posts podem ser apenas texto, independente do tamanho
    });
  }
  
  // Toggle de campos extras no mobile
  const toggleExtraFieldsBtn = document.getElementById('toggle-extra-fields');
  const mobileExtraFields = document.getElementById('mobile-extra-fields');
  const toggleIcon = document.getElementById('toggle-icon');
  
  if (toggleExtraFieldsBtn && mobileExtraFields && toggleIcon) {
    toggleExtraFieldsBtn.addEventListener('click', function() {
      if (mobileExtraFields.style.display === 'none' || mobileExtraFields.style.display === '') {
        mobileExtraFields.style.display = 'block';
        toggleIcon.className = 'bi bi-dash-circle';
        this.classList.remove('btn-outline-secondary');
        this.classList.add('btn-secondary');
      } else {
        mobileExtraFields.style.display = 'none';
        toggleIcon.className = 'bi bi-plus-circle';
        this.classList.remove('btn-secondary');
        this.classList.add('btn-outline-secondary');
      }
    });
  }
  
  // Contador de caracteres
  const contentField = document.getElementById('{{ form.content.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.content.name }}"]');
  const charCount = document.getElementById('char-count');
  const charCountMobile = document.getElementById('char-count-mobile');
  
  if (contentField) {
    contentField.addEventListener('input', function() {
      const length = this.value.length;
      if (charCount) {
        charCount.textContent = length;
      }
      if (charCountMobile) {
        charCountMobile.textContent = length;
      }
    });
  }
  
  // Contador de hashtags
  const hashtagsField = document.getElementById('{{ form.hashtags.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.hashtags.name }}"]');
  const hashtagCount = document.getElementById('hashtag-count');
  
  if (hashtagsField && hashtagCount) {
    hashtagsField.addEventListener('input', function() {
      const hashtags = this.value.match(/#\w+/g) || [];
      hashtagCount.textContent = hashtags.length;
    });
  }
  
  // Preview de mídia
  const imageField = document.getElementById('{{ form.image.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.image.name }}"]');
  const videoField = document.getElementById('{{ form.video.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.video.name }}"]');
  const mediaPreview = document.getElementById('media-preview');
  const previewContent = document.getElementById('preview-content');
  
  if (imageField && mediaPreview && previewContent) {
    imageField.addEventListener('change', function() {
      if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
          if (previewContent) {
            previewContent.innerHTML = `<img src="${e.target.result}" class="img-fluid rounded" style="max-height: 100px;">`;
          }
          if (mediaPreview) {
            mediaPreview.style.display = 'block';
          }
        };
        reader.readAsDataURL(this.files[0]);
      }
    });
  }
  
  if (videoField && mediaPreview && previewContent) {
    videoField.addEventListener('change', function() {
      if (this.files && this.files[0]) {
        if (previewContent) {
          previewContent.innerHTML = `<video controls class="img-fluid rounded" style="max-height: 100px;"><source src="${URL.createObjectURL(this.files[0])}"></video>`;
        }
        if (mediaPreview) {
          mediaPreview.style.display = 'block';
        }
      }
    });
  }
  
  // Preview de link
  const linkField = document.getElementById('{{ form.link.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.link.name }}"]');
  const linkPreview = document.getElementById('link-preview');
  const linkContent = document.getElementById('link-content');
  
  if (linkField && linkPreview && linkContent) {
    linkField.addEventListener('blur', function() {
      if (this.value) {
        if (linkContent) {
          linkContent.innerHTML = `<i class="bi bi-link-45deg"></i> ${this.value}`;
        }
        if (linkPreview) {
          linkPreview.style.display = 'block';
        }
      }
    });
  }
  
  // Compartilhamento
  const shareBtns = document.querySelectorAll('.share-btn');
  const shareModalElement = document.getElementById('shareModal');
  const shareForm = document.getElementById('shareForm');
  const shareComment = document.getElementById('shareComment');
  const shareCharCount = document.getElementById('shareCharCount');
  
  if (shareBtns.length > 0 && shareModalElement && shareForm) {
    const shareModal = new bootstrap.Modal(shareModalElement);
    
    shareBtns.forEach(btn => {
      btn.addEventListener('click', function() {
        const postId = this.dataset.postId;
        if (postId && shareForm) {
          shareForm.action = `/social/post/${postId}/share/`;
          if (shareModal) {
            shareModal.show();
          }
        }
      });
    });
  }
  
  if (shareComment && shareCharCount) {
    shareComment.addEventListener('input', function() {
      if (shareCharCount) {
        shareCharCount.textContent = this.value.length;
      }
    });
  }
  
  // Like padrão (igual ao do perfil)
  const likeBtns = document.querySelectorAll('.like-btn');
  if (likeBtns.length > 0) {
    likeBtns.forEach(btn => {
      btn.addEventListener('click', function() {
        const postId = this.dataset.postId;
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
        if (!postId || !csrfToken) {
          console.error('Elementos necessários não encontrados para like');
          return;
        }
        fetch(`/social/post/${postId}/like/`, {
          method: 'POST',
          headers: {
            'X-CSRFToken': csrfToken.value
          }
        })
        .then(response => response.json())
        .then(data => {
          const icon = this.querySelector('i');
          const count = this.querySelector('.like-count');
          if (data.liked) {
            if (icon) icon.className = 'bi bi-heart-fill text-danger';
          } else {
            if (icon) icon.className = 'bi bi-heart';
          }
          if (typeof data.likes_count !== 'undefined' && count) {
            count.textContent = data.likes_count;
          }
        })
        .catch(error => {
          console.error('Erro:', error);
        });
      });
    });
  }
  
     // Fixar/desfixar posts
   const pinBtns = document.querySelectorAll('.pin-btn');
   if (pinBtns.length > 0) {
     pinBtns.forEach(btn => {
       btn.addEventListener('click', function(e) {
         e.preventDefault();
         const postId = this.dataset.postId;
         const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
         
         if (!postId || !csrfToken) {
           console.error('Elementos necessários não encontrados para pin');
           return;
         }
         
         fetch(`/social/post/${postId}/pin/`, {
           method: 'POST',
           headers: {
             'X-CSRFToken': csrfToken.value
           }
         })
         .then(response => response.json())
         .then(data => {
           if (data.pinned) {
             this.innerHTML = '<i class="bi bi-pin-angle-fill"></i> {% trans "Desfixar" %}';
           } else {
             this.innerHTML = '<i class="bi bi-pin-angle"></i> {% trans "Fixar" %}';
           }
         })
         .catch(error => {
           console.error('Erro:', error);
         });
       });
     });
   }
   
   // Botões de seguir na sidebar
   const followBtns = document.querySelectorAll('.follow-btn');
   if (followBtns.length > 0) {
     followBtns.forEach(btn => {
       btn.addEventListener('click', function(e) {
         e.preventDefault();
         const userId = parseInt(this.dataset.userId);
         const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
         
         if (!userId || isNaN(userId) || !csrfToken) {
           console.error('Elementos necessários não encontrados para follow ou ID inválido:', this.dataset.userId);
           return;
         }
         
         fetch(`/social/user/${userId}/follow/`, {
           method: 'POST',
           headers: {
             'X-CSRFToken': csrfToken.value
           }
         })
         .then(response => response.json())
         .then(data => {
           if (data.following) {
             this.innerHTML = '<i class="bi bi-person-check"></i>';
             this.classList.remove('btn-outline-primary');
             this.classList.add('btn-success');
           } else {
             this.innerHTML = '<i class="bi bi-person-plus"></i>';
             this.classList.remove('btn-success');
             this.classList.add('btn-outline-primary');
           }
         })
         .catch(error => {
           console.error('Erro:', error);
         });
       });
     });
   }
  
     // Sistema de denúncias
   const reportBtns = document.querySelectorAll('.report-btn');
   const reportModal = document.getElementById('reportModal');
   const reportForm = document.getElementById('reportForm');
   
   // Verificar se os elementos existem antes de usar
   if (reportBtns.length > 0 && reportModal && reportForm) {
     const reportModalInstance = new bootstrap.Modal(reportModal);
     const reportDescription = document.getElementById('reportDescription');
     const reportCharCount = document.getElementById('reportCharCount');
     
     reportBtns.forEach(btn => {
       btn.addEventListener('click', function(e) {
         e.preventDefault();
         const contentType = this.dataset.contentType;
         const contentId = this.dataset.contentId;
         
         if (contentType && contentId && reportForm) {
           // Configurar o formulário para a denúncia específica
           reportForm.action = `/social/report/${contentType}/${contentId}/`;
           if (reportModalInstance) {
             reportModalInstance.show();
           }
         }
       });
     });
     
     // Contador de caracteres para descrição
     if (reportDescription && reportCharCount) {
       reportDescription.addEventListener('input', function() {
         if (reportCharCount) {
           reportCharCount.textContent = this.value.length;
         }
       });
     }
     
     // Envio do formulário de denúncia
     reportForm.addEventListener('submit', function(e) {
       e.preventDefault();
       
       const formData = new FormData(this);
       const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
       
       if (!csrfToken) {
         console.error('CSRF token não encontrado');
         return;
       }
       
       fetch(this.action, {
         method: 'POST',
         body: formData,
         headers: {
           'X-CSRFToken': csrfToken.value
         }
       })
       .then(response => {
         if (!response.ok) {
           throw new Error(`HTTP error! status: ${response.status}`);
         }
         return response.json();
       })
       .then(data => {
         if (data.success) {
           if (reportModalInstance) {
             reportModalInstance.hide();
           }
           // Mostrar mensagem de sucesso
           showAlert('success', data.message);
         } else {
           // Mostrar erro
           showAlert('danger', data.message);
         }
       })
       .catch(error => {
         console.error('Erro:', error);
         // Mostrar erro genérico
         showAlert('danger', 'Erro ao enviar denúncia. Tente novamente.');
       });
     });
   }
   
   // Função para mostrar alertas de forma segura
   function showAlert(type, message) {
     const alertDiv = document.createElement('div');
     alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
     alertDiv.innerHTML = `
       <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}"></i> ${message}
       <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
     `;
     
     // Tentar inserir no topo da página de forma segura
     const container = document.querySelector('.container-fluid');
     if (container) {
       container.insertBefore(alertDiv, container.firstChild);
     } else {
       // Fallback: inserir no body
       document.body.insertBefore(alertDiv, document.body.firstChild);
     }
     
     // Auto-remover após 5 segundos
     setTimeout(() => {
       if (alertDiv.parentNode) {
         alertDiv.remove();
       }
     }, 5000);
   }
});

// Funções auxiliares
function clearMedia() {
  const mediaPreview = document.getElementById('media-preview');
  const previewContent = document.getElementById('preview-content');
  const imageField = document.getElementById('{{ form.image.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.image.name }}"]');
  const videoField = document.getElementById('{{ form.video.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.video.name }}"]');
  
  if (mediaPreview) {
    mediaPreview.style.display = 'none';
  }
  if (previewContent) {
    previewContent.innerHTML = '';
  }
  if (imageField) {
    imageField.value = '';
  }
  if (videoField) {
    videoField.value = '';
  }
}

function clearLink() {
  const linkPreview = document.getElementById('link-preview');
  const linkContent = document.getElementById('link-content');
  const linkField = document.getElementById('{{ form.link.id_for_label|default:"" }}') || document.querySelector('[name="{{ form.link.name }}"]');
  
  if (linkPreview) {
    linkPreview.style.display = 'none';
  }
  if (linkContent) {
    linkContent.innerHTML = '';
  }
  if (linkField) {
    linkField.value = '';
  }
}

// Funções auxiliares para mobile
function clearMediaMobile() {
  const mediaPreviewMobile = document.getElementById('media-preview-mobile');
  const previewContentMobile = document.getElementById('preview-content-mobile');
  const imageField = document.querySelector('#{{ form.image.id_for_label }}');
  const videoField = document.querySelector('#{{ form.video.id_for_label }}');
  
  if (mediaPreviewMobile) {
    mediaPreviewMobile.style.display = 'none';
  }
  if (previewContentMobile) {
    previewContentMobile.innerHTML = '';
  }
  if (imageField) {
    imageField.value = '';
  }
  if (videoField) {
    videoField.value = '';
  }
}

function clearLinkMobile() {
  const linkPreviewMobile = document.getElementById('link-preview-mobile');
  const linkContentMobile = document.getElementById('link-content-mobile');
  const linkField = document.querySelector('#{{ form.link.id_for_label }}');
  
  if (linkPreviewMobile) {
    linkPreviewMobile.style.display = 'none';
  }
  if (linkContentMobile) {
    linkContentMobile.innerHTML = '';
  }
  if (linkField) {
    linkField.value = '';
  }
}
</script>

<!-- CSS para responsividade mobile -->
<style>
/* Garantir que o campo content seja sempre visível e acessível */
#{{ form.content.id_for_label }} {
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 1 !important;
}

/* Mobile optimizations */
@media (max-width: 991.98px) {
  /* Reduzir padding nos cards para economizar espaço */
  .card-body {
    padding: 0.75rem !important;
  }
  
  /* Compactar form de criar post */
  .card.mb-4 {
    margin-bottom: 1rem !important;
  }
  
  /* Formulário de post mobile mais compacto */
  #mobile-extra-fields {
    transition: all 0.3s ease-in-out;
    overflow: hidden;
  }
  
  #mobile-extra-fields .form-label {
    font-size: 0.75rem;
    margin-bottom: 0.25rem;
  }
  
  #mobile-extra-fields .form-control {
    font-size: 0.875rem;
    padding: 0.375rem;
  }
  
  /* Botão toggle de campos extras */
  #toggle-extra-fields {
    transition: all 0.2s ease;
  }
  
  #toggle-extra-fields:hover {
    transform: scale(1.05);
  }
  
  /* Previews mobile mais compactos */
  #media-preview-mobile .alert,
  #link-preview-mobile .alert {
    font-size: 0.875rem;
    padding: 0.5rem;
  }
  
  /* Otimizar botões de ação dos posts */
  .post-actions .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
  }
  
  /* Reduzir espaçamento entre posts */
  .post-item {
    margin-bottom: 1rem;
  }
  
  /* Avatar menor no form de criar post */
  .social-social-avatar-container {
    width: 40px !important;
    height: 40px !important;
  }
  
  /* Avatar extra pequeno no mobile */
  .d-lg-none .social-social-avatar-container {
    width: 32px !important;
    height: 32px !important;
  }
  
  /* Compactar dropdown de reações */
  .dropdown-menu {
    font-size: 0.875rem;
  }
  
  /* Otimizar área de texto */
  .form-control {
    font-size: 1rem;
  }
  
  /* Textarea no mobile mais compacto */
  .d-lg-none textarea.form-control {
    min-height: 60px;
    font-size: 0.95rem;
  }
  
  /* Ajustar container */
  .container-fluid {
    padding-left: 0.5rem;
    padding-right: 0.5rem;
  }
}

/* Mobile extra small devices */
@media (max-width: 575.98px) {
  /* Remover bordas laterais dos cards */
  .card {
    border-left: none;
    border-right: none;
    border-radius: 0;
  }
  
  /* Padding mínimo */
  .container-fluid {
    padding-left: 0;
    padding-right: 0;
  }
  
  /* Cards sem margin lateral */
  .card.mb-4, .card {
    margin-left: 0;
    margin-right: 0;
  }
}
</style>
{% endblock content %}