<?php
declare(strict_types=1);

$avatarOpenLabel = $T('Відкрити аватар','Открыть аватар','Open avatar');
$avatarCloseLabel = $T('Закрити','Закрыть','Close');
$avatarModalLabel = $T('Збільшена аватарка профілю','Увеличенный аватар профиля','Large profile avatar');
$avatarModalId = 'profileAvatarModal_' . (int)$profileUserId;
$avatarOpenBtnId = 'profileAvatarOpenBtn_' . (int)$profileUserId;
$avatarCloseBtnId = 'profileAvatarCloseBtn_' . (int)$profileUserId;
?>
<div class="card card-app p-0 mb-3 overflow-hidden profile-hero">
      <div class="profile-cover">
        <?php if (trim($profileCover) !== ''): ?>
          <img class="profile-cover-bg" src="<?= h($profileCover) ?>" alt="" loading="lazy">
          <img class="profile-cover-img" src="<?= h($profileCover) ?>" alt="" loading="lazy">
        <?php else: ?>
          <div class="profile-cover-empty"></div>
        <?php endif; ?>
      </div>

      <div class="profile-avatar">
        <?php if (trim($profileAvatar) !== ''): ?>
          <button type="button"
                  class="profile-avatar-link profile-avatar-button"
                  id="<?= h($avatarOpenBtnId) ?>"
                  aria-controls="<?= h($avatarModalId) ?>"
                  aria-haspopup="dialog"
                  aria-label="<?= h($avatarOpenLabel) ?>">
            <img src="<?= h($profileAvatar) ?>" alt="<?= h($profileDisplayName) ?>" loading="lazy">
          </button>
        <?php else: ?>
          <div class="profile-avatar-placeholder d-flex align-items-center justify-content-center fw-bold">
            <?= h($profileInitials) ?>
          </div>
        <?php endif; ?>
      </div>

      <div class="p-3 profile-head">
        <div class="fw-semibold fs-5 d-flex align-items-center gap-2 flex-wrap">
          <span><?= h($profileDisplayName) ?></span>
          <?php if ($isPrivate): ?>
            <span class="badge bg-secondary"><?= h($T('Закритий профіль','Закрытый профиль','Private profile')) ?></span>
          <?php endif; ?>
        </div>
        <div class="text-muted">@<?= h($profileUsername) ?></div>
        <div class="profile-presence">
          <span class="profile-presence-dot <?= $profileIsOnline ? 'is-online' : 'is-offline' ?>"></span>
          <span class="<?= $profileIsOnline ? 'text-success' : 'text-muted' ?>"><?= h($profilePresenceText) ?></span>
        </div>

        <?php if (!$isPrivateStub): ?>
          <?php if ($status !== ''): ?>
            <div class="mt-1"><?= h($status) ?></div>
          <?php endif; ?>

          <?php
            $location = '';
            if ($city !== '' && $country !== '') $location = $city . ', ' . $country;
            elseif ($city !== '') $location = $city;
            elseif ($country !== '') $location = $country;

            $meta = [];
            if ($location !== '') $meta[] = $location;
            if ($birth !== '') $meta[] = $birth;
            if ($genderLbl !== '') $meta[] = $genderLbl;
          ?>
          <?php if ($meta): ?>
            <div class="text-muted small mt-1"><?= h(implode(' • ', $meta)) ?></div>
          <?php endif; ?>

          <?php if ($education !== '' || $workplace !== ''): ?>
            <div class="text-muted small mt-2">
              <?php if ($education !== ''): ?>
                <div><?= h($T('Освіта','Образование','Education')) ?>: <?= h($education) ?></div>
              <?php endif; ?>
              <?php if ($workplace !== ''): ?>
                <div><?= h($T('Місце роботи','Место работы','Workplace')) ?>: <?= h($workplace) ?></div>
              <?php endif; ?>
            </div>
          <?php endif; ?>

          <?php if ($about !== ''): ?>
            <div class="text-muted small mt-2" style="white-space:pre-wrap;"><?= h($about) ?></div>
          <?php endif; ?>
        <?php endif; ?>

        <?php
          $viewerCanManageRestrictions = ar_is_staff_can_manage(is_array($me ?? null) ? $me : null) && !$isOwner;
          $viewerRestrictionUrl = $viewerCanManageRestrictions
            ? ('/admin/restrictions/?user_id=' . (int)$profileUserId . '&back=' . rawurlencode(current_uri()))
            : '';

          $viewerRestrictionState = (is_array($me ?? null) && !empty($me['id']) && isset($pdo) && $pdo instanceof PDO && function_exists('ar_get_state'))
            ? ar_get_state($pdo, (int)$me['id'])
            : [];
          $viewerPmBlocked = is_array($viewerRestrictionState) && function_exists('ar_is_action_blocked')
            ? ar_is_action_blocked($viewerRestrictionState, 'messages')
            : false;
          $viewerPmBlockedText = $viewerPmBlocked && function_exists('ar_action_error')
            ? ar_action_error($viewerRestrictionState, 'messages')
            : '';
        ?>

        <?php if (!$isOwner): ?>
          <div class="mt-3 d-flex gap-2 flex-wrap align-items-center profile-actions-bar">
            <?php if ($viewerCanManageRestrictions): ?>
              <a class="btn btn-sm btn-outline-danger" href="<?= h($viewerRestrictionUrl) ?>">⛔ <?= h($T('Блокування', 'Блокировки', 'Restrictions')) ?></a>
            <?php endif; ?>
            <?php if ($meId <= 0): ?>
              <a class="btn btn-sm btn-primary" href="/login.php?to=<?= urlencode(current_uri()) ?>">
                <?= h($T('Увійти, щоб додати в друзі','Войти, чтобы добавить в друзья','Login to add as friend')) ?>
              </a>

            <?php elseif ($isPrivateStub): ?>
              <?php
                $back = current_uri();
                $confirmUnfriend = $T('Видалити з друзів?', 'Удалить из друзей?', 'Remove from friends?');
              ?>

              <?php if (!$friendsReady): ?>
                <span class="text-muted small"><?= h($T('Модуль друзів тимчасово недоступний.','Модуль друзей временно недоступен.','Friends module is temporarily unavailable.')) ?></span>
              <?php else: ?>
                <?php if ($areFriends): ?>
                  <span class="badge bg-success"><?= h($T('Ви друзі','Вы друзья','Friends')) ?></span>

                  <form method="post" action="/functional/friends/action.php" class="m-0"
                        onsubmit="return confirm(<?= json_encode($confirmUnfriend, JSON_UNESCAPED_UNICODE) ?>);">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="remove_friend">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-outline-danger"><?= h($T('Видалити з друзів','Удалить из друзей','Remove friend')) ?></button>
                  </form>

                <?php elseif ($incomingPending): ?>
                  <span class="badge bg-warning text-dark"><?= h($T('Вам надіслано запит','Вам отправили заявку','Incoming request')) ?></span>

                  <form method="post" action="/functional/friends/action.php" class="m-0">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="accept_friend">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-success"><?= h($T('Прийняти','Принять','Accept')) ?></button>
                  </form>

                  <form method="post" action="/functional/friends/action.php" class="m-0">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="decline_friend">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-outline-danger"><?= h($T('Відхилити','Отклонить','Decline')) ?></button>
                  </form>

                <?php elseif ($outgoingPending): ?>
                  <span class="badge bg-secondary"><?= h($T('Запит надіслано','Заявка отправлена','Request sent')) ?></span>

                  <form method="post" action="/functional/friends/action.php" class="m-0">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="cancel_friend">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-outline-secondary"><?= h($T('Скасувати','Отменить','Cancel')) ?></button>
                  </form>

                <?php else: ?>
                  <form method="post" action="/functional/friends/action.php" class="m-0">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="send_friend">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-primary"><?= h($T('Додати в друзі','Добавить в друзья','Add friend')) ?></button>
                  </form>

                  <?php if ($outgoingDeclined): ?>
                    <span class="badge bg-light text-dark border">
                      <?= h($T('Запит відхилено','Заявка отклонена','Request declined')) ?>
                    </span>
                  <?php endif; ?>
                <?php endif; ?>
              <?php endif; ?>

              <div class="vm-private-note w-100">
                <?= h($T('Користувач закрив свій профіль.','Пользователь закрыл свой профиль.','This user closed their profile.')) ?>
              </div>

            <?php elseif (!$friendsReady): ?>
              <?php $pmLabel = $T('Приватне повідомлення','Личное сообщение','Private message'); ?>
              <?php if ($viewerPmBlocked): ?>
                <button type="button" class="btn btn-sm btn-outline-secondary" disabled title="<?= h($viewerPmBlockedText) ?>">✉️ <?= h($pmLabel) ?></button>
              <?php else: ?>
                <a class="btn btn-sm btn-outline-success" href="/messages/?u=<?= urlencode($profileUsername) ?>">✉️ <?= h($pmLabel) ?></a>
              <?php endif; ?>

            <?php else: ?>
              <?php
                $back = current_uri();
                $confirmUnfriend = $T('Видалити з друзів?', 'Удалить из друзей?', 'Remove from friends?');

                $noFollowBecausePending = ($incomingPending || $outgoingPending);
                $showFollow = (!$areFriends && !$noFollowBecausePending);

                $pmLabel = $T('Приватне повідомлення','Личное сообщение','Private message');
              ?>

              <?php if ($viewerPmBlocked): ?>
                <button type="button" class="btn btn-sm btn-outline-secondary" disabled title="<?= h($viewerPmBlockedText) ?>">✉️ <?= h($pmLabel) ?></button>
              <?php else: ?>
                <a class="btn btn-sm btn-outline-success" href="/messages/?u=<?= urlencode($profileUsername) ?>">✉️ <?= h($pmLabel) ?></a>
              <?php endif; ?>

              <?php if ($areFriends): ?>
                <span class="badge bg-success"><?= h($T('Ви друзі','Вы друзья','Friends')) ?></span>

                <form method="post" action="/functional/friends/action.php" class="m-0"
                      onsubmit="return confirm(<?= json_encode($confirmUnfriend, JSON_UNESCAPED_UNICODE) ?>);">
                  <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                  <input type="hidden" name="do" value="remove_friend">
                  <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                  <input type="hidden" name="back" value="<?= h($back) ?>">
                  <button class="btn btn-sm btn-outline-danger"><?= h($T('Видалити з друзів','Удалить из друзей','Remove friend')) ?></button>
                </form>

              <?php elseif ($incomingPending): ?>
                <span class="badge bg-warning text-dark"><?= h($T('Вам надіслано запит','Вам отправили заявку','Incoming request')) ?></span>

                <form method="post" action="/functional/friends/action.php" class="m-0">
                  <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                  <input type="hidden" name="do" value="accept_friend">
                  <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                  <input type="hidden" name="back" value="<?= h($back) ?>">
                  <button class="btn btn-sm btn-success"><?= h($T('Прийняти','Принять','Accept')) ?></button>
                </form>

                <form method="post" action="/functional/friends/action.php" class="m-0">
                  <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                  <input type="hidden" name="do" value="decline_friend">
                  <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                  <input type="hidden" name="back" value="<?= h($back) ?>">
                  <button class="btn btn-sm btn-outline-danger"><?= h($T('Відхилити','Отклонить','Decline')) ?></button>
                </form>

              <?php elseif ($outgoingPending): ?>
                <span class="badge bg-secondary"><?= h($T('Запит надіслано','Заявка отправлена','Request sent')) ?></span>

                <form method="post" action="/functional/friends/action.php" class="m-0">
                  <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                  <input type="hidden" name="do" value="cancel_friend">
                  <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                  <input type="hidden" name="back" value="<?= h($back) ?>">
                  <button class="btn btn-sm btn-outline-secondary"><?= h($T('Скасувати','Отменить','Cancel')) ?></button>
                </form>

              <?php else: ?>
                <form method="post" action="/functional/friends/action.php" class="m-0">
                  <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                  <input type="hidden" name="do" value="send_friend">
                  <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                  <input type="hidden" name="back" value="<?= h($back) ?>">
                  <button class="btn btn-sm btn-primary"><?= h($T('Додати в друзі','Добавить в друзья','Add friend')) ?></button>
                </form>

                <?php if ($outgoingDeclined): ?>
                  <span class="badge bg-light text-dark border">
                    <?= h($T('Запит відхилено','Заявка отклонена','Request declined')) ?>
                  </span>
                <?php endif; ?>
              <?php endif; ?>

              <?php if ($showFollow): ?>
                <?php if (!$isFollowing): ?>
                  <form method="post" action="/functional/friends/action.php" class="m-0">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="follow">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-outline-primary"><?= h($T('Підписатися','Подписаться','Follow')) ?></button>
                  </form>
                <?php else: ?>
                  <span class="badge bg-info text-dark"><?= h($T('Ви підписані','Вы подписаны','Following')) ?></span>
                  <form method="post" action="/functional/friends/action.php" class="m-0">
                    <input type="hidden" name="csrf" value="<?= h($fcsrf) ?>">
                    <input type="hidden" name="do" value="unfollow">
                    <input type="hidden" name="user_id" value="<?= (int)$profileUserId ?>">
                    <input type="hidden" name="back" value="<?= h($back) ?>">
                    <button class="btn btn-sm btn-outline-secondary"><?= h($T('Відписатися','Отписаться','Unfollow')) ?></button>
                  </form>
                <?php endif; ?>
              <?php endif; ?>

            <?php endif; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>


<?php if (trim($profileAvatar) !== ''): ?>
  <style>
    .profile-avatar-button{
      border:0;
      padding:0;
      background:transparent;
      display:block;
      cursor:zoom-in;
    }
    .profile-avatar-modal{
      position:fixed;
      inset:0;
      z-index:1200;
    }
    .profile-avatar-modal[hidden]{
      display:none !important;
    }
    .profile-avatar-modal__backdrop{
      position:absolute;
      inset:0;
      background:rgba(0,0,0,.82);
    }
    .profile-avatar-modal__dialog{
      position:relative;
      z-index:1;
      min-height:100%;
      display:flex;
      align-items:center;
      justify-content:center;
      padding:20px;
    }
    .profile-avatar-modal__inner{
      position:relative;
      max-width:min(92vw, 980px);
      max-height:90vh;
      display:flex;
      align-items:center;
      justify-content:center;
    }
    .profile-avatar-modal__img{
      display:block;
      max-width:100%;
      max-height:90vh;
      width:auto;
      height:auto;
      border-radius:18px;
      box-shadow:0 20px 60px rgba(0,0,0,.45);
      background:#111;
    }
    .profile-avatar-modal__close{
      position:absolute;
      top:10px;
      right:10px;
      z-index:2;
      width:42px;
      height:42px;
      border:0;
      border-radius:999px;
      background:rgba(17,17,17,.72);
      color:#fff;
      font-size:28px;
      line-height:1;
      display:flex;
      align-items:center;
      justify-content:center;
      cursor:pointer;
    }
    .profile-avatar-modal__close:hover{
      background:rgba(17,17,17,.88);
    }
  </style>

  <div class="profile-avatar-modal"
       id="<?= h($avatarModalId) ?>"
       hidden
       aria-hidden="true">
    <div class="profile-avatar-modal__backdrop" data-avatar-modal-close="1"></div>

    <div class="profile-avatar-modal__dialog">
      <div class="profile-avatar-modal__inner"
           role="dialog"
           aria-modal="true"
           aria-label="<?= h($avatarModalLabel) ?>">
        <button type="button"
                class="profile-avatar-modal__close"
                id="<?= h($avatarCloseBtnId) ?>"
                aria-label="<?= h($avatarCloseLabel) ?>">
          &times;
        </button>

        <img class="profile-avatar-modal__img"
             src="<?= h($profileAvatar) ?>"
             alt="<?= h($profileDisplayName) ?>"
             loading="eager">
      </div>
    </div>
  </div>

  <script>
    (function () {
      var openBtn = document.getElementById(<?= json_encode($avatarOpenBtnId, JSON_UNESCAPED_UNICODE) ?>);
      var closeBtn = document.getElementById(<?= json_encode($avatarCloseBtnId, JSON_UNESCAPED_UNICODE) ?>);
      var modal = document.getElementById(<?= json_encode($avatarModalId, JSON_UNESCAPED_UNICODE) ?>);
      if (!openBtn || !closeBtn || !modal) return;

      var previousOverflow = '';

      function openModal() {
        previousOverflow = document.body.style.overflow || '';
        modal.hidden = false;
        modal.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
        closeBtn.focus({ preventScroll: true });
      }

      function closeModal() {
        modal.hidden = true;
        modal.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = previousOverflow;
        openBtn.focus({ preventScroll: true });
      }

      openBtn.addEventListener('click', function () {
        openModal();
      });

      closeBtn.addEventListener('click', function () {
        closeModal();
      });

      modal.addEventListener('click', function (e) {
        if (e.target && e.target.closest('[data-avatar-modal-close="1"]')) {
          closeModal();
        }
      });

      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && !modal.hidden) {
          closeModal();
        }
      });
    })();
  </script>
<?php endif; ?>