<?php
$vmCommentRestrictionState = (isset($me) && is_array($me) && !empty($me['id']) && isset($pdo) && $pdo instanceof PDO && function_exists('ar_get_state'))
  ? ar_get_state($pdo, (int)$me['id'])
  : [];
$vmCommentBlocked = is_array($vmCommentRestrictionState) && function_exists('ar_is_action_blocked')
  ? ar_is_action_blocked($vmCommentRestrictionState, 'comments')
  : false;
$vmCommentBlockedText = $vmCommentBlocked && function_exists('ar_action_error')
  ? ar_action_error($vmCommentRestrictionState, 'comments')
  : '';
?>
      <div class="d-flex align-items-center justify-content-between mb-2">
        <div class="fw-semibold"><?= h($T('Пости','Посты','Posts')) ?></div>
      </div>

      <?php if ($vmCommentBlocked): ?>
        <div class="alert alert-warning"><?= h($vmCommentBlockedText) ?></div>
      <?php endif; ?>

      <?php foreach ($posts as $p): ?>
        <?php
          $pid = (int)($p['id'] ?? 0);
          $authorId = (int)($p['user_id'] ?? 0);

          $isPromoted = ((int)($p['is_promoted'] ?? 0) === 1);
          $promotedCampaignId = (int)($p['promoted_campaign_id'] ?? 0);
          $promotedClickUrl = trim((string)($p['promoted_click_url'] ?? ''));

          $canManagePost = can_edit_owner($me, $authorId);

          $isRepost = $hasRepost && ((int)($p['repost_post_id'] ?? 0) > 0);
          $contentId = $pid;
          if ($isRepost) $contentId = (int)($p['repost_post_id'] ?? 0);

          $atts = $attachmentsByPost[$contentId] ?? [];
          $poll = $pollByPost[$contentId] ?? null;

          $likes = (int)($p['likes'] ?? 0);
          $dislikes = (int)($p['dislikes'] ?? 0);
          $myReaction = (string)($p['my_reaction'] ?? '');

          $fullName = user_full_name($p);
          $postUsername = (string)($p['username'] ?? '');
          $ava = user_avatar_path($p);
          $ini = user_initials($fullName, $postUsername !== '' ? $postUsername : 'U');

          $confirmDelPost = $T('Видалити пост?', 'Удалить пост?', 'Delete post?');

          $origFullName = $isRepost ? user_full_name($p, 'orig_') : '';
          $origUsername = $isRepost ? (string)($p['orig_username'] ?? '') : '';
          $origAva = $isRepost ? user_avatar_path($p, 'orig_') : '';
          $origIni = $isRepost ? user_initials($origFullName, $origUsername !== '' ? $origUsername : 'U') : '';
          $origBody = $isRepost ? (string)($p['orig_body'] ?? '') : '';
          $origCreated = $isRepost ? (string)($p['orig_created_at'] ?? '') : '';

          $bodyText = (string)($p['body'] ?? '');
          $firstUrl = normalize_url(extract_first_url($bodyText));
          $firstHash = $firstUrl !== '' ? url_hash($firstUrl) : '';
          $lp = ($firstHash !== '' && isset($previewByHash[$firstHash])) ? $previewByHash[$firstHash] : null;

          $backToPost = current_uri() . '#post-' . $pid;
          $likeBtnClass = ($myReaction === 'like') ? 'btn-success' : 'btn-outline-success';
          $disBtnClass  = ($myReaction === 'dislike') ? 'btn-danger' : 'btn-outline-danger';
          $likeTitle = $T('Лайків: ', 'Лайков: ', 'Likes: ') . $likes;
          $disTitle  = $T('Дизлайків: ', 'Дизлайков: ', 'Dislikes: ') . $dislikes;

          $canPromotePost = (
            $meId > 0
            && !$isPromoted
            && function_exists('reclama_is_enabled')
            && function_exists('reclama_allow_post_campaigns')
            && reclama_is_enabled($pdo)
            && reclama_allow_post_campaigns($pdo)
            && $authorId === $meId
          );

          $sponsoredLabel = $T('РЕКЛАМА', 'РЕКЛАМА', 'SPONSORED');
        ?>
        <div class="card card-app p-3 mb-3" id="post-<?= $pid ?>">
          <div class="d-flex justify-content-between align-items-start gap-2">
            <div class="d-flex align-items-center gap-2">
              <div class="vm-ava">
                <?php if ($ava !== ''): ?>
                  <img src="<?= h($ava) ?>" alt="" loading="lazy">
                <?php else: ?>
                  <div class="vm-ava-ph"><?= h($ini) ?></div>
                <?php endif; ?>
              </div>

              <div>
                <div class="post-author">
                  <?= h($fullName) ?>
                  <?php if ($postUsername !== ''): ?>
                    <span class="text-muted small"> @<?= h($postUsername) ?></span>
                  <?php endif; ?>
                </div>
                <div class="post-meta d-flex flex-wrap align-items-center gap-2">
                  <span><?= h((string)($p['created_at'] ?? '')) ?></span>
                  <?php if ($isPromoted): ?>
                    <span class="vm-sponsored-badge"><?= h($sponsoredLabel) ?></span>
                  <?php endif; ?>
                </div>
                <?php if ($isRepost): ?>
                  <div class="vm-repost-label"><?= h($T('Репост','Репост','Repost')) ?></div>
                <?php endif; ?>
              </div>
            </div>

            <?php if ($canManagePost): ?>
              <details class="vm-menu">
                <summary class="vm-menu-btn" aria-label="menu">⋯</summary>
                <div class="vm-menu-box">
                  <a class="vm-menu-item" href="/post_edit.php?id=<?= $pid ?>&back=<?= urlencode(current_uri()) ?>">
                    <?= h($T('Редагувати','Редактировать','Edit')) ?>
                  </a>

                  <form method="post" action="/functional/post/manage.php"
                        onsubmit="return confirm(<?= json_encode($confirmDelPost, JSON_UNESCAPED_UNICODE) ?>);">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= $pid ?>">
                    <input type="hidden" name="back" value="<?= h(current_uri()) ?>">
                    <button type="submit" class="vm-menu-item vm-menu-danger">
                      <?= h($T('Видалити','Удалить','Delete')) ?>
                    </button>
                  </form>
                </div>
              </details>
            <?php endif; ?>
          </div>

          <?php if ($isRepost): ?>
            <?php if (trim($bodyText) !== ''): ?>
              <div class="mt-2"><?= linkify_text($bodyText) ?></div>
            <?php endif; ?>

            <?php if ($firstUrl !== '' && $firstHash !== ''): ?>
              <?php render_link_preview_card($lp, $firstUrl, $firstHash); ?>
            <?php endif; ?>

            <div class="vm-repost-box mt-3">
              <div class="d-flex align-items-center gap-2">
                <div class="vm-ava-sm">
                  <?php if ($origAva !== ''): ?>
                    <img src="<?= h($origAva) ?>" alt="" loading="lazy">
                  <?php else: ?>
                    <div class="vm-ava-ph"><?= h($origIni) ?></div>
                  <?php endif; ?>
                </div>
                <div>
                  <div class="fw-semibold">
                    <?= h($origFullName) ?>
                    <?php if ($origUsername !== ''): ?>
                      <span class="text-muted small"> @<?= h($origUsername) ?></span>
                    <?php endif; ?>
                  </div>
                  <div class="text-muted small"><?= h($origCreated) ?></div>
                </div>
              </div>

              <?php if (trim((string)$origBody) !== ''): ?>
                <div class="mt-2"><?= linkify_text((string)$origBody) ?></div>
              <?php endif; ?>

              <?php if ($atts): ?>
                <?php
                  $galleryId = 'p' . $pid;
                  $imgs = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'image'));
                  $aud  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'audio'));
                  $vid  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'video'));
                  $fil  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'file'));
                ?>
                <div class="post-attachments mt-3" data-gallery-images="<?= h($galleryId) ?>">
                  <?php if ($imgs): ?>
                    <?php if (count($imgs) === 1): $a = $imgs[0]; ?>
                      <div class="attachments-single">
                        <a class="att-img att-img-single js-lightbox" href="<?= h((string)($a['path'] ?? '')) ?>" data-gallery="<?= h($galleryId) ?>" target="_blank" rel="noopener">
                          <img src="<?= h((string)($a['path'] ?? '')) ?>" alt="" loading="lazy">
                        </a>
                      </div>
                    <?php else: ?>
                      <div class="attachments-grid">
                        <?php foreach ($imgs as $a): ?>
                          <a class="att-img js-lightbox" href="<?= h((string)($a['path'] ?? '')) ?>" data-gallery="<?= h($galleryId) ?>" target="_blank" rel="noopener">
                            <img src="<?= h((string)($a['path'] ?? '')) ?>" alt="" loading="lazy">
                          </a>
                        <?php endforeach; ?>
                      </div>
                    <?php endif; ?>
                  <?php endif; ?>

                  <?php foreach ($aud as $a): ?>
                    <div class="mt-2">
                      <audio controls preload="none" class="w-100">
                        <source src="<?= h((string)($a['path'] ?? '')) ?>" type="<?= h((string)($a['mime'] ?? '')) ?>">
                      </audio>
                    </div>
                  <?php endforeach; ?>

                  <?php foreach ($vid as $a): ?>
                    <div class="mt-2">
                      <video controls preload="metadata" class="w-100 rounded-3"
                             playsinline webkit-playsinline
                             disablepictureinpicture
                             controlslist="nodownload noplaybackrate">
                        <source src="<?= h((string)($a['path'] ?? '')) ?>" type="<?= h((string)($a['mime'] ?? '')) ?>">
                      </video>
                    </div>
                  <?php endforeach; ?>

                  <?php if ($fil): ?>
                    <div class="mt-2 d-flex flex-column gap-1">
                      <?php foreach ($fil as $a): ?>
                        <a class="att-file" href="<?= h((string)($a['path'] ?? '')) ?>" target="_blank" rel="noopener">
                          <?= h(t('download')) ?>: <?= h((string)($a['original_name'] ?? '')) ?>
                        </a>
                      <?php endforeach; ?>
                    </div>
                  <?php endif; ?>
                </div>
              <?php endif; ?>

              <?php if ($poll): ?>
                <?php
                  $pollId = (int)($poll['id'] ?? 0);
                  $opts = $pollOptionsByPoll[$pollId] ?? [];
                  $myVoteOpt = $myPollVoteByPoll[$pollId] ?? 0;

                  $totalVotes = 0;
                  foreach ($opts as $o) $totalVotes += (int)($pollVotesByOption[(int)($o['id'] ?? 0)] ?? 0);
                ?>
                <div class="poll-box mt-3">
                  <div class="fw-semibold mb-2"><?= h((string)($poll['question'] ?? '')) ?></div>

                  <?php if ($canInteract && $opts): ?>
                    <?php if ($myVoteOpt <= 0): ?>
                      <form method="post" action="/poll_vote.php" class="vstack gap-2">
                        <?= csrf_field() ?>
                        <input type="hidden" name="poll_id" value="<?= $pollId ?>">

                        <?php foreach ($opts as $o): $oid = (int)($o['id'] ?? 0); ?>
                          <label class="poll-opt">
                            <input type="radio" name="option_id" value="<?= $oid ?>" required>
                            <span><?= h((string)($o['option_text'] ?? '')) ?></span>
                          </label>
                        <?php endforeach; ?>

                        <div class="d-flex align-items-center justify-content-between">
                          <button class="btn btn-sm btn-primary" type="submit"><?= h(t('poll_vote')) ?></button>
                          <div class="text-muted small"><?= h(t('poll_total_votes')) ?>: <?= $totalVotes ?></div>
                        </div>
                      </form>
                    <?php else: ?>
                      <div class="vstack gap-2">
                        <?php foreach ($opts as $o):
                          $oid = (int)($o['id'] ?? 0);
                          $cnt = (int)($pollVotesByOption[$oid] ?? 0);
                          $pct = $totalVotes > 0 ? (int)round(($cnt / $totalVotes) * 100) : 0;
                          $isMine = ($oid === (int)$myVoteOpt);
                        ?>
                          <div class="poll-res <?= $isMine ? 'mine' : '' ?>">
                            <div class="d-flex justify-content-between small mb-1">
                              <div><?= h((string)($o['option_text'] ?? '')) ?><?= $isMine ? ' • ✓' : '' ?></div>
                              <div class="text-muted"><?= $cnt ?> (<?= $pct ?>%)</div>
                            </div>
                            <div class="poll-bar">
                              <div class="poll-bar-fill" style="width: <?= $pct ?>%"></div>
                            </div>
                          </div>
                        <?php endforeach; ?>
                        <div class="text-muted small"><?= h(t('poll_total_votes')) ?>: <?= $totalVotes ?></div>
                      </div>
                    <?php endif; ?>
                  <?php elseif ($opts): ?>
                    <div class="text-muted small">
                      <?= h($T('Голосування недоступне.','Голосование недоступно.','Voting is not available.')) ?>
                    </div>
                  <?php endif; ?>
                </div>
              <?php endif; ?>
            </div>

          <?php else: ?>
            <?php if (trim($bodyText) !== ''): ?>
              <div class="mt-2"><?= linkify_text($bodyText) ?></div>
            <?php endif; ?>

            <?php if ($firstUrl !== '' && $firstHash !== ''): ?>
              <?php render_link_preview_card($lp, $firstUrl, $firstHash); ?>
            <?php endif; ?>

            <?php if ($atts): ?>
              <?php
                $galleryId = 'p' . $pid;
                $imgs = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'image'));
                $aud  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'audio'));
                $vid  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'video'));
                $fil  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'file'));
              ?>
              <div class="post-attachments mt-3" data-gallery-images="<?= h($galleryId) ?>">
                <?php if ($imgs): ?>
                  <?php if (count($imgs) === 1): $a = $imgs[0]; ?>
                    <div class="attachments-single">
                      <a class="att-img att-img-single js-lightbox" href="<?= h((string)($a['path'] ?? '')) ?>" data-gallery="<?= h($galleryId) ?>" target="_blank" rel="noopener">
                        <img src="<?= h((string)($a['path'] ?? '')) ?>" alt="" loading="lazy">
                      </a>
                    </div>
                  <?php else: ?>
                    <div class="attachments-grid">
                      <?php foreach ($imgs as $a): ?>
                        <a class="att-img js-lightbox" href="<?= h((string)($a['path'] ?? '')) ?>" data-gallery="<?= h($galleryId) ?>" target="_blank" rel="noopener">
                          <img src="<?= h((string)($a['path'] ?? '')) ?>" alt="" loading="lazy">
                        </a>
                      <?php endforeach; ?>
                    </div>
                  <?php endif; ?>
                <?php endif; ?>

                <?php foreach ($aud as $a): ?>
                  <div class="mt-2">
                    <audio controls preload="none" class="w-100">
                      <source src="<?= h((string)($a['path'] ?? '')) ?>" type="<?= h((string)($a['mime'] ?? '')) ?>">
                    </audio>
                  </div>
                <?php endforeach; ?>

                <?php foreach ($vid as $a): ?>
                  <div class="mt-2">
                    <video controls preload="metadata" class="w-100 rounded-3"
                           playsinline webkit-playsinline
                           disablepictureinpicture
                           controlslist="nodownload noplaybackrate">
                      <source src="<?= h((string)($a['path'] ?? '')) ?>" type="<?= h((string)($a['mime'] ?? '')) ?>">
                    </video>
                  </div>
                <?php endforeach; ?>

                <?php if ($fil): ?>
                  <div class="mt-2 d-flex flex-column gap-1">
                    <?php foreach ($fil as $a): ?>
                      <a class="att-file" href="<?= h((string)($a['path'] ?? '')) ?>" target="_blank" rel="noopener">
                        <?= h(t('download')) ?>: <?= h((string)($a['original_name'] ?? '')) ?>
                      </a>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>
            <?php endif; ?>

            <?php if ($poll): ?>
              <?php
                $pollId = (int)($poll['id'] ?? 0);
                $opts = $pollOptionsByPoll[$pollId] ?? [];
                $myVoteOpt = $myPollVoteByPoll[$pollId] ?? 0;

                $totalVotes = 0;
                foreach ($opts as $o) $totalVotes += (int)($pollVotesByOption[(int)($o['id'] ?? 0)] ?? 0);
              ?>
              <div class="poll-box mt-3">
                <div class="fw-semibold mb-2"><?= h((string)($poll['question'] ?? '')) ?></div>

                <?php if ($canInteract && $opts): ?>
                  <?php if ($myVoteOpt <= 0): ?>
                    <form method="post" action="/poll_vote.php" class="vstack gap-2">
                      <?= csrf_field() ?>
                      <input type="hidden" name="poll_id" value="<?= $pollId ?>">

                      <?php foreach ($opts as $o): $oid = (int)($o['id'] ?? 0); ?>
                        <label class="poll-opt">
                          <input type="radio" name="option_id" value="<?= $oid ?>" required>
                          <span><?= h((string)($o['option_text'] ?? '')) ?></span>
                        </label>
                      <?php endforeach; ?>

                      <div class="d-flex align-items-center justify-content-between">
                        <button class="btn btn-sm btn-primary" type="submit"><?= h(t('poll_vote')) ?></button>
                        <div class="text-muted small"><?= h(t('poll_total_votes')) ?>: <?= $totalVotes ?></div>
                      </div>
                    </form>
                  <?php else: ?>
                    <div class="vstack gap-2">
                      <?php foreach ($opts as $o):
                        $oid = (int)($o['id'] ?? 0);
                        $cnt = (int)($pollVotesByOption[$oid] ?? 0);
                        $pct = $totalVotes > 0 ? (int)round(($cnt / $totalVotes) * 100) : 0;
                        $isMine = ($oid === (int)$myVoteOpt);
                      ?>
                        <div class="poll-res <?= $isMine ? 'mine' : '' ?>">
                          <div class="d-flex justify-content-between small mb-1">
                            <div><?= h((string)($o['option_text'] ?? '')) ?><?= $isMine ? ' • ✓' : '' ?></div>
                            <div class="text-muted"><?= $cnt ?> (<?= $pct ?>%)</div>
                          </div>
                          <div class="poll-bar">
                            <div class="poll-bar-fill" style="width: <?= $pct ?>%"></div>
                          </div>
                        </div>
                      <?php endforeach; ?>
                      <div class="text-muted small"><?= h(t('poll_total_votes')) ?>: <?= $totalVotes ?></div>
                    </div>
                  <?php endif; ?>
                <?php elseif ($opts): ?>
                  <div class="text-muted small">
                    <?= h($T('Голосування недоступне.','Голосование недоступно.','Voting is not available.')) ?>
                  </div>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          <?php endif; ?>

          <div class="post-actions mt-3 d-flex align-items-center gap-2 flex-wrap">
            <?php if ($canInteract && !$vmCommentBlocked): ?>
              <form method="post" action="/post_react.php" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="post_id" value="<?= $pid ?>">
                <input type="hidden" name="reaction" value="like">
                <input type="hidden" name="back" value="<?= h($backToPost) ?>">
                <button type="submit"
                        class="btn btn-sm <?= h($likeBtnClass) ?>"
                        data-post="<?= $pid ?>" data-react="like"
                        title="<?= h($likeTitle) ?>"
                        aria-label="<?= h(t('like')) ?>">
                  👍 <span class="count" id="likes-<?= $pid ?>"><?= $likes ?></span>
                </button>
              </form>

              <form method="post" action="/post_react.php" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="post_id" value="<?= $pid ?>">
                <input type="hidden" name="reaction" value="dislike">
                <input type="hidden" name="back" value="<?= h($backToPost) ?>">
                <button type="submit"
                        class="btn btn-sm <?= h($disBtnClass) ?>"
                        data-post="<?= $pid ?>" data-react="dislike"
                        title="<?= h($disTitle) ?>"
                        aria-label="<?= h(t('dislike')) ?>">
                  👎 <span class="count" id="dislikes-<?= $pid ?>"><?= $dislikes ?></span>
                </button>
              </form>

              <?php if ($hasRepost): ?>
                <?php
                  $targetRepostId = $pid;
                  if ($isRepost) $targetRepostId = (int)($p['repost_post_id'] ?? 0);
                ?>
                <form method="post" action="/post_repost.php" class="d-inline">
                  <?= csrf_field() ?>
                  <input type="hidden" name="post_id" value="<?= $targetRepostId ?>">
                  <input type="hidden" name="back" value="<?= h($backToPost) ?>">
                  <button type="submit" class="btn btn-sm btn-outline-secondary">
                    🔁 <?= h($T('Репост','Репост','Repost')) ?>
                  </button>
                </form>
              <?php endif; ?>

              <?php if ($canPromotePost): ?>
                <a class="btn btn-sm btn-outline-warning" href="/functional/reclama/create.php?post_id=<?= $pid ?>">
                  📣 <?= h($T('Рекламувати', 'Рекламировать', 'Promote')) ?>
                </a>
              <?php endif; ?>

              <?php if ($isPromoted && $promotedClickUrl !== ''): ?>
                <a class="btn btn-sm btn-outline-primary"
                   href="<?= h($promotedClickUrl) ?>"
                   target="_blank"
                   rel="noopener nofollow sponsored">
                  ↗ <?= h($T('Перейти', 'Перейти', 'Open')) ?>
                </a>
              <?php endif; ?>
            <?php else: ?>
              <button type="button" class="btn btn-sm btn-outline-success" disabled>
                👍 <span class="count"><?= $likes ?></span>
              </button>
              <button type="button" class="btn btn-sm btn-outline-danger" disabled>
                👎 <span class="count"><?= $dislikes ?></span>
              </button>
            <?php endif; ?>
          </div>

          <div class="comments-box mt-3">
            <div class="comments-title"><?= h(t('comments')) ?></div>

            <?php if ($canInteract && !$vmCommentBlocked): ?>
              <form method="post" action="/functional/comment/create.php" enctype="multipart/form-data" class="vstack gap-2 mt-2">
                <?= csrf_field() ?>
                <input type="hidden" name="post_id" value="<?= $pid ?>">
                <input type="hidden" name="parent_id" value="">
                <input type="hidden" name="back" value="<?= h($backToPost) ?>">

                <div class="vm-emoji-wrap">
                  <textarea class="form-control js-emoji-target" name="body" rows="2" placeholder="<?= h(t('write_comment')) ?>"></textarea>
                </div>

                <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between">
                  <label class="btn btn-sm btn-outline-secondary mb-0">
                    <?= h(t('attach_files')) ?>
                    <input type="file" name="files[]" multiple hidden
                           accept="image/*,audio/*,video/*,.pdf,.zip,.rar,.7z,.txt,.doc,.docx,.xls,.xlsx">
                  </label>
                  <button class="btn btn-sm btn-primary" type="submit"><?= h(t('send')) ?></button>
                </div>
              </form>
            <?php else: ?>
              <div class="text-muted small mt-2">
                <?= h($T('Коментування недоступне.','Комментирование недоступно.','Commenting is not available.')) ?>
              </div>
            <?php endif; ?>

            <div class="comments-list mt-3">
              <?php
                $top = $commentsByPost[$pid] ?? [];
                foreach ($top as $c) {
                  render_comment_profile($c, $repliesByParent, $commentAttById, $previewByHash, $pid, $meId, $isAdmin, $canInteract, $T, false);
                }
              ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
