<?php include 'header.php'; ?>

<head>
  <meta charset="UTF-8">
</head>

<style>
  /* ---------------------------------------
   BASE RESET & ROOT
--------------------------------------- */
  *,
  *::before,
  *::after {
    box-sizing: border-box;
  }

  html {
    height: 100%;
    height: -webkit-fill-available;
    width: 100%;
  }

  body {
    margin: 0;
    height: 100%;
    height: -webkit-fill-available;
    width: 100%;
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
  }

  ::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }

  ::-webkit-scrollbar-track {
    background: transparent;
  }

  ::-webkit-scrollbar-thumb {
    background: #2a3942;
    border-radius: 4px;
  }

  /* ---------------------------------------
   APP SHELL
--------------------------------------- */
  #app {
    display: flex;
    flex: 1;
    min-height: 0;
    margin: 15px 50px;
    border-radius: 12px;
    overflow: hidden;
    height: calc(100vh - 80px);
    height: calc(100dvh - 80px);
    background: #111b21;
    color: #e9edef;
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
  }

  /* ---------------------------------------
   SIDEBAR
--------------------------------------- */
  #wsidebar {
    width: 360px;
    min-width: 260px;
    max-width: 360px;
    display: flex;
    flex-direction: column;
    background: #111b21;
    border-right: 1px solid #2a3942;
    flex-shrink: 0;
    height: 100%;
    overflow: hidden;
    transition: transform .25s ease;
  }

  /* ---------------------------------------
   CHAT AREA
--------------------------------------- */
  #chatArea {
    flex: 1;
    min-width: 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background: #0b141a;
    position: relative;
    overflow: hidden;
    /* KEY: chat area itself never scrolls */
    height: 100%;
  }

  /* Wallpaper dots */
  #chatArea::before {
    content: '';
    position: absolute;
    inset: 0;
    opacity: .04;
    background-image: radial-gradient(circle, #fff 1px, transparent 1px);
    background-size: 24px 24px;
    pointer-events: none;
    z-index: 0;
  }

  /* ---------------------------------------
   MESSAGES SCROLL AREA — only this scrolls
--------------------------------------- */
  #chatMessages {
    flex: 1;
    min-height: 0;
    /* critical for flex children */
    overflow-y: auto;
    overflow-x: hidden;
    padding: 16px 12px;
    display: flex;
    flex-direction: column;
    gap: 2px;
    position: relative;
    z-index: 1;
  }

  /* ---------------------------------------
   BUBBLES
--------------------------------------- */
  .ofcrm-chat-msg-in {
    border-radius: 0 10px 10px 10px;
    background: #202c33;
  }

  .ofcrm-chat-msg-out {
    border-radius: 10px 0 10px 10px;
    background: #005c4b;
  }

  /* ---------------------------------------
   STATUS DOTS
--------------------------------------- */
  .ofcrm-chat-dot-on {
    width: 10px;
    height: 10px;
    background: #00a884;
    border-radius: 50%;
    border: 2px solid #202c33;
    flex-shrink: 0;
  }

  .ofcrm-chat-dot-off {
    width: 10px;
    height: 10px;
    background: #8696a0;
    border-radius: 50%;
    border: 2px solid #202c33;
    flex-shrink: 0;
  }

  /* ---------------------------------------
   CONTEXT MENU
--------------------------------------- */
  #ctxMenu {
    position: fixed;
    background: #1d2f38;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, .6);
    z-index: 9000;
    min-width: 190px;
    max-width: calc(100vw - 16px);
    overflow: hidden;
    border: 1px solid #2a3942;
    display: none;
  }

  .ofcrm-chat-ctx-item {
    padding: 11px 18px;
    cursor: pointer;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #e9edef;
    transition: background .12s;
  }

  .ofcrm-chat-ctx-item:hover {
    background: #2a3942;
  }

  .ofcrm-chat-ctx-item.ofcrm-chat-danger {
    color: #f15c6d;
  }

  /* ---------------------------------------
   COPY BUTTON (per-message)
--------------------------------------- */
  .ofcrm-chat-copy-btn {
    opacity: 0;
    transition: opacity .15s, background .12s, color .12s;
    background: none;
    border: none;
    cursor: pointer;
    color: #8696a0;
    font-size: 14px;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    align-self: flex-end;
    margin-bottom: 4px;
  }

  .ofcrm-chat-msg-wrap:hover .ofcrm-chat-copy-btn {
    opacity: 1;
  }

  .ofcrm-chat-copy-btn:hover {
    background: #2a3942 !important;
    color: #00a884 !important;
  }

  /* ---------------------------------------
   REACTIONS
--------------------------------------- */
  .ofcrm-chat-react-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    margin-top: 4px;
  }

  .ofcrm-chat-react-chip {
    background: #182229;
    border: 1px solid #2a3942;
    border-radius: 12px;
    padding: 2px 8px;
    font-size: 12px;
    cursor: pointer;
    transition: background .12s;
    user-select: none;
  }

  .ofcrm-chat-react-chip:hover {
    background: #2a3942;
  }

  .ofcrm-chat-react-chip.ofcrm-chat-mine {
    border-color: #00a884;
    background: #0a2e28;
  }

  /* ---------------------------------------
   MISC UI
--------------------------------------- */
  .ofcrm-chat-mention {
    color: #00a884;
    font-weight: 700;
  }

  .ofcrm-chat-sched-badge {
    background: #2a3942;
    color: #8696a0;
    font-size: 10px;
    border-radius: 6px;
    padding: 1px 6px;
    white-space: nowrap;
  }

  #pinnedBanner {
    border-left: 3px solid #00a884;
    background: #182229;
  }

  .ofcrm-chat-msg-wrap.ofcrm-chat-selected {
    background: rgba(0, 168, 132, .12);
    border-radius: 8px;
  }

  /* Typing dots */
  .ofcrm-chat-tdot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #8696a0;
    display: inline-block;
    animation: tdot .9s infinite;
  }

  .ofcrm-chat-tdot:nth-child(2) {
    animation-delay: .15s
  }

  .ofcrm-chat-tdot:nth-child(3) {
    animation-delay: .3s
  }

  @keyframes tdot {

    0%,
    100% {
      transform: translateY(0)
    }

    50% {
      transform: translateY(-5px)
    }
  }

  /* Image overlay */
  #imgOverlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .9);
    z-index: 10000;
    align-items: center;
    justify-content: center;
  }

  #imgOverlay.ofcrm-chat-show {
    display: flex;
  }

  /* ---------------------------------------
   MODAL SYSTEM
--------------------------------------- */
  .ofcrm-chat-modal-wrap {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .65);
    z-index: 8000;
    align-items: center;
    justify-content: center;
    padding: 16px;
  }

  .ofcrm-chat-modal-wrap.ofcrm-chat-open {
    display: flex;
  }

  .ofcrm-chat-modal-box {
    background: #202c33;
    border-radius: 16px;
    padding: 24px;
    width: 100%;
    max-width: 440px;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
  }

  /* Emoji grid */
  .ofcrm-chat-emoji-grid {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 3px;
  }

  .ofcrm-chat-emoji-btn {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    padding: 4px;
    border-radius: 6px;
    transition: background .12s;
  }

  .ofcrm-chat-emoji-btn:hover {
    background: #2a3942;
  }

  /* Admin badge */
  .ofcrm-chat-admin-badge {
    background: #1d3a2e;
    color: #00a884;
    font-size: 10px;
    border-radius: 4px;
    padding: 1px 5px;
    font-weight: 700;
  }

  /* Toast */
  #toast {
    position: fixed;
    bottom: 24px;
    left: 50%;
    transform: translateX(-50%);
    background: #1d2f38;
    color: #fff;
    font-size: 13px;
    padding: 8px 20px;
    border-radius: 99px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, .4);
    z-index: 9999;
    display: none;
    border: 1px solid #2a3942;
    max-width: calc(100vw - 32px);
    text-align: center;
  }

  /* Pinned panel */
  #pinnedPanel {
    position: absolute;
    top: 64px;
    right: 0;
    width: 300px;
    height: calc(100% - 64px);
    background: #182229;
    border-left: 1px solid #2a3942;
    z-index: 200;
    display: none;
    flex-direction: column;
    overflow: hidden;
  }

  #pinnedPanel.ofcrm-chat-open {
    display: flex;
  }

  /* datetime-local */
  input[type="datetime-local"] {
    background: #2a3942;
    border: none;
    color: #fff;
    border-radius: 8px;
    padding: 10px 14px;
    outline: none;
    width: 100%;
    font-size: 14px;
  }

  /* Tab active */
  .ofcrm-chat-tab-active {
    background: #00a884 !important;
    color: #fff !important;
  }

  .ofcrm-chat-tab-btn {
    border: none;
    cursor: pointer;
    border-radius: 99px;
    padding: 5px 14px;
    font-size: 12px;
    font-weight: 600;
    white-space: nowrap;
    transition: all .15s;
    background: none;
    color: #fff;
  }

  /* Attach preview */
  #attachPreview {
    display: none;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px;
    padding: 10px 16px;
    border-top: 1px solid #2a3942;
  }

  #attachPreview .ofcrm-chat-attach-list {
    display: flex;
    gap: 8px;
    overflow-x: auto;
    padding-right: 4px;
    min-height: 56px;
  }

  #attachPreview .ofcrm-chat-attach-item {
    position: relative;
    min-width: 56px;
    width: 56px;
    height: 56px;
    border-radius: 12px;
    background: #2a3942;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  #attachPreview .ofcrm-chat-attach-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  #attachPreview .ofcrm-chat-attach-item .ofcrm-chat-attach-remove {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background: rgba(0, 0, 0, .65);
    border: none;
    color: #fff;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }

  #attachPreview .ofcrm-chat-attach-doc {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 12px;
    border-radius: 12px;
    background: #111b21;
    min-width: 180px;
  }

  #attachPreview .ofcrm-chat-attach-doc-icon {
    font-size: 22px;
    color: #60a5fa;
    flex-shrink: 0;
  }

  #attachPreview .ofcrm-chat-attach-doc-info {
    overflow: hidden;
  }

  #attachPreview .ofcrm-chat-attach-doc-info p {
    margin: 0;
    color: #fff;
    font-size: 13px;
    line-height: 1.2;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  #attachPreview .ofcrm-chat-attach-doc-info span {
    color: #8696a0;
    font-size: 11px;
  }

  #chatMessages.ofcrm-chat-empty {
    justify-content: center;
  }

  #chatMessages.ofcrm-chat-empty>div {
    flex: 1;
    min-height: 100%;
  }

  #groupMembers {
    display: none;
    gap: 8px;
    padding: 10px 12px;
    overflow-x: auto;
    border-bottom: 1px solid #2a3942;
    background: #111b21;
    flex-shrink: 0;
  }

  #groupMembers .ofcrm-chat-group-member {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 10px;
    border-radius: 999px;
    background: #182229;
    white-space: nowrap;
    color: #e9edef;
    font-size: 12px;
  }

  #groupMembers .ofcrm-chat-group-member img {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    object-fit: cover;
  }

  #emojiPicker {
    max-height: 260px;
    overflow-y: auto;
  }

  /* ---------------------------------------
   SCROLL-TO-BOTTOM BUTTON
--------------------------------------- */
  #scrollDownBtn {
    position: absolute;
    bottom: 80px;
    right: 16px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #202c33;
    border: 1px solid #2a3942;
    color: #e9edef;
    font-size: 18px;
    cursor: pointer;
    z-index: 50;
    display: none;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 12px rgba(0, 0, 0, .4);
    transition: background .15s, transform .15s;
  }

  #scrollDownBtn:hover {
    background: #2a3942;
    transform: translateY(-2px);
  }

  #scrollDownBtn.ofcrm-chat-show {
    display: flex;
  }

  #scrollDownBtn .ofcrm-chat-unread-dot {
    position: absolute;
    top: -4px;
    right: -4px;
    background: #00a884;
    color: #fff;
    font-size: 10px;
    font-weight: 700;
    border-radius: 99px;
    padding: 1px 5px;
    min-width: 18px;
    text-align: center;
    display: none;
  }

  #scrollDownBtn .ofcrm-chat-unread-dot.ofcrm-chat-show {
    display: block;
  }

  /* ---------------------------------------
   IMAGE CONTEXT MENU
--------------------------------------- */
  #imageMenu {
    display: none;
    position: fixed;
    background: #202c33;
    border-radius: 10px;
    overflow: hidden;
    z-index: 9999;
    min-width: 160px;
    border: 1px solid #2a3942;
    box-shadow: 0 4px 20px rgba(0, 0, 0, .5);
  }

  #imageMenu div {
    padding: 12px 16px;
    cursor: pointer;
    font-size: 14px;
    color: #e9edef;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: background .12s;
  }

  #imageMenu div:hover {
    background: #2a3942;
  }

  /* ---------------------------------------
   MOBILE — sidebar overlay
--------------------------------------- */
  @media (max-width: 700px) {
    #wsidebar {
      position: fixed;
      inset: 0;
      z-index: 500;
      width: 100%;
      max-width: 100%;
      transform: translateX(-100%);
      height: 100%;
      height: 100dvh;
    }

    #wsidebar.ofcrm-chat-mob-open {
      transform: translateX(0);
    }

    #backBtn {
      display: flex !important;
    }

    #chatArea {
      width: 100%;
    }

    #pinnedPanel {
      width: 100%;
    }
  }

  @media (min-width: 701px) {
    #backBtn {
      display: none !important;
    }
  }

  /* ---------------------------------------
   RESPONSIVE — APP CONTAINER
--------------------------------------- */
  @media (max-width: 1024px) {
    #app {
      margin: 0 12px;
    }
  }

  @media (max-width: 700px) {

    #app {
      margin: 0;
      border-radius: 0;
      position: fixed;
      inset: 0;
      width: 100vw;
      max-width: none;
      height: 100vh;
      height: 100dvh;
      min-height: 100vh;
      min-height: 100dvh;
      height: -webkit-fill-available;
    }

    #chatArea {
      flex: 1;
      min-height: 0;
      width: 100vw;
      height: 100vh;
      height: 100dvh;
      height: -webkit-fill-available;
    }

    #chatHeader {
      justify-content: flex-start;
      gap: 10px;
      padding: 0 12px;
    }

    #chatActionButtons,
    #msgSearchBar,
    #hdrStatus,
    #hdrDot {
      display: none !important;
    }

    #hdrName {
      font-size: 16px;
      font-weight: 700;
    }

    #hdrAvatar {
      width: 38px !important;
      height: 38px !important;
    }

    .ofcrm-chat-msg-wrap .ofcrm-chat-bubble-wrap {
      max-width: 82% !important;
    }

    #mentionDropdown {
      left: 12px !important;
      right: 12px;
      min-width: 0 !important;
      width: auto;
    }

    .ofcrm-chat-modal-box {
      padding: 18px;
    }

    #scrollDownBtn {
      bottom: 72px;
      right: 10px;
    }
  }

  @media (max-width: 420px) {
    .ofcrm-chat-msg-wrap .ofcrm-chat-bubble-wrap {
      max-width: 86% !important;
    }

    .ofcrm-chat-msg-img {
      max-width: 170px !important;
    }

    #chatHeader {
      padding: 0 8px;
      gap: 6px;
    }

    #hdrName {
      font-size: 13px;
    }

    #chatMessages {
      padding: 10px 6px;
    }

    .ofcrm-chat-ctx-item {
      padding: 10px 14px;
      font-size: 13px;
    }

    .ofcrm-chat-copy-btn {
      opacity: 1;
      width: 24px !important;
      height: 24px !important;
      font-size: 12px !important;
    }
  }

  /* Always show copy btn on touch devices */
  @media (hover: none) {
    .ofcrm-chat-copy-btn {
      opacity: 1;
    }
  }
</style>

<div id="app">

  <!-- --------------- SIDEBAR --------------- -->
  <div id="wsidebar">
    <!-- Header -->
    <div
      style="height:64px;background:#202c33;border-bottom:1px solid #2a3942;padding:0 16px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">
      <div style="display:flex;align-items:center;gap:12px;">
        <div style="position:relative;">
          <img src="https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=" style="width:40px;height:40px;border-radius:50%;">
          <span class="ofcrm-chat-dot-on" style="position:absolute;bottom:0;right:0;"></span>
        </div>
        <span style="font-weight:600;font-size:15px;">My Chats</span>
      </div>
      <div style="display:flex;gap:6px;">
        <button id="createGroupBtn" title="New Group"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;display:flex;align-items:center;justify-content:center;transition:background .15s;"
          onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'">
          <i class="ri-group-line"></i>
        </button>
      </div>
    </div>
    <!-- Search -->
    <div style="padding:10px 12px 6px;flex-shrink:0;">
      <div style="position:relative;">
        <i class="ri-search-line"
          style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#8696a0;font-size:14px;"></i>
        <input id="wsidebarSearch" type="text" placeholder="Search chats…"
          style="width:100%;background:#202c33;border:none;border-radius:10px;padding:9px 12px 9px 36px;color:#fff;outline:none;font-size:13px;box-sizing:border-box;"
          oninput="renderwsidebar()">
      </div>
    </div>
    <!-- Tabs -->
    <div style="display:flex;gap:6px;padding:4px 12px 8px;flex-shrink:0;overflow-x:auto;">
      <button class="ofcrm-chat-tab-btn ofcrm-chat-tab-active" data-tab="all">All</button>
      <button class="ofcrm-chat-tab-btn" data-tab="unread">Unread</button>
      <button class="ofcrm-chat-tab-btn" data-tab="groups">Groups</button>
      <button class="ofcrm-chat-tab-btn" data-tab="pinned">Pinned</button>
    </div>
    <!-- Chat list -->
    <div id="chatList" style="flex:1;overflow-y:auto;min-height:0;"></div>
  </div>

  <!-- --------------- CHAT AREA --------------- -->
  <div id="chatArea">

    <!-- Chat Header -->
    <div id="chatHeader"
      style="height:64px;background:#202c33;border-bottom:1px solid #2a3942;padding:0 12px;display:flex;align-items:center;gap:10px;flex-shrink:0;position:relative;z-index:10;">
        <button id="backBtn" onclick="currentContact = null; updateChatPaneState(); showwsidebar()"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;display:none;align-items:center;justify-content:center;flex-shrink:0;">
        <i class="ri-arrow-left-line"></i>
      </button>
      <div style="position:relative;flex-shrink:0;">
        <img id="hdrAvatar" src="https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=" style="width:40px;height:40px;border-radius:50%;">
        <span id="hdrDot" class="ofcrm-chat-dot-on" style="position:absolute;bottom:0;right:0;"></span>
      </div>
      <div style="flex:1;min-width:0;">
        <div id="hdrName"
          style="font-weight:600;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">Select a
          chat</div>
        <div id="hdrStatus" style="font-size:11px;color:#00a884;">Online</div>
      </div>
      <div id="chatActionButtons" style="display:flex;gap:2px;flex-shrink:0;">
        <button id="searchMsgBtn" title="Search"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;display:flex;align-items:center;justify-content:center;"
          onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
            class="ri-search-line"></i></button>
        <button id="pinnedPanelBtn" title="Pinned messages"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;display:flex;align-items:center;justify-content:center;"
          onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
            class="ri-bookmark-line"></i></button>
        <button id="chatPinBtn" type="button" title="Pin chat"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;display:none;align-items:center;justify-content:center;"
          onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
            class="ri-pushpin-line"></i></button>
        <button id="adminPanelBtn" type="button" title="Group Settings"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;display:none;align-items:center;justify-content:center;"
          onclick="openChatModal('adminModal'); renderAdminPanel();"
          onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
            class="ri-settings-3-line"></i></button>
        <button id="selectModeBtn" title="Select"
          style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;display:flex;align-items:center;justify-content:center;"
          onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
            class="ri-checkbox-multiple-line"></i></button>
      </div>
      <!-- Inline search bar -->
      <div id="msgSearchBar"
        style="display:none;position:absolute;inset:0;background:#202c33;padding:0 16px;align-items:center;gap:10px;z-index:5;">
        <i class="ri-search-line" style="color:#8696a0;"></i>
        <input id="msgSearchInput" type="text" placeholder="Search in conversation…"
          style="flex:1;min-width:0;background:none;border:none;color:#fff;outline:none;font-size:14px;"
          oninput="runMsgSearch()">
        <span id="msgSearchCount" style="font-size:12px;color:#8696a0;white-space:nowrap;flex-shrink:0;"></span>
        <button onclick="prevSearchResult()"
          style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;flex-shrink:0;"><i
            class="ri-arrow-up-s-line"></i></button>
        <button onclick="nextSearchResult()"
          style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;flex-shrink:0;"><i
            class="ri-arrow-down-s-line"></i></button>
        <button onclick="closeMsgSearch()"
          style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;flex-shrink:0;"><i
            class="ri-close-line"></i></button>
      </div>
    </div>
    <div id="groupMembers"></div>

    <!-- Pinned banner -->
    <div id="pinnedBanner"
      style="display:none;padding:8px 16px;flex-shrink:0;cursor:pointer;flex-direction:row;align-items:center;gap:10px;z-index:9;position:relative;">
      <i class="ri-pushpin-fill" style="color:#00a884;flex-shrink:0;"></i>
      <div style="flex:1;min-width:0;">
        <span style="font-size:11px;color:#8696a0;">Pinned message</span>
        <p id="pinnedBannerText"
          style="font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:0;"></p>
      </div>
      <button id="closePinnedBanner"
        style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:18px;flex-shrink:0;"><i
          class="ri-close-line"></i></button>
    </div>

    <!-- Pinned panel -->
    <div id="pinnedPanel">
      <div
        style="padding:14px 16px;border-bottom:1px solid #2a3942;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">
        <span style="font-weight:600;font-size:14px;"> Pinned Messages</span>
        <button id="closePinnedPanel"
          style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;"><i
            class="ri-close-line"></i></button>
      </div>
      <div id="pinnedPanelList" style="flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:8px;">
      </div>
    </div>

    <!-- Select toolbar -->
    <div id="selectToolbar"
      style="display:none;background:#182229;padding:8px 16px;flex-shrink:0;align-items:center;gap:10px;border-bottom:1px solid #2a3942;z-index:9;position:relative;flex-wrap:wrap;">
      <span id="selectCount" style="font-size:13px;color:#e9edef;">0 selected</span>
      <div style="margin-left:auto;display:flex;gap:6px;flex-wrap:wrap;">
        <button id="forwardSelectedBtn"
          style="background:#2a3942;border:none;cursor:pointer;color:#e9edef;border-radius:8px;padding:6px 14px;font-size:13px;display:flex;align-items:center;gap:6px;white-space:nowrap;"><i
            class="ri-share-forward-line"></i> Forward</button>
        <button id="deleteSelectedBtn"
          style="background:#2a3942;border:none;cursor:pointer;color:#f15c6d;border-radius:8px;padding:6px 14px;font-size:13px;display:flex;align-items:center;gap:6px;white-space:nowrap;"><i
            class="ri-delete-bin-line"></i> Delete</button>
        <button id="cancelSelectBtn" style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;"><i
            class="ri-close-line"></i></button>
      </div>
    </div>

    <!-- Older loader -->
    <div id="olderLoader"
      style="display:none;text-align:center;padding:10px;font-size:12px;color:#8696a0;flex-shrink:0;z-index:9;position:relative;">
      Loading older messages…</div>

    <!-- Messages — THIS IS THE ONLY SCROLLING ELEMENT -->
    <div id="chatMessages"></div>

    <!-- Scroll to bottom button -->
    <button id="scrollDownBtn" onclick="scrollToBottom(true)">
      <i class="ri-arrow-down-line"></i>
      <span class="ofcrm-chat-unread-dot" id="newMsgDot"></span>
    </button>

    <!-- Typing indicator -->
    <div id="typingIndicator"
      style="display:none;padding:0 20px 6px;font-size:12px;color:#8696a0;align-items:center;gap:6px;position:relative;z-index:9;flex-shrink:0;">
      <span class="ofcrm-chat-tdot"></span><span class="ofcrm-chat-tdot"></span><span class="ofcrm-chat-tdot"></span>
      <span id="typingName" style="margin-left:4px;">typing…</span>
    </div>

    <!-- Reply/Edit bar -->
    <div id="replyBar"
      style="display:none;background:#182229;border-top:1px solid #2a3942;padding:8px 16px;flex-shrink:0;align-items:center;gap:10px;position:relative;z-index:9;">
      <div style="flex:1;min-width:0;border-left:3px solid #00a884;padding-left:10px;">
        <p id="replyLabel" style="font-size:12px;color:#00a884;font-weight:600;margin:0 0 2px;"></p>
        <p id="replyPreview"
          style="font-size:12px;color:#8696a0;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;">
        </p>
      </div>
      <button id="clearReply"
        style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;flex-shrink:0;"><i
          class="ri-close-line"></i></button>
    </div>

    <!-- Attach preview bar -->
    <div id="attachPreview"
      style="background:#182229;border-top:1px solid #2a3942;flex-shrink:0;position:relative;z-index:9;display:none;">
      <div id="attachList" class="ofcrm-chat-attach-list"></div>
      <button id="clearAllAttach"
        style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;flex-shrink:0;margin-left:auto;margin-top:8px;"><i
          class="ri-close-circle-line"></i></button>
    </div>

    <!-- Input bar -->
    <div id="inputBar"
      style="background:#202c33;padding:10px 12px;border-top:1px solid #2a3942;flex-shrink:0;position:relative;z-index:9;">
      <div id="mentionDropdown"
        style="display:none;position:absolute;bottom:72px;left:60px;background:#1d2f38;border-radius:12px;border:1px solid #2a3942;box-shadow:0 4px 20px rgba(0,0,0,.5);z-index:100;min-width:200px;overflow:hidden;">
      </div>
      <div style="display:flex;align-items:center;gap:8px;">
        <!-- Attach -->
        <div style="position:relative;flex-shrink:0;">
          <button id="attachBtn"
            style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;display:flex;align-items:center;justify-content:center;"
            onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
              class="ri-attachment-line"></i></button>
          <div id="attachMenu"
            style="display:none;position:absolute;bottom:48px;left:0;background:#1d2f38;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.5);z-index:200;width:200px;max-width:calc(100vw - 24px);overflow:hidden;border:1px solid #2a3942;">
            <button onclick="document.getElementById('imageInput').click()"
              style="width:100%;background:none;border:none;cursor:pointer;color:#e9edef;padding:12px 16px;text-align:left;font-size:13px;display:flex;align-items:center;gap:10px;"
              onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
                class="ri-image-line" style="color:#4ade80;font-size:18px;"></i>Photos & Videos</button>
            <button onclick="document.getElementById('documentInput').click()"
              style="width:100%;background:none;border:none;cursor:pointer;color:#e9edef;padding:12px 16px;text-align:left;font-size:13px;display:flex;align-items:center;gap:10px;"
              onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i
                class="ri-file-text-line" style="color:#60a5fa;font-size:18px;"></i>Document</button>
          </div>
          <input type="file" id="imageInput" accept="image/*,video/*" style="display:none;" multiple>
          <input type="file" id="documentInput" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt"
            style="display:none;" multiple>
        </div>

        <!-- Text input -->
        <input id="messageInput" type="text" placeholder="Type a message…"
          style="flex:1;min-width:0;background:#2a3942;border:none;border-radius:24px;padding:10px 18px;color:#fff;outline:none;font-size:14px;">
        <!-- Send -->
        <button id="sendBtn"
          style="width:40px;height:40px;border-radius:50%;background:#00a884;border:none;cursor:pointer;color:#fff;font-size:18px;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s;"
          onmouseover="this.style.background='#06cf9c'" onmouseout="this.style.background='#00a884'"><i
            class="ri-send-plane-fill"></i></button>
      </div>
    </div>

  </div><!-- end #chatArea -->
</div><!-- end #app -->

<!-- --- IMAGE OVERLAY --- -->
<div id="galleryOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.95);z-index:10000;flex-direction:column;">
  <!-- Top bar -->
  <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;flex-shrink:0;">
    <span id="galleryCounter" style="color:#fff;font-size:14px;font-weight:600;"></span>
    <div style="display:flex;gap:8px;">
      <button id="galleryDownloadBtn" title="Download" style="width:40px;height:40px;border-radius:50%;background:rgba(255,255,255,.1);border:none;cursor:pointer;color:#fff;font-size:18px;display:flex;align-items:center;justify-content:center;"><i class="ri-download-line"></i></button>
      <button onclick="closeGallery()" style="width:40px;height:40px;border-radius:50%;background:rgba(255,255,255,.1);border:none;cursor:pointer;color:#fff;font-size:22px;display:flex;align-items:center;justify-content:center;"><i class="ri-close-line"></i></button>
    </div>
  </div>
  <!-- Main image -->
  <div style="flex:1;min-height:0;position:relative;display:flex;align-items:center;justify-content:center;">
    <button id="galleryPrev" onclick="galleryNav(-1)" style="position:absolute;left:12px;z-index:2;width:44px;height:44px;border-radius:50%;background:rgba(255,255,255,.15);border:none;cursor:pointer;color:#fff;font-size:24px;display:flex;align-items:center;justify-content:center;transition:background .15s;" onmouseover="this.style.background='rgba(255,255,255,.3)'" onmouseout="this.style.background='rgba(255,255,255,.15)'"><i class="ri-arrow-left-s-line"></i></button>
    <img id="galleryMainImg" src="" style="max-width:calc(100vw - 120px);max-height:calc(100vh - 180px);object-fit:contain;border-radius:8px;transition:opacity .18s;">
    <button id="galleryNext" onclick="galleryNav(1)" style="position:absolute;right:12px;z-index:2;width:44px;height:44px;border-radius:50%;background:rgba(255,255,255,.15);border:none;cursor:pointer;color:#fff;font-size:24px;display:flex;align-items:center;justify-content:center;transition:background .15s;" onmouseover="this.style.background='rgba(255,255,255,.3)'" onmouseout="this.style.background='rgba(255,255,255,.15)'"><i class="ri-arrow-right-s-line"></i></button>
  </div>
  <!-- Thumbnail strip -->
  <div id="galleryThumbs" style="display:flex;gap:6px;padding:10px 16px;overflow-x:auto;flex-shrink:0;justify-content:center;min-height:72px;align-items:center;"></div>
</div>


<!-- --- CONTACT INFO PANEL --- -->
<div id="contactInfoPanel" style="display:none;position:fixed;inset:0;z-index:7000;background:rgba(0,0,0,.5);">
  <div id="contactInfoBox" style="position:absolute;top:0;right:0;width:100%;max-width:420px;height:100%;background:#111b21;display:flex;flex-direction:column;box-shadow:-4px 0 24px rgba(0,0,0,.5);transform:translateX(100%);transition:transform .25s ease;">
    
    <!-- Header -->
    <div style="height:64px;background:#202c33;border-bottom:1px solid #2a3942;padding:0 16px;display:flex;align-items:center;gap:12px;flex-shrink:0;">
      <button onclick="closeContactInfo()" style="width:36px;height:36px;border-radius:50%;background:none;border:none;cursor:pointer;color:#8696a0;font-size:20px;display:flex;align-items:center;justify-content:center;" onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='none'"><i class="ri-arrow-left-line"></i></button>
      <span style="font-size:16px;font-weight:600;color:#fff;">Contact Info</span>
    </div>

    <!-- Avatar + Name block -->
    <div style="background:#182229;padding:24px 16px;display:flex;flex-direction:column;align-items:center;gap:10px;flex-shrink:0;">
      <div style="position:relative;">
        <img id="ciAvatar" src="" style="width:80px;height:80px;border-radius:50%;object-fit:cover;">
        <span id="ciDot" style="position:absolute;bottom:4px;right:4px;width:14px;height:14px;border-radius:50%;border:3px solid #182229;background:#00a884;"></span>
      </div>
      <div style="text-align:center;">
        <p id="ciName" style="margin:0;font-size:18px;font-weight:700;color:#fff;"></p>
        <p id="ciStatus" style="margin:4px 0 0;font-size:13px;color:#8696a0;"></p>
      </div>
    </div>

    <!-- Tabs -->
    <div style="display:flex;background:#202c33;border-bottom:1px solid #2a3942;flex-shrink:0;">
      <button class="ci-tab-btn" data-citab="media" style="flex:1;padding:14px 0;background:none;border:none;cursor:pointer;color:#00a884;font-size:13px;font-weight:600;border-bottom:2px solid #00a884;transition:all .15s;">Media</button>
      <button class="ci-tab-btn" data-citab="docs" style="flex:1;padding:14px 0;background:none;border:none;cursor:pointer;color:#8696a0;font-size:13px;font-weight:600;border-bottom:2px solid transparent;transition:all .15s;">Docs</button>
      <button class="ci-tab-btn" data-citab="links" style="flex:1;padding:14px 0;background:none;border:none;cursor:pointer;color:#8696a0;font-size:13px;font-weight:600;border-bottom:2px solid transparent;transition:all .15s;">Links</button>
    </div>

    <!-- Search bar -->
    <div style="padding:10px 12px;background:#111b21;flex-shrink:0;border-bottom:1px solid #2a3942;">
      <div style="position:relative;">
        <i class="ri-search-line" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#8696a0;font-size:14px;"></i>
        <input id="ciSearch" type="text" placeholder="Search media, docs and links" oninput="renderCiTab()"
          style="width:100%;background:#202c33;border:none;border-radius:10px;padding:9px 12px 9px 36px;color:#fff;outline:none;font-size:13px;box-sizing:border-box;">
      </div>
    </div>

    <!-- Content area -->
    <div id="ciContent" style="flex:1;overflow-y:auto;padding:12px;"></div>
  </div>
</div>

<!-- --- CONTEXT MENU --- -->
<div id="ctxMenu">
  <div class="ofcrm-chat-ctx-item" data-action="reply"><i class="ri-reply-line" style="color:#8696a0;"></i>Reply</div>
  <div class="ofcrm-chat-ctx-item" data-action="forward"><i class="ri-share-forward-line"
      style="color:#8696a0;"></i>Forward</div>
  <div class="ofcrm-chat-ctx-item" data-action="pin"><i class="ri-pushpin-line" style="color:#8696a0;"></i><span
      class="ofcrm-chat-pin-label">Pin</span></div>
  <div class="ofcrm-chat-ctx-item" data-action="edit" style="display:none;"><i class="ri-edit-line"
      style="color:#8696a0;"></i>Edit</div>
  <div class="ofcrm-chat-ctx-item" data-action="copy"><i class="ri-file-copy-line" style="color:#8696a0;"></i>Copy</div>
  <div class="ofcrm-chat-ctx-item ofcrm-chat-danger" data-action="delete"><i class="ri-delete-bin-line"></i>Delete</div>
</div>

<!-- --- REACTION PICKER --- -->
<div id="reactPicker"
  style="display:none;position:fixed;background:#1d2f38;border-radius:99px;padding:8px 14px;box-shadow:0 6px 24px rgba(0,0,0,.5);z-index:9100;border:1px solid #2a3942;gap:10px;max-width:calc(100vw - 16px);">
  <span class="ofcrm-chat-react-opt" data-r=" "
    style="font-size:24px;cursor:pointer;transition:transform .12s;display:inline-block;"
    onmouseover="this.style.transform='scale(1.3)'" onmouseout="this.style.transform='scale(1)'"> </span>
  <span class="ofcrm-chat-react-opt" data-r=" "
    style="font-size:24px;cursor:pointer;transition:transform .12s;display:inline-block;"
    onmouseover="this.style.transform='scale(1.3)'" onmouseout="this.style.transform='scale(1)'"> </span>
  <span class="ofcrm-chat-react-opt" data-r=" "
    style="font-size:24px;cursor:pointer;transition:transform .12s;display:inline-block;"
    onmouseover="this.style.transform='scale(1.3)'" onmouseout="this.style.transform='scale(1)'"> </span>
  <span class="ofcrm-chat-react-opt" data-r=" "
    style="font-size:24px;cursor:pointer;transition:transform .12s;display:inline-block;"
    onmouseover="this.style.transform='scale(1.3)'" onmouseout="this.style.transform='scale(1)'"> </span>
  <span class="ofcrm-chat-react-opt" data-r=" "
    style="font-size:24px;cursor:pointer;transition:transform .12s;display:inline-block;"
    onmouseover="this.style.transform='scale(1.3)'" onmouseout="this.style.transform='scale(1)'"> </span>
  <span class="ofcrm-chat-react-opt" data-r=" "
    style="font-size:24px;cursor:pointer;transition:transform .12s;display:inline-block;"
    onmouseover="this.style.transform='scale(1.3)'" onmouseout="this.style.transform='scale(1)'"> </span>
</div>

<!-- --- IMAGE CONTEXT MENU --- -->
<div id="imageMenu">
  <div id="downloadImage"><i class="ri-download-line"></i> Download</div>
  <div id="forwardImage"><i class="ri-share-forward-line"></i> Forward</div>
</div>

<!-- --- FORWARD MODAL --- -->
<div id="forwardModal" class="ofcrm-chat-modal-wrap">
  <div class="ofcrm-chat-modal-box">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
      <h2 style="margin:0;font-size:17px;color: white;">Forward to</h2>
      <button onclick="closeChatModal('forwardModal')"
        style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:24px;line-height:1;padding:0;"><i
          class="ri-close-line"></i></button>
    </div>
    <div id="forwardContactList"
      style="max-height:260px;overflow-y:auto;display:flex;flex-direction:column;gap:6px;margin-bottom:16px; color:white;"></div>
    <button id="doForward"
      style="width:100%;background:#00a884;border:none;cursor:pointer;color:#fff;border-radius:10px;padding:12px;font-size:14px;font-weight:600;">Forward</button>
  </div>
</div>

<!-- --- CREATE GROUP MODAL --- -->
<div id="groupModal" class="ofcrm-chat-modal-wrap">
  <div class="ofcrm-chat-modal-box">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;">
      <h2 style="margin:0;font-size:17px; color:#fff">Create Group</h2>
      <button onclick="closeChatModal('groupModal')"
        style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:24px;line-height:1;padding:0;"><i
          class="ri-close-line"></i></button>
    </div>
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
      <div style="position:relative;width:56px;height:56px;flex-shrink:0;">
        <img id="createGroupIconImg" src="https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0="
          style="width:56px;height:56px;border-radius:50%;object-fit:cover;border:2px solid #1f2c34;background:#202c33;" />
        <button id="createGroupIconBtn" type="button"
          style="position:absolute;right:-4px;bottom:-4px;width:28px;height:28px;border-radius:50%;border:none;background:#00a884;color:#fff;font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;">
          <i class="ri-camera-line"></i>
        </button>
        <button id="createGroupIconRemoveBtn" type="button"
          style="position:absolute;left:-4px;bottom:-4px;width:28px;height:28px;border-radius:50%;border:none;background:#f15c6d;color:#fff;font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;">
          <i class="ri-delete-bin-line"></i>
        </button>
        <input type="file" id="createGroupIconInput" accept="image/*" style="display:none;" />
      </div>
      <input type="text" id="groupName" placeholder="Group name (required)"
        style="flex:1;min-width:0;background:#2a3942;border:none;border-radius:10px;padding:12px 14px;color:#fff;outline:none;font-size:14px;">
    </div>
    <p style="font-size:12px;color:#8696a0;margin:0 0 8px;">Select Members:</p>
    <input type="text" id="createMemberSearch" placeholder="Search members..."
      style="width:100%;background:#2a3942;border:none;border-radius:10px;padding:10px 14px;color:#fff;outline:none;font-size:13px;margin-bottom:8px;" oninput="renderGroupMemberList()">
    <div id="memberList"
      style="max-height:220px;overflow-y:auto;background:#111b21;border-radius:10px;padding:8px;margin-bottom:16px;display:flex;flex-direction:column;gap:4px;">
    </div>
    <button id="createGroupSubmit"
      style="width:100%;background:#00a884;border:none;cursor:pointer;color:#fff;border-radius:10px;padding:12px;font-size:14px;font-weight:600;">Create
      Group</button>
  </div>
</div>

<!-- --- GROUP ADMIN MODAL --- -->
<div id="adminModal" class="ofcrm-chat-modal-wrap">
  <div class="ofcrm-chat-modal-box">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;">
      <h2 style="margin:0;font-size:17px;">Group Settings</h2>
      <button onclick="closeChatModal('adminModal')"
        style="background:none;border:none;cursor:pointer;color:#8696a0;font-size:24px;line-height:1;padding:0;"><i
          class="ri-close-line"></i></button>
    </div>
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
      <div style="position:relative;width:72px;height:72px;flex-shrink:0;">
        <img id="groupIconImg" src="" alt="Group icon"
          style="width:72px;height:72px;border-radius:50%;object-fit:cover;border:2px solid #1f2c34;background:#202c33;" />
        <button id="changeGroupIconBtn" type="button"
          style="position:absolute;right:-4px;bottom:-4px;width:32px;height:32px;border-radius:50%;border:none;background:#00a884;color:#fff;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;">
          <i class="ri-camera-line"></i>
        </button>
        <input type="file" id="groupIconInput" accept="image/*" style="display:none;" />
      </div>
      <div style="flex:1;min-width:0;">
        <label for="groupNameInput" style="display:block;font-size:12px;color:#8696a0;margin-bottom:6px;">Group Name</label>
        <input id="groupNameInput" type="text" placeholder="Group name"
          style="width:100%;background:#111b21;border:none;border-radius:10px;padding:12px 14px;color:#fff;outline:none;font-size:14px;" />
      </div>
    </div>
    <div style="margin-bottom:16px;">
      <p style="font-size:12px;color:#8696a0;margin:0 0 8px;">Group Members</p>
      <div id="adminMemberList"
        style="display:flex;flex-direction:column;gap:8px;max-height:220px;overflow-y:auto;margin-bottom:12px;"></div>
      <button id="addMemberBtn"
        style="width:100%;background:#2a3942;border:none;cursor:pointer;color:#e9edef;border-radius:10px;padding:12px 16px;font-size:14px;display:flex;align-items:center;justify-content:center;gap:8px;"
        onmouseover="this.style.background='#374c59'" onmouseout="this.style.background='#2a3942'">
        <i class="ri-user-add-line" style="color:#00a884;"></i> Add members
      </button>
      <input type="text" id="addMemberSearch" placeholder="Search members..."
        style="width:100%;background:#2a3942;border:none;border-radius:10px;padding:10px 14px;color:#fff;outline:none;font-size:13px;margin-top:8px;margin-bottom:8px;" oninput="renderAdminPanel()">
      <div id="adminAddMemberList" style="display:flex;flex-direction:column;gap:8px;max-height:160px;overflow-y:auto;"></div>
      <button id="deleteGroupBtn"
        style="width:100%;margin-top:12px;background:#f15c6d;border:none;cursor:pointer;color:#fff;border-radius:10px;padding:12px 16px;font-size:14px;display:flex;align-items:center;justify-content:center;gap:8px;"
        onmouseover="this.style.background='#d9465c'" onmouseout="this.style.background='#f15c6d'">
        <i class="ri-delete-bin-6-line" style="color:#fff;"></i> Delete Group
      </button>
    </div>
  </div>
</div>

<!-- --- TOAST --- -->
<div id="toast"></div>

<script>
  // ---------------------------------------
  //  MODAL HELPERS
  // ---------------------------------------
  function openChatModal(id) { const el = document.getElementById(id); if (el) el.classList.add('ofcrm-chat-open'); }
  function closeChatModal(id) { const el = document.getElementById(id); if (el) el.classList.remove('ofcrm-chat-open'); }
  document.querySelectorAll('.ofcrm-chat-modal-wrap').forEach(wrap => {
    wrap.addEventListener('click', function (e) { if (e.target === this) this.classList.remove('ofcrm-chat-open'); });
  });
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') document.querySelectorAll('.ofcrm-chat-modal-wrap.ofcrm-chat-open').forEach(m => m.classList.remove('ofcrm-chat-open'));
  });

  // ---------------------------------------
  //  TOAST
  // ---------------------------------------
  function showToast(msg) {
    const t = document.getElementById('toast');
    t.textContent = msg; t.style.display = 'block';
    clearTimeout(t._t); t._t = setTimeout(() => t.style.display = 'none', 2400);
  }

  // ---------------------------------------
  //  DATA
  // ---------------------------------------
  let contacts = [
    { id: 0, name: 'Self', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: true, unread: 0, pinned: false, isGroup: false, isSelf: true, lastMsg: '', time: '' },
    { id: 1, name: 'Raj', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: true, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
    { id: 2, name: 'Rahul', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: false, unread: 0, pinned: true, isGroup: false, lastMsg: '', time: '' },
    { id: 3, name: 'Ramesh', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: true, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
    { id: 4, name: 'Harsh', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: false, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
    { id: 5, name: 'Rajesh', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: true, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
    { id: 6, name: 'Mukesh', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: false, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
    { id: 7, name: 'Amit', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: false, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
    { id: 8, name: 'Rohit', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: false, unread: 0, pinned: false, isGroup: false, lastMsg: '', time: '' },
   
    {
      id: 7, name: 'Test Group', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', online: false, unread: 0, pinned: true, isGroup: true, lastMsg: '', time: '',
      members: [
        { id: 1, name: 'Raj', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', isAdmin: true, muted: false },
        { id: 2, name: 'Rahul', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', isAdmin: false, muted: false },
        { id: 4, name: 'Harsh', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', isAdmin: false, muted: true },
        { id: 10, name: 'You', avatar: 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=', isAdmin: true, muted: false },
      ]
    },
  ];

  let messagesDB = {
    0: [],
    1: [],
    2: [],
    3: [],
    4: [],
    5: [],
    6: [],
    7: [],
  };

  let pinnedMessages = {};
  let currentContact = null;
  let replyTo = null;
  let editingMsgId = null;
  let pendingAttachments = [];
  let selectMode = false;
  let selectedMsgs = new Set();
  let ctxMsgId = null;
  let forwardMsgIds = [];
  let nextMsgId = 200;
  let searchResults = [];
  let searchIdx = 0;
  let currentTab = 'all';
  let groupSelMembers = [];
  let selectedImage = '';
  let createGroupIconData = '';
  let newMsgCount = 0; // unread count while scrolled up

  function getMsgs(cid) { if (!messagesDB[cid]) messagesDB[cid] = []; return messagesDB[cid]; }
  function getPinned(cid) { if (!pinnedMessages[cid]) pinnedMessages[cid] = []; return pinnedMessages[cid]; }
  function getPinnedChatCount() { return contacts.filter(c => c.pinned).length; }
  function escapeHTML(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
  function highlightMentions(t) { return t.replace(/@(\w+)/g, '<span class="ofcrm-chat-mention">@$1</span>'); }
  function linkifyText(text) {
    const escaped = escapeHTML(text);
    return escaped.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" style="color:#60a5fa;text-decoration:underline;">$1</a>');
  }
  function fmtTime(d) { if (typeof d === 'string') return d; return d.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: true }); }

  function parseMsgDate(msg) {
    if (msg.timestamp) return new Date(msg.timestamp);
    if (msg.date) return new Date(msg.date);
    if (typeof msg.time === 'string') {
      const t = msg.time.trim().toLowerCase();
      if (t === 'now' || t === 'today') return new Date();
      if (t === 'yesterday') { const d = new Date(); d.setDate(d.getDate() - 1); return d; }
      if (t === 'last month') { const d = new Date(); d.setMonth(d.getMonth() - 1); return d; }
      const parsed = Date.parse(msg.time);
      if (!Number.isNaN(parsed)) return new Date(parsed);
    }
    return new Date();
  }

  function isSameDay(a, b) {
    return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  }

  function formatDateSeparator(date) {
    const today = new Date();
    if (isSameDay(date, today)) return 'Today';
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    if (isSameDay(date, yesterday)) return 'Yesterday';
    return date.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' });
  }

  function isAtBottom() {
    const el = document.getElementById('chatMessages');
    return el.scrollHeight - el.scrollTop - el.clientHeight < 60;
  }

  function scrollToBottom(smooth = false) {
    const el = document.getElementById('chatMessages');
    el.scrollTo({ top: el.scrollHeight, behavior: smooth ? 'smooth' : 'instant' });
    newMsgCount = 0;
    updateScrollBtn();
  }

  function updateScrollBtn() {
    const btn = document.getElementById('scrollDownBtn');
    const dot = document.getElementById('newMsgDot');
    if (isAtBottom()) {
      btn.classList.remove('ofcrm-chat-show');
      newMsgCount = 0;
    } else {
      btn.classList.add('ofcrm-chat-show');
    }
    if (newMsgCount > 0) {
      dot.textContent = newMsgCount > 99 ? '99+' : newMsgCount;
      dot.classList.add('ofcrm-chat-show');
    } else {
      dot.classList.remove('ofcrm-chat-show');
    }
  }

  // ---------------------------------------
  //  MOBILE NAV
  // ---------------------------------------
  function showwsidebar() { document.getElementById('wsidebar').classList.add('ofcrm-chat-mob-open'); }
  function hidewsidebar() { document.getElementById('wsidebar').classList.remove('ofcrm-chat-mob-open'); }

  // ---------------------------------------
  //  SIDEBAR RENDER
  // ---------------------------------------
function renderwsidebar() {
    const list = document.getElementById('chatList');
    const q = document.getElementById('wsidebarSearch').value.toLowerCase();

    let all = [...contacts];
    if (currentTab === 'unread') all = all.filter(c => c.unread > 0);
    if (currentTab === 'groups') all = all.filter(c => c.isGroup);
    if (currentTab === 'pinned') all = all.filter(c => c.pinned);
    if (q) all = all.filter(c => c.name.toLowerCase().includes(q));

    const pinned = all.filter(c => c.pinned);
    const unpinned = all.filter(c => !c.pinned);

    const renderItem = (c) => `
    <div class="ofcrm-chat-chat-item" data-cid="${c.id}" style="display:flex;align-items:center;gap:12px;padding:12px 16px;cursor:pointer;border-bottom:1px solid #1f2c34;transition:background .12s;${currentContact?.id === c.id ? 'background:#2a3942' : ''}"
      onmouseover="if(${currentContact?.id}!==${c.id})this.style.background='#182229'" onmouseout="if(${currentContact?.id}!==${c.id})this.style.background=''">
      <div style="position:relative;flex-shrink:0;">
        <img src="${c.avatar}" style="width:48px;height:48px;border-radius:50%;object-fit:cover;">
        ${c.isGroup ? '' : c.isSelf
          ? '<span class="ofcrm-chat-dot-on" style="position:absolute;bottom:0;right:0;"></span>'
          : `<span class="${c.online ? 'ofcrm-chat-dot-on' : 'ofcrm-chat-dot-off'}" style="position:absolute;bottom:0;right:0;"></span>`}
        ${c.pinned ? '<span style="position:absolute;top:-2px;right:-2px;width:16px;height:16px;border-radius:50%;background:#00a884;display:flex;align-items:center;justify-content:center;border:2px solid #111b21;"><i class="ri-pushpin-fill" style="font-size:8px;color:#fff;"></i></span>' : ''}
      </div>
      <div style="flex:1;min-width:0;">
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <span style="font-size:14px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
            ${c.isSelf ? '<i class="ri-bookmark-fill" style="color:#00a884;font-size:12px;margin-right:4px;"></i>' : ''}
            ${c.isGroup ? '<i class="ri-group-line" style="color:#fff;font-size:12px;margin-right:4px;"></i>' : ''}
            ${escapeHTML(c.name)}
          </span>
          <div style="display:flex;align-items:center;gap:4px;flex-shrink:0;margin-left:8px;">
            <span style="font-size:11px;color:#fff;">${c.time}</span>
          </div>
        </div>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-top:2px;">
          <p style="font-size:12px;color:#fff;margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;">${escapeHTML(c.lastMsg)}</p>
          <div style="display:flex;align-items:center;gap:4px;flex-shrink:0;">
            ${c.unread > 0 ? `<span style="width:20px;height:20px;border-radius:50%;background:#00a884;color:#fff;font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;">${c.unread}</span>` : ''}
          </div>
        </div>
      </div>
    </div>`;

    let html = '';

    if (pinned.length && currentTab !== 'unread' && currentTab !== 'groups') {
      html += `<div style="padding:6px 16px 4px;font-size:11px;font-weight:700;color:#8696a0;text-transform:uppercase;letter-spacing:.6px;display:flex;align-items:center;gap:6px;background:#111b21;">
        <i class="ri-pushpin-fill" style="color:#00a884;font-size:12px;"></i> Pinned
      </div>`;
      html += pinned.map(renderItem).join('');
      if (unpinned.length) {
        html += `<div style="padding:6px 16px 4px;font-size:11px;font-weight:700;color:#8696a0;text-transform:uppercase;letter-spacing:.6px;background:#111b21;">All Chats</div>`;
      }
    }

    html += unpinned.map(renderItem).join('');
    list.innerHTML = html;

    list.querySelectorAll('.ofcrm-chat-chat-item').forEach(el => {
      el.addEventListener('click', () => {
        openChat(contacts.find(c => c.id === +el.dataset.cid));
        hidewsidebar();
      });
    });
  }

  // Tabs
  function syncSidebarTabs() {
    document.querySelectorAll('.ofcrm-chat-tab-btn').forEach(btn => {
      btn.classList.toggle('ofcrm-chat-tab-active', btn.dataset.tab === currentTab);
    });
  }

  document.querySelectorAll('.ofcrm-chat-tab-btn').forEach(btn => {
    btn.addEventListener('click', function () {
      currentTab = this.dataset.tab;
      syncSidebarTabs();
      renderwsidebar();
    });
  });

  document.getElementById('createGroupBtn').addEventListener('click', openGroupModal);
  document.getElementById('createGroupSubmit').addEventListener('click', createGroup);

  function openGroupModal() {
    createGroupIconData = '';
    document.getElementById('groupName').value = '';
    document.getElementById('createGroupIconImg').src = 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=';
    document.getElementById('createGroupIconRemoveBtn').style.display = 'none';
    renderGroupMemberList();
    openChatModal('groupModal');
  }

  function renderGroupMemberList() {
    const list = document.getElementById('memberList');
    const available = contacts.filter(c => !c.isGroup && !c.isSelf);
    if (!available.length) {
      list.innerHTML = '<div style="color:#8696a0;font-size:13px;">No contacts available</div>';
      return;
    }
    let filtered = available;
    const searchInput = document.getElementById('createMemberSearch');
    if (searchInput && searchInput.value.trim()) {
      const q = searchInput.value.toLowerCase();
      filtered = available.filter(c => c.name.toLowerCase().includes(q));
    }
    list.innerHTML = filtered.map(c => `
      <label style="display:flex;align-items:center;gap:10px;padding:8px;border-radius:10px;background:#111b21;cursor:pointer;">
        <input type="checkbox" value="${c.id}" style="width:16px;height:16px;" />
        <img src="${c.avatar}" style="width:36px;height:36px;border-radius:50%;object-fit:cover;flex-shrink:0;">
        <div style="flex:1;min-width:0;">
          <div style="font-size:13px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(c.name)}</div>
          <div style="font-size:11px;color:#8696a0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(c.lastMsg)}</div>
        </div>
      </label>
    `).join('');
  }

  function createGroup() {
    const name = document.getElementById('groupName').value.trim();
    if (!name) return showToast('Please enter a group name');

    const selected = [...document.querySelectorAll('#memberList input[type=checkbox]:checked')].map(el => +el.value);
    if (!selected.length) return showToast('Please select at least one member');

    const members = contacts.filter(c => selected.includes(c.id)).map(c => ({
      id: c.id,
      name: c.name,
      avatar: c.avatar,
      isAdmin: c.name === 'You',
      muted: false
    }));

    const nextGroupId = Math.max(...contacts.map(c => c.id), 0) + 1;
    const group = {
      id: nextGroupId,
      name,
      avatar: createGroupIconData || 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=',
      online: false,
      unread: 0,
      pinned: false,
      isGroup: true,
      lastMsg: 'Group created',
      time: 'Now',
      members
    };

    contacts.push(group);
    messagesDB[nextGroupId] = [];
    closeChatModal('groupModal');
    renderwsidebar();
    openChat(group);
    showToast('Group created successfully');
  }

  // ---------------------------------------
  //  OPEN CHAT
  // ---------------------------------------
  function updateExternalTopBar(show) {
    if (window.innerWidth > 700) return;
    const selectors = ['header', '.topbar', '.top-bar', '.navbar', '.appbar', '.site-header'];
    selectors.forEach(selector => {
      document.querySelectorAll(selector).forEach(el => {
        el.style.display = show ? '' : 'none';
      });
    });
  }

  function updateChatPaneState() {
    const header = document.getElementById('chatHeader');
    const inputBar = document.getElementById('inputBar');
    const pinnedBanner = document.getElementById('pinnedBanner');
    const selectToolbar = document.getElementById('selectToolbar');
    const groupMembers = document.getElementById('groupMembers');
    const typingIndicator = document.getElementById('typingIndicator');

    if (!currentContact) {
      header.style.display = 'none';
      inputBar.style.display = 'none';
      pinnedBanner.style.display = 'none';
      selectToolbar.style.display = 'none';
      groupMembers.style.display = 'none';
      typingIndicator.style.display = 'none';
      updateExternalTopBar(true);
      return;
    }

    header.style.display = 'flex';
    inputBar.style.display = '';
    updateExternalTopBar(false);
  }

  function openChat(contact) {
    if (!contact) return;
    currentContact = contact;
    const msgs = getMsgs(contact.id);
    const firstUnread = msgs.find(m => m.unread);
    contact.unread = 0;
    newMsgCount = 0;

    document.getElementById('hdrAvatar').src = contact.avatar;
    document.getElementById('hdrName').textContent = contact.name;
    updateExternalTopBar(false);
    const statusEl = document.getElementById('hdrStatus');
    const dotEl = document.getElementById('hdrDot');

    if (contact.isSelf) {
      statusEl.textContent = 'Your saved messages'; statusEl.style.color = '#8696a0';
      dotEl.className = 'ofcrm-chat-dot-on'; dotEl.style.display = 'block';
      document.getElementById('adminPanelBtn').style.display = 'none';
    } else if (contact.isGroup) {
      statusEl.textContent = (contact.members?.length || 0) + ' members'; statusEl.style.color = '#8696a0';
      dotEl.style.display = 'none';
      document.getElementById('adminPanelBtn').style.display = 'flex';
    } else {
      statusEl.textContent = contact.online ? 'Online' : 'Last seen recently';
      statusEl.style.color = contact.online ? '#00a884' : '#8696a0';
      dotEl.className = contact.online ? 'ofcrm-chat-dot-on' : 'ofcrm-chat-dot-off'; dotEl.style.display = 'block';
      document.getElementById('adminPanelBtn').style.display = 'none';
    }
    renderChatPinButton();
    updateChatPaneState();

    exitSelectMode(); clearReplyBar();
    document.getElementById('pinnedPanel').classList.remove('ofcrm-chat-open');
    document.getElementById('msgSearchBar').style.display = 'none';
    renderwsidebar(); renderMessages(false, firstUnread?.id, firstUnread?.id);
    if (firstUnread) {
      msgs.forEach(m => { if (m.unread) m.unread = false; });
      currentContact.unread = 0;
      renderwsidebar();
    } else {
      scrollToBottom();
    }
    renderPinnedBanner(); renderGroupMembers();

    if (contact.isGroup) {
      document.getElementById('hdrName').style.cursor = 'pointer';
      document.getElementById('hdrName').title = 'View group details';
    } else {
      document.getElementById('hdrName').style.cursor = 'pointer';
      document.getElementById('hdrName').title = 'View contact info';
    }

    if (!contact.isGroup && !contact.isSelf && contact.online) {
      setTimeout(() => { showTyping(contact.name); setTimeout(hideTyping, 2800); }, 3500);
    }
  }

  function showTyping(name) { document.getElementById('typingIndicator').style.display = 'flex'; document.getElementById('typingName').textContent = name + ' is typing…'; }
  document.getElementById('hdrName').addEventListener('click', function () {
    if (currentContact?.isGroup) {
      renderAdminPanel();
      openChatModal('adminModal');
    } else if (currentContact) {
      openContactInfo();
    }
  });
  function hideTyping() { document.getElementById('typingIndicator').style.display = 'none'; }
  function renderGroupMembers() {
    const bar = document.getElementById('groupMembers');
    bar.style.display = 'none';
  }

  // ---------------------------------------
  //  RENDER MESSAGES
  // ---------------------------------------
  function renderMessages(keepScroll = false, jumpToMsgId = null, unreadBoundaryId = null) {
    const container = document.getElementById('chatMessages');
    if (!currentContact) {
      updateChatPaneState();
      if (window.innerWidth <= 700) {
        container.innerHTML = '';
        return;
      }
      container.innerHTML = `
        <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:24px;color:#94a3b8;">
          <div style="width:172px;height:172px;border-radius:50%;background:rgba(255,255,255,.05);display:flex;align-items:center;justify-content:center;margin-bottom:24px;">
            <i class="ri-chat-voice-line" style="font-size:48px;color:#00a884;"></i>
          </div>
          <h2 style="margin:0 0 8px;font-size:20px;color:#f8fafb;">No active chat</h2>
          <p style="margin:0;max-width:340px;line-height:1.75;">Select a person from the sidebar to start chatting.</p>
        </div>`;
      return;
    }
    const msgs = getMsgs(currentContact.id);
    const pinned = getPinned(currentContact.id);
    const prevScrollTop = container.scrollTop;
    const prevScrollHeight = container.scrollHeight;
    const wasAtBottom = isAtBottom();

    let html = '<div id="olderAnchor" style="height:1px;"></div>';
    let prevDate = null;
    let unreadSeparatorAdded = false;
    msgs.forEach((msg, i) => {
      const msgDate = parseMsgDate(msg);
      if (!prevDate || !isSameDay(msgDate, prevDate)) {
        html += `<div style="display:flex;align-items:center;justify-content:center;margin:12px 0;
          font-size:12px;color:#94a3b8;background:rgba(255,255,255,.05);padding:4px 12px;border-radius:999px;">
          ${escapeHTML(formatDateSeparator(msgDate))}</div>`;
        prevDate = msgDate;
      }
      if (msg.id === unreadBoundaryId && !unreadSeparatorAdded) {
        html += `<div style="display:flex;align-items:center;justify-content:center;margin:10px 0;
          font-size:12px;color:#fff;background:#00a884;padding:6px 12px;border-radius:999px;">
          Unread messages</div>`;
        unreadSeparatorAdded = true;
      }
      const isMe = msg.from === 'me';
      const showAvatar = !isMe && (i === 0 || msgs[i - 1].from === 'me');
      const isPinned = pinned.includes(msg.id);

      // Reactions
      let reactHtml = '';
      const ents = Object.entries(msg.reactions || {});
      if (ents.length) {
        const chips = ents.map(([e, u]) => `<span class="ofcrm-chat-react-chip${u.includes('me') ? ' ofcrm-chat-mine' : ''}" data-msgid="${msg.id}" data-r="${e}">${e} ${u.length}</span>`).join('');
        reactHtml = `<div class="ofcrm-chat-react-bar" style="justify-content:${isMe ? 'flex-end' : 'flex-start'}">${chips}</div>`;
      }

      // Reply preview
      const replyHtml = msg.replyTo ? `<div style="border-left:3px solid #00a884;padding:4px 8px;background:rgba(255,255,255,.06);border-radius:4px;margin-bottom:6px;">
      <p style="font-size:11px;color:#00a884;font-weight:700;margin:0 0 2px;">${escapeHTML(msg.replyTo.name)}</p>
      <p style="font-size:11px;color:#8696a0;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:240px;">${escapeHTML(msg.replyTo.text)}</p>
    </div>`: '';

      // Content
      let content = '';
      if (msg.attachments?.length) {
        const imgAtts = msg.attachments.filter(a => a.type === 'image');
        const docAtts = msg.attachments.filter(a => a.type !== 'image');
        let imgGrid = '';
        if (imgAtts.length) {
          const msgImgUrls = JSON.stringify(imgAtts.map(a => a.url));
          const count = imgAtts.length;
          const show = Math.min(count, 4);
          const extra = count - show;
          // Grid layouts matching WhatsApp
          let gridStyle = '';
          if (count === 1) gridStyle = 'grid-template-columns:1fr;max-width:260px;';
          else if (count === 2) gridStyle = 'grid-template-columns:1fr 1fr;max-width:280px;';
          else if (count === 3) gridStyle = 'grid-template-columns:1fr 1fr;max-width:280px;';
          else gridStyle = 'grid-template-columns:1fr 1fr;max-width:280px;';
          const cells = imgAtts.slice(0, show).map((att, idx) => {
            const isLast = idx === show - 1 && extra > 0;
            const span = (count === 3 && idx === 0) ? 'grid-column:span 2;' : '';
            return `<div style="position:relative;${span}border-radius:6px;overflow:hidden;aspect-ratio:1/1;cursor:pointer;" class="ofcrm-chat-img-cell" data-imgs='${msgImgUrls}' data-idx="${idx}">
              <img src="${att.url}" style="width:100%;height:100%;object-fit:cover;display:block;">
              ${isLast && extra > 0 ? `<div style="position:absolute;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;font-size:24px;font-weight:700;color:#fff;">+${extra}</div>` : ''}
              <button class="ofcrm-chat-image-menu-btn" data-image="${att.url}" style="position:absolute;top:6px;right:6px;width:28px;height:28px;border:none;border-radius:50%;background:rgba(0,0,0,0.6);color:#fff;cursor:pointer;z-index:10;display:flex;align-items:center;justify-content:center;font-size:13px;opacity:0;transition:opacity .15s;" onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0'"><i class="ri-more-2-fill"></i></button>
            </div>`;
          }).join('');
          imgGrid = `<div style="display:grid;${gridStyle}gap:3px;border-radius:10px;overflow:hidden;margin-bottom:${docAtts.length || msg.text ? '8px' : '0'};">${cells}</div>`;
        }
        const docItems = docAtts.map(att => `<div style="display:flex;align-items:center;gap:10px;background:rgba(0,0,0,.15);border-radius:8px;padding:10px 12px;min-width:180px;">
          <i class="ri-file-text-fill" style="font-size:26px;color:#60a5fa;flex-shrink:0;"></i>
          <div style="min-width:0;overflow:hidden;">
            <p style="font-size:13px;font-weight:500;margin:0 0 2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(att.name)}</p>
            <p style="font-size:11px;color:#8696a0;margin:0;">${att.size}</p>
          </div>
        </div>`).join('');
        content = `${imgGrid}${docItems ? `<div style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:8px;">${docItems}</div>` : ''}${msg.text ? `<p style="margin:0;font-size:14px;word-break:break-word;">${escapeHTML(msg.text)}</p>` : ''}`;
      }else if (msg.document) {
        content = `<div style="display:flex;align-items:center;gap:10px;background:rgba(0,0,0,.15);border-radius:8px;padding:8px 12px;">
        <i class="ri-file-text-fill" style="font-size:28px;color:#60a5fa;flex-shrink:0;"></i>
        <div style="min-width:0;"><p style="font-size:13px;font-weight:500;margin:0 0 2px;word-break:break-all;">${escapeHTML(msg.document.name)}</p>
        <p style="font-size:11px;color:#8696a0;margin:0;">${msg.document.size}</p></div>
      </div>`;
      } else {
        content = `<span style="font-size:14px;word-break:break-word;">${highlightMentions(linkifyText(msg.text))}</span>`;
      }

      const meta = `<span style="font-size:10px;color:#8696a0;margin-left:6px;white-space:nowrap;">${msg.time}${msg.edited ? ' · edited' : ''}</span>
      ${isMe ? `<span style="font-size:11px;margin-left:3px;${msg.status === 'read' ? 'color:#53bdeb;' : 'color:#8696a0;'}">${msg.status === 'read' ? ' ' : msg.status === 'delivered' ? ' ' : '?'}</span>` : ''}
      ${isPinned ? '<i class="ri-pushpin-fill" style="font-size:10px;color:#00a884;margin-left:3px;"></i>' : ''}`;

      // Copy button — always rendered, CSS controls visibility
      const copyBtn = `<button class="ofcrm-chat-copy-btn" data-id="${msg.id}" title="Copy message"><i class="ri-file-copy-line"></i></button>`;

      if (isMe) {
        html += `<div id="msg-${msg.id}" class="ofcrm-chat-msg-wrap" data-id="${msg.id}" style="display:flex;justify-content:flex-end;align-items:flex-end;gap:4px;margin-bottom:2px;">
        ${copyBtn}
        <div class="ofcrm-chat-bubble-wrap" style="max-width:min(340px,80%);">
          <div class="ofcrm-chat-msg-out" style="padding:8px 12px;display:inline-block;width:100%;">
            ${replyHtml}
            ${msg.fromName ? `<p style="font-size:11px;color:#00a884;font-weight:700;margin:0 0 4px;">${escapeHTML(msg.fromName)}</p>` : ''}
            ${content}
            <div style="display:flex;align-items:center;justify-content:flex-end;gap:2px;margin-top:2px;">${meta}</div>
          </div>${reactHtml}
        </div>
      </div>`;
      } else {
        html += `<div id="msg-${msg.id}" class="ofcrm-chat-msg-wrap" data-id="${msg.id}" style="display:flex;align-items:flex-end;gap:6px;margin-bottom:2px;">
        ${showAvatar ? `<img src="${currentContact.avatar}" style="width:28px;height:28px;border-radius:50%;flex-shrink:0;margin-bottom:2px;">` : '<div style="width:28px;flex-shrink:0;"></div>'}
        <div class="ofcrm-chat-bubble-wrap" style="max-width:min(340px,80%);">
          <div class="ofcrm-chat-msg-in" style="padding:8px 12px;display:inline-block;width:100%;">
            ${replyHtml}
            ${msg.fromName ? `<p style="font-size:11px;color:#00a884;font-weight:700;margin:0 0 4px;">${escapeHTML(msg.fromName)}</p>` : ''}
            ${content}
            <div style="display:flex;align-items:center;justify-content:flex-end;gap:2px;margin-top:2px;">${meta}</div>
          </div>${reactHtml}
        </div>
        ${copyBtn}
      </div>`;
      }
    });

    if (!msgs.length) {
      container.classList.add('ofcrm-chat-empty');
      container.innerHTML = `<div style="display:flex;flex:1;align-items:center;justify-content:center;padding:24px;min-height:200px;"><div style="text-align:center;color:#8696a0;max-width:320px;"><div style="font-size:48px;line-height:1;margin-bottom:12px;"> </div><p style="margin:0;font-size:15px;">No messages yet. Start the conversation.</p></div></div>`;
    } else {
      container.classList.remove('ofcrm-chat-empty');
      container.innerHTML = html;
    }

    if (jumpToMsgId) {
      const target = document.getElementById('msg-' + jumpToMsgId);
      if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else if (keepScroll) {
      container.scrollTop = prevScrollTop + (container.scrollHeight - prevScrollHeight);
    } else if (wasAtBottom) {
      container.scrollTop = container.scrollHeight;
    }

    updateScrollBtn();
    bindMsgEvents(container);
  }

  function bindMsgEvents(container) {
    let pressTimer = null;

    // Context menu + select + long press
    container.querySelectorAll('.ofcrm-chat-msg-wrap').forEach(el => {
      el.addEventListener('contextmenu', e => { e.preventDefault(); showCtxMenu(e, +el.dataset.id); });
      el.addEventListener('click', e => {
        if (selectMode && !e.target.closest('.ofcrm-chat-copy-btn') && !e.target.closest('.ofcrm-chat-msg-img') && !e.target.closest('.ofcrm-chat-image-menu-btn'))
          toggleSelectMsg(+el.dataset.id);
      });
      el.addEventListener('touchstart', e => {
        pressTimer = setTimeout(() => {
          const t = e.touches[0];
          showCtxMenu({ clientX: t.clientX, clientY: t.clientY }, +el.dataset.id);
        }, 550);
      }, { passive: true });
      el.addEventListener('touchend', () => clearTimeout(pressTimer));
      el.addEventListener('touchmove', () => clearTimeout(pressTimer));
    });

    // Copy buttons
    container.querySelectorAll('.ofcrm-chat-copy-btn').forEach(btn => {
      btn.addEventListener('click', e => {
        e.stopPropagation();
        const msg = getMsgs(currentContact.id).find(m => m.id === +btn.dataset.id);
        if (!msg) return;
        const text = msg.text || (msg.image ? '  Photo' : '  Document');
        if (navigator.clipboard?.writeText) {
          navigator.clipboard.writeText(text).then(() => showToast('Message copied!')).catch(() => fallbackCopy(text));
        } else { fallbackCopy(text); }
      });
    });

    // Image lightbox
    container.querySelectorAll('.ofcrm-chat-img-cell').forEach(cell => {
      cell.addEventListener('click', e => {
        if (e.target.closest('.ofcrm-chat-image-menu-btn')) return;
        const imgs = JSON.parse(cell.dataset.imgs);
        const startIdx = +cell.dataset.idx;
        openGallery(imgs, startIdx);
      });
    });

    // Image menu button
    container.querySelectorAll('.ofcrm-chat-image-menu-btn').forEach(btn => {
      btn.addEventListener('click', e => {
        e.stopPropagation();
        selectedImage = btn.dataset.image;
        const menu = document.getElementById('imageMenu');
        menu.style.display = 'block';
        const x = Math.min(e.clientX, window.innerWidth - 180);
        const y = Math.min(e.clientY, window.innerHeight - 100);
        menu.style.left = x + 'px'; menu.style.top = y + 'px';
      });
    });

    // Reaction chip toggle
    container.querySelectorAll('.ofcrm-chat-react-chip').forEach(chip => {
      chip.addEventListener('click', () => {
        const msgId = +chip.dataset.msgid, emoji = chip.dataset.r;
        const msg = getMsgs(currentContact.id).find(m => m.id === msgId); if (!msg) return;
        if (!msg.reactions[emoji]) msg.reactions[emoji] = [];
        const arr = msg.reactions[emoji], idx = arr.indexOf('me');
        if (idx === -1) arr.push('me'); else arr.splice(idx, 1);
        if (!arr.length) delete msg.reactions[emoji];
        renderMessages(true);
      });
    });
  }

  function fallbackCopy(text) {
    const ta = document.createElement('textarea');
    ta.value = text; document.body.appendChild(ta); ta.select();
    try { document.execCommand('copy'); showToast('Message copied!'); } catch (_) { showToast('Copy failed'); }
    ta.remove();
  }

  let galleryImages = [];
  let galleryIndex = 0;

  function openGallery(imgs, startIdx) {
    galleryImages = imgs;
    galleryIndex = startIdx;
    const overlay = document.getElementById('galleryOverlay');
    overlay.style.display = 'flex';
    overlay.style.flexDirection = 'column';
    renderGallerySlide();
    renderGalleryThumbs();
  }

  function closeGallery() {
    document.getElementById('galleryOverlay').style.display = 'none';
    galleryImages = [];
    galleryIndex = 0;
  }

  function galleryNav(dir) {
    galleryIndex = (galleryIndex + dir + galleryImages.length) % galleryImages.length;
    renderGallerySlide();
    renderGalleryThumbs();
  }

  function renderGallerySlide() {
    const img = document.getElementById('galleryMainImg');
    img.style.opacity = '0';
    setTimeout(() => {
      img.src = galleryImages[galleryIndex];
      img.style.opacity = '1';
    }, 80);
    document.getElementById('galleryCounter').textContent = `${galleryIndex + 1} / ${galleryImages.length}`;
    document.getElementById('galleryPrev').style.display = galleryImages.length > 1 ? 'flex' : 'none';
    document.getElementById('galleryNext').style.display = galleryImages.length > 1 ? 'flex' : 'none';
    // Download
    document.getElementById('galleryDownloadBtn').onclick = () => {
      const a = document.createElement('a'); a.href = galleryImages[galleryIndex]; a.download = 'photo.jpg';
      document.body.appendChild(a); a.click(); a.remove();
    };
  }

  function renderGalleryThumbs() {
    const strip = document.getElementById('galleryThumbs');
    if (galleryImages.length <= 1) { strip.style.display = 'none'; return; }
    strip.style.display = 'flex';
    strip.innerHTML = galleryImages.map((url, i) => `
      <div onclick="galleryIndex=${i};renderGallerySlide();renderGalleryThumbs();"
        style="width:56px;height:56px;flex-shrink:0;border-radius:6px;overflow:hidden;cursor:pointer;border:2px solid ${i === galleryIndex ? '#00a884' : 'transparent'};transition:border-color .15s;opacity:${i === galleryIndex ? '1' : '0.55'};">
        <img src="${url}" style="width:100%;height:100%;object-fit:cover;">
      </div>`).join('');
  }

  // Keyboard navigation for gallery
  document.addEventListener('keydown', e => {
    if (document.getElementById('galleryOverlay').style.display !== 'none') {
      if (e.key === 'ArrowLeft') galleryNav(-1);
      else if (e.key === 'ArrowRight') galleryNav(1);
      else if (e.key === 'Escape') closeGallery();
    }
  });

  // Touch swipe for gallery
  let galleryTouchX = null;
  document.getElementById('galleryOverlay').addEventListener('touchstart', e => { galleryTouchX = e.touches[0].clientX; }, { passive: true });
  document.getElementById('galleryOverlay').addEventListener('touchend', e => {
    if (galleryTouchX === null) return;
    const dx = e.changedTouches[0].clientX - galleryTouchX;
    if (Math.abs(dx) > 50) galleryNav(dx < 0 ? 1 : -1);
    galleryTouchX = null;
  });

// ---------------------------------------
  //  CONTACT INFO PANEL
  // ---------------------------------------
  let ciCurrentTab = 'media';

  function openContactInfo() {
    if (!currentContact) return;
    ciCurrentTab = 'media';
    document.getElementById('ciAvatar').src = currentContact.avatar;
    document.getElementById('ciName').textContent = currentContact.name;
    if (currentContact.isSelf) {
      document.getElementById('ciStatus').textContent = 'Your saved messages';
      document.getElementById('ciDot').style.background = '#00a884';
    } else if (currentContact.isGroup) {
      document.getElementById('ciStatus').textContent = (currentContact.members?.length || 0) + ' members';
      document.getElementById('ciDot').style.display = 'none';
    } else {
      document.getElementById('ciStatus').textContent = currentContact.online ? 'Online' : 'Last seen recently';
      document.getElementById('ciDot').style.background = currentContact.online ? '#00a884' : '#8696a0';
      document.getElementById('ciDot').style.display = 'block';
    }
    document.getElementById('ciSearch').value = '';
    syncCiTabs();
    renderCiTab();
    const panel = document.getElementById('contactInfoPanel');
    const box = document.getElementById('contactInfoBox');
    panel.style.display = 'block';
    requestAnimationFrame(() => { box.style.transform = 'translateX(0)'; });
  }

  function closeContactInfo() {
    const box = document.getElementById('contactInfoBox');
    box.style.transform = 'translateX(100%)';
    setTimeout(() => { document.getElementById('contactInfoPanel').style.display = 'none'; }, 260);
  }

  document.getElementById('contactInfoPanel').addEventListener('click', function(e) {
    if (e.target === this) closeContactInfo();
  });

  document.querySelectorAll('.ci-tab-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      ciCurrentTab = this.dataset.citab;
      document.getElementById('ciSearch').value = '';
      syncCiTabs();
      renderCiTab();
    });
  });

  function syncCiTabs() {
    document.querySelectorAll('.ci-tab-btn').forEach(btn => {
      const active = btn.dataset.citab === ciCurrentTab;
      btn.style.color = active ? '#00a884' : '#8696a0';
      btn.style.borderBottom = active ? '2px solid #00a884' : '2px solid transparent';
    });
  }

function getCiData() {
    if (!currentContact) return { media: [], docs: [], links: [] };
    const msgs = getMsgs(currentContact.id);
    const media = [], docs = [], links = [];
    const urlRegex = /(https?:\/\/[^\s]+)/g;

    msgs.forEach(msg => {
      // Only show what was RECEIVED (not sent by you)
      if (msg.from === 'me') return;

      const dateStr = (() => {
        const d = parseMsgDate(msg);
        return d.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' }) + ', ' +
               d.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: true });
      })();

      if (msg.attachments?.length) {
        msg.attachments.forEach(att => {
          if (att.type === 'image') {
            media.push({ url: att.url, name: att.name, date: dateStr, msgId: msg.id });
          } else {
            docs.push({ name: att.name, size: att.size, date: dateStr, msgId: msg.id });
          }
        });
      }
      if (msg.document) {
        docs.push({ name: msg.document.name, size: msg.document.size, date: dateStr, msgId: msg.id });
      }
      if (msg.text) {
        const found = msg.text.match(urlRegex);
        if (found) found.forEach(url => links.push({ url, date: dateStr, msgId: msg.id }));
      }
    });
    return { media, docs, links };
  }

  function renderCiTab() {
    const content = document.getElementById('ciContent');
    const q = document.getElementById('ciSearch').value.trim().toLowerCase();
    const data = getCiData();

    if (ciCurrentTab === 'media') {
      let items = data.media;
      if (q) items = items.filter(i => (i.name || '').toLowerCase().includes(q) || i.date.toLowerCase().includes(q));
      if (!items.length) {
        content.innerHTML = `<div style="text-align:center;padding:48px 24px;color:#8696a0;">
          <i class="ri-image-line" style="font-size:48px;display:block;margin-bottom:12px;"></i>
          <p style="margin:0;font-size:14px;">No media shared yet</p></div>`;
        return;
      }
      // Group by date (day only)
      const groups = {};
      items.forEach(item => {
        const day = item.date.split(',')[0];
        if (!groups[day]) groups[day] = [];
        groups[day].push(item);
      });
      content.innerHTML = Object.entries(groups).map(([day, imgs]) => `
        <div style="margin-bottom:16px;">
          <p style="font-size:11px;color:#8696a0;margin:0 0 8px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;">${escapeHTML(day)}</p>
          <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:3px;border-radius:8px;overflow:hidden;">
            ${imgs.map(img => `
              <div style="position:relative;aspect-ratio:1/1;cursor:pointer;overflow:hidden;" class="ci-media-thumb" data-url="${img.url}" data-imgs='${JSON.stringify(imgs.map(i=>i.url))}' data-idx="${imgs.indexOf(img)}">
                <img src="${img.url}" style="width:100%;height:100%;object-fit:cover;display:block;transition:transform .2s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
                <div style="position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,.6));padding:4px 6px;">
                  <span style="font-size:9px;color:rgba(255,255,255,.8);">${escapeHTML(img.date.split(',')[1]?.trim() || '')}</span>
                </div>
              </div>`).join('')}
          </div>
        </div>`).join('');

      content.querySelectorAll('.ci-media-thumb').forEach(thumb => {
        thumb.addEventListener('click', () => {
          const imgs = JSON.parse(thumb.dataset.imgs);
          openGallery(imgs, +thumb.dataset.idx);
        });
      });

    } else if (ciCurrentTab === 'docs') {
      let items = data.docs;
      if (q) items = items.filter(i => i.name.toLowerCase().includes(q) || i.date.toLowerCase().includes(q));
      if (!items.length) {
        content.innerHTML = `<div style="text-align:center;padding:48px 24px;color:#8696a0;">
          <i class="ri-file-text-line" style="font-size:48px;display:block;margin-bottom:12px;"></i>
          <p style="margin:0;font-size:14px;">No documents shared yet</p></div>`;
        return;
      }
      content.innerHTML = items.map(doc => `
        <div style="display:flex;align-items:center;gap:12px;padding:12px;border-radius:10px;background:#202c33;margin-bottom:8px;">
          <div style="width:44px;height:44px;border-radius:10px;background:#1d3a5a;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="ri-file-text-fill" style="font-size:22px;color:#60a5fa;"></i>
          </div>
          <div style="flex:1;min-width:0;">
            <p style="margin:0 0 2px;font-size:13px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(doc.name)}</p>
            <p style="margin:0;font-size:11px;color:#8696a0;">${escapeHTML(doc.size || '')} · ${escapeHTML(doc.date)}</p>
          </div>
        </div>`).join('');

    } else if (ciCurrentTab === 'links') {
      let items = data.links;
      if (q) items = items.filter(i => i.url.toLowerCase().includes(q) || i.date.toLowerCase().includes(q));
      if (!items.length) {
        content.innerHTML = `<div style="text-align:center;padding:48px 24px;color:#8696a0;">
          <i class="ri-link" style="font-size:48px;display:block;margin-bottom:12px;"></i>
          <p style="margin:0;font-size:14px;">No links shared yet</p></div>`;
        return;
      }
      content.innerHTML = items.map(lnk => `
        <a href="${escapeHTML(lnk.url)}" target="_blank" rel="noopener noreferrer" style="text-decoration:none;display:flex;align-items:flex-start;gap:12px;padding:12px;border-radius:10px;background:#202c33;margin-bottom:8px;transition:background .15s;" onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background='#202c33'">
          <div style="width:44px;height:44px;border-radius:10px;background:#1a2e1a;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="ri-link" style="font-size:20px;color:#00a884;"></i>
          </div>
          <div style="flex:1;min-width:0;">
            <p style="margin:0 0 4px;font-size:13px;font-weight:600;color:#60a5fa;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(lnk.url)}</p>
            <p style="margin:0;font-size:11px;color:#8696a0;">${escapeHTML(lnk.date)}</p>
          </div>
          <i class="ri-external-link-line" style="color:#8696a0;font-size:16px;flex-shrink:0;margin-top:2px;"></i>
        </a>`).join('');
    }
  }


  // ---------------------------------------
  //  SCROLL TO BOTTOM BUTTON
  // ---------------------------------------
  document.getElementById('chatMessages').addEventListener('scroll', updateScrollBtn);

  // ---------------------------------------
  //  SEND
  // ---------------------------------------
function sendMessage() {
  if (!currentContact) return showToast('Open a chat first');
  const input = document.getElementById('messageInput');
  const text = input.value.trim();
  if (!text && !pendingAttachments.length) return;

  if (editingMsgId) {
    const msg = getMsgs(currentContact.id).find(m => m.id === editingMsgId);
    if (msg) { msg.text = text; msg.edited = true; }
    editingMsgId = null; clearReplyBar(); input.value = '';
    renderMessages(true); return;
  }

  const baseMsg = {
    from: 'me',
    time: fmtTime(new Date()),
    timestamp: new Date().toISOString(),
    status: 'delivered',
    reactions: {},
    pinned: false,
    edited: false
  };

  if (pendingAttachments.length) {
    const attachmentsCopy = [...pendingAttachments];
    pendingAttachments = [];
    document.getElementById('attachPreview').style.display = 'none';
    document.getElementById('attachList').innerHTML = '';

    attachmentsCopy.forEach((att, idx) => {
      const attMsg = {
        ...baseMsg,
        id: nextMsgId++,
        attachments: [att],
        text: idx === attachmentsCopy.length - 1 ? text : '',
        replyTo: idx === 0 ? (replyTo || null) : null,
      };
      getMsgs(currentContact.id).push(attMsg);
    });

    // Update sidebar preview
    const lastAtt = attachmentsCopy[attachmentsCopy.length - 1];
    currentContact.lastMsg = text || (lastAtt.type === 'image' ? '📷 Photo' : '📄 Document');
    currentContact.time = baseMsg.time;
    if (replyTo) clearReplyBar();

  } else {
    const msg = { ...baseMsg, id: nextMsgId++, text };
    if (replyTo) { msg.replyTo = replyTo; clearReplyBar(); }
    getMsgs(currentContact.id).push(msg);
    currentContact.lastMsg = text;
    currentContact.time = baseMsg.time;

    // Read receipt simulation
    setTimeout(() => { msg.status = 'read'; renderMessages(true); }, 1500);
  }

  input.value = '';
  renderMessages(false);
  scrollToBottom();
  renderwsidebar();

  if (!currentContact.isSelf) {
    setTimeout(() => {
      showTyping(currentContact.name);
      setTimeout(() => {
        hideTyping();
        const r = {
          id: nextMsgId++, text: 'Ok', from: 'them',
          time: fmtTime(new Date()), timestamp: new Date().toISOString(),
          status: 'read', reactions: {}, pinned: false, edited: false
        };
        getMsgs(currentContact.id).push(r);
        currentContact.lastMsg = r.text; currentContact.time = r.time;
        if (isAtBottom()) {
          renderMessages(false); scrollToBottom();
        } else {
          newMsgCount++;
          renderMessages(true);
        }
        renderwsidebar();
      }, 1600);
    }, 1800 + Math.random() * 2000);
  }
}

  document.getElementById('sendBtn').addEventListener('click', sendMessage);
  document.getElementById('messageInput').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });

  // ---------------------------------------
  //  REPLY / EDIT BAR
  // ---------------------------------------
  function setReply(msg) {
    replyTo = { name: msg.from === 'me' ? 'You' : currentContact.name, text: msg.text || (msg.image ? '  Photo' : '  Document') };
    document.getElementById('replyLabel').textContent = '? Reply to: ' + replyTo.name;
    document.getElementById('replyPreview').textContent = replyTo.text;
    document.getElementById('replyBar').style.display = 'flex';
    document.getElementById('messageInput').focus();
  }
  function setEdit(msg) {
    editingMsgId = msg.id;
    document.getElementById('replyLabel').textContent = '  Editing message';
    document.getElementById('replyPreview').textContent = msg.text;
    document.getElementById('replyBar').style.display = 'flex';
    document.getElementById('messageInput').value = msg.text;
    document.getElementById('messageInput').focus();
  }
  function clearReplyBar() {
    replyTo = null; editingMsgId = null;
    document.getElementById('replyBar').style.display = 'none';
    document.getElementById('messageInput').value = '';
  }
  document.getElementById('clearReply').addEventListener('click', clearReplyBar);

  // ---------------------------------------
  //  CONTEXT MENU
  // ---------------------------------------
  function showCtxMenu(e, msgId) {
    ctxMsgId = msgId;
    const menu = document.getElementById('ctxMenu');
    const msg = getMsgs(currentContact.id).find(m => m.id === msgId);
    const isMe = msg?.from === 'me';
    menu.querySelector('[data-action="edit"]').style.display = (isMe && msg?.text) ? 'flex' : 'none';
    const isPinned = getPinned(currentContact.id).includes(msgId);
    menu.querySelector('.ofcrm-chat-pin-label').textContent = isPinned ? 'Unpin' : 'Pin';
    menu.style.visibility = 'hidden'; menu.style.display = 'block';
    const menuW = menu.offsetWidth, menuH = menu.offsetHeight;
    menu.style.visibility = '';
    const x = Math.min(e.clientX, window.innerWidth - menuW - 8);
    const y = Math.min(e.clientY, window.innerHeight - menuH - 8);
    menu.style.left = Math.max(8, x) + 'px'; menu.style.top = Math.max(8, y) + 'px';
  }

  document.getElementById('ctxMenu').querySelectorAll('.ofcrm-chat-ctx-item').forEach(item => {
    item.addEventListener('click', () => {
      const action = item.dataset.action;
      const msgs = getMsgs(currentContact.id);
      const msg = msgs.find(m => m.id === ctxMsgId);
      document.getElementById('ctxMenu').style.display = 'none';
      if (!msg) return;

      if (action === 'reply') setReply(msg);
      else if (action === 'edit') setEdit(msg);
      else if (action === 'copy') {
        const text = msg.text || (msg.image ? '  Photo' : '  Document');
        if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).then(() => showToast('Copied!')).catch(() => fallbackCopy(text));
        else fallbackCopy(text);
      }
      else if (action === 'delete') {
        if (!confirm('Delete this message?')) return;
        messagesDB[currentContact.id] = msgs.filter(m => m.id !== ctxMsgId);
        renderMessages(true); showToast('Message deleted');
      }
      else if (action === 'pin') {
        const p = getPinned(currentContact.id);
        if (p.includes(ctxMsgId)) { pinnedMessages[currentContact.id] = p.filter(id => id !== ctxMsgId); showToast('Unpinned'); }
        else { p.push(ctxMsgId); showToast('Pinned ?'); }
        renderPinnedBanner(); renderMessages(true);
      }
      else if (action === 'react') {
        const picker = document.getElementById('reactPicker');
        const rect = item.getBoundingClientRect();
        picker.style.display = 'flex';
        const pickerW = picker.offsetWidth || 240;
        picker.style.left = Math.max(8, Math.min(rect.left, window.innerWidth - pickerW - 8)) + 'px';
        picker.style.top = Math.max(8, rect.top - 60) + 'px';
        picker.dataset.msgid = ctxMsgId;
      }
      else if (action === 'forward') { forwardMsgIds = [ctxMsgId]; openForwardModal(); }
    });
  });

  // Close menus on outside click
  document.addEventListener('click', e => {
    if (!e.target.closest('#ctxMenu')) document.getElementById('ctxMenu').style.display = 'none';
    if (!e.target.closest('#reactPicker')) document.getElementById('reactPicker').style.display = 'none';
    if (!e.target.closest('#attachMenu') && !e.target.closest('#attachBtn')) document.getElementById('attachMenu').style.display = 'none';
    if (!e.target.closest('#mentionDropdown')) document.getElementById('mentionDropdown').style.display = 'none';
    if (!e.target.closest('#imageMenu') && !e.target.closest('.ofcrm-chat-image-menu-btn')) document.getElementById('imageMenu').style.display = 'none';
  });

  // ---------------------------------------
  //  REACTION PICKER
  // ---------------------------------------
  document.querySelectorAll('.ofcrm-chat-react-opt').forEach(opt => {
    opt.addEventListener('click', () => {
      const picker = document.getElementById('reactPicker');
      const msgId = +picker.dataset.msgid, emoji = opt.dataset.r;
      const msg = getMsgs(currentContact.id).find(m => m.id === msgId); if (!msg) return;
      if (!msg.reactions[emoji]) msg.reactions[emoji] = [];
      const arr = msg.reactions[emoji], idx = arr.indexOf('me');
      if (idx === -1) arr.push('me'); else arr.splice(idx, 1);
      if (!arr.length) delete msg.reactions[emoji];
      picker.style.display = 'none';
      renderMessages(true);
    });
  });

  // ---------------------------------------
  //  PINNED MESSAGES
  // ---------------------------------------
  function renderPinnedBanner() {
    if (!currentContact) return;
    const p = getPinned(currentContact.id);
    const banner = document.getElementById('pinnedBanner');
    if (!p.length) { banner.style.display = 'none'; return; }
    const msg = getMsgs(currentContact.id).find(m => m.id === p[p.length - 1]);
    if (!msg) { banner.style.display = 'none'; return; }
    document.getElementById('pinnedBannerText').textContent = msg.text || (msg.image ? '  Photo' : '  Document');
    banner.style.display = 'flex';
  }
  document.getElementById('closePinnedBanner').addEventListener('click', e => { e.stopPropagation(); document.getElementById('pinnedBanner').style.display = 'none'; });
  document.getElementById('pinnedPanelBtn').addEventListener('click', () => {
    const panel = document.getElementById('pinnedPanel');
    panel.classList.toggle('ofcrm-chat-open');
    if (panel.classList.contains('ofcrm-chat-open')) renderPinnedPanel();
  });
  document.getElementById('closePinnedPanel').addEventListener('click', () => { document.getElementById('pinnedPanel').classList.remove('ofcrm-chat-open'); });

  function renderPinnedPanel() {
    if (!currentContact) return;
    const p = getPinned(currentContact.id), msgs = getMsgs(currentContact.id);
    const list = document.getElementById('pinnedPanelList');
    if (!p.length) { list.innerHTML = '<p style="font-size:13px;color:#8696a0;text-align:center;padding:20px 0;">No pinned messages</p>'; return; }
    list.innerHTML = p.map(id => {
      const msg = msgs.find(m => m.id === id); if (!msg) return '';
      return `<div style="background:#202c33;border-radius:10px;padding:12px;border-left:3px solid #00a884;">
      <p style="font-size:11px;color:#00a884;font-weight:700;margin:0 0 4px;">${msg.from === 'me' ? 'You' : escapeHTML(currentContact.name)}</p>
      <p style="font-size:13px;margin:0 0 4px;word-break:break-word;">${escapeHTML(msg.text || '  Media')}</p>
      <p style="font-size:11px;color:#8696a0;margin:0;">${msg.time}</p>
    </div>`;
    }).join('');
  }

  // ---------------------------------------
  //  SELECT / FORWARD
  // ---------------------------------------
  function enterSelectMode() { selectMode = true; document.getElementById('selectToolbar').style.display = 'flex'; }
  function exitSelectMode() {
    selectMode = false; selectedMsgs.clear();
    document.getElementById('selectToolbar').style.display = 'none';
    document.getElementById('selectCount').textContent = '0 selected';
    document.querySelectorAll('.ofcrm-chat-msg-wrap').forEach(el => el.classList.remove('ofcrm-chat-selected'));
  }
  function toggleSelectMsg(id) {
    if (selectedMsgs.has(id)) selectedMsgs.delete(id); else selectedMsgs.add(id);
    document.getElementById('selectCount').textContent = selectedMsgs.size + ' selected';
    document.querySelectorAll('.ofcrm-chat-msg-wrap').forEach(el => { el.classList.toggle('ofcrm-chat-selected', selectedMsgs.has(+el.dataset.id)); });
  }
  document.getElementById('selectModeBtn').addEventListener('click', () => { selectMode ? exitSelectMode() : enterSelectMode(); });
  document.getElementById('cancelSelectBtn').addEventListener('click', exitSelectMode);
  document.getElementById('deleteSelectedBtn').addEventListener('click', () => {
    if (!selectedMsgs.size) return;
    if (!confirm(`Delete ${selectedMsgs.size} message(s)?`)) return;
    messagesDB[currentContact.id] = getMsgs(currentContact.id).filter(m => !selectedMsgs.has(m.id));
    exitSelectMode(); renderMessages(false); showToast('Deleted');
  });
  document.getElementById('forwardSelectedBtn').addEventListener('click', () => {
    if (!selectedMsgs.size) return showToast('Select messages first');
    forwardMsgIds = [...selectedMsgs]; openForwardModal();
  });

  function openForwardModal() {
    const list = document.getElementById('forwardContactList');
    list.innerHTML = contacts.map(c => `
    <label style="display:flex;align-items:center;gap:12px;padding:10px 12px;border-radius:10px;cursor:pointer;transition:background .12s;" onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background=''">
      <input type="checkbox" class="ofcrm-chat-fwd-chk" value="${c.id}" style="accent-color:#00a884;width:16px;height:16px;flex-shrink:0;">
      <img src="${c.avatar}" style="width:36px;height:36px;border-radius:50%;flex-shrink:0;">
      <span style="font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(c.name)}</span>
    </label>`).join('');
    openChatModal('forwardModal');
  }
  document.getElementById('doForward').addEventListener('click', () => {
    const sel = [...document.querySelectorAll('.ofcrm-chat-fwd-chk:checked')].map(c => +c.value);
    if (!sel.length) return showToast('Select a chat');
    const msgs = getMsgs(currentContact.id).filter(m => forwardMsgIds.includes(m.id));
    sel.forEach(cid => {
      msgs.forEach(m => getMsgs(cid).push({ ...m, id: nextMsgId++, from: 'me', time: fmtTime(new Date()), status: 'delivered', replyTo: null }));
      const c = contacts.find(x => x.id === cid); if (c) { c.lastMsg = '? Forwarded'; c.time = fmtTime(new Date()); }
    });
    closeChatModal('forwardModal'); exitSelectMode(); renderwsidebar(); showToast(`Forwarded to ${sel.length} chat(s)`);
  });

  // ---------------------------------------
  //  ATTACHMENTS
  // ---------------------------------------
  document.getElementById('attachBtn').addEventListener('click', e => { e.stopPropagation(); const m = document.getElementById('attachMenu'); m.style.display = m.style.display === 'block' ? 'none' : 'block'; });
  document.getElementById('imageInput').addEventListener('change', function () {
    const files = Array.from(this.files);
    if (!files.length) return;
    const previewContainer = document.getElementById('attachPreview');
    const list = document.getElementById('attachList');

    files.forEach(file => {
      const url = URL.createObjectURL(file);
      const attachment = { id: nextMsgId++, type: 'image', url, name: file.name, size: (file.size / 1024).toFixed(1) + ' KB' };
      pendingAttachments.push(attachment);

      const item = document.createElement('div');
      item.className = 'ofcrm-chat-attach-item';
      item.dataset.id = attachment.id;
      item.innerHTML = `
      <img src="${url}" alt="${escapeHTML(file.name)}">
      <button type="button" class="ofcrm-chat-attach-remove" data-id="${attachment.id}">&times;</button>
    `;
      list.appendChild(item);
    });

    previewContainer.style.display = 'flex';
    document.getElementById('attachMenu').style.display = 'none';
    this.value = '';
  });
  document.getElementById('documentInput').addEventListener('change', function () {
    const files = Array.from(this.files);
    if (!files.length) return;
    const previewContainer = document.getElementById('attachPreview');
    const list = document.getElementById('attachList');

    files.forEach(file => {
      const attachment = { id: nextMsgId++, type: 'document', name: file.name, size: (file.size / 1024).toFixed(1) + ' KB' };
      pendingAttachments.push(attachment);

      const item = document.createElement('div');
      item.className = 'ofcrm-chat-attach-item ofcrm-chat-attach-doc';
      item.dataset.id = attachment.id;
      item.innerHTML = `
      <div style="display:flex;align-items:center;gap:8px;min-width:0;">
        <i class="ri-file-text-fill ofcrm-chat-attach-doc-icon"></i>
        <div class="ofcrm-chat-attach-doc-info">
          <p>${escapeHTML(file.name)}</p>
          <span>${attachment.size}</span>
        </div>
      </div>
      <button type="button" class="ofcrm-chat-attach-remove" data-id="${attachment.id}">&times;</button>
    `;
      list.appendChild(item);
    });

    previewContainer.style.display = 'flex';
    document.getElementById('attachMenu').style.display = 'none';
    this.value = '';
  });

  document.getElementById('attachPreview').addEventListener('click', function (e) {
    if (!e.target.closest('.ofcrm-chat-attach-remove')) return;
    const id = +e.target.dataset.id;
    pendingAttachments = pendingAttachments.filter(a => a.id !== id);
    const item = this.querySelector(`[data-id="${id}"]`);
    if (item) item.remove();
    if (!pendingAttachments.length) { this.style.display = 'none'; }
  });

  document.getElementById('clearAllAttach').addEventListener('click', () => {
    pendingAttachments = [];
    document.getElementById('attachPreview').style.display = 'none';
    document.getElementById('attachList').innerHTML = '';
  });

  // ---------------------------------------
  //  IMAGE MENU
  // ---------------------------------------
  document.getElementById('downloadImage').addEventListener('click', () => {
    const a = document.createElement('a'); a.href = selectedImage; a.download = 'image.jpg';
    document.body.appendChild(a); a.click(); a.remove();
    document.getElementById('imageMenu').style.display = 'none';
  });
  document.getElementById('forwardImage').addEventListener('click', () => {
    const imageMsg = { id: nextMsgId++, image: selectedImage, from: 'me', time: fmtTime(new Date()), status: 'delivered', reactions: {} };
    // store temporarily for forward
    if (currentContact) getMsgs(currentContact.id); // ensure exists
    forwardMsgIds = [imageMsg.id];
    // put in a temp map so forward can find it
    if (!messagesDB['_tmp']) messagesDB['_tmp'] = [];
    messagesDB['_tmp'].push(imageMsg);
    openForwardModal();
    document.getElementById('imageMenu').style.display = 'none';
  });


  // ---------------------------------------
  //  MENTION DROPDOWN
  // ---------------------------------------
  document.getElementById('messageInput').addEventListener('input', function () {
    const val = this.value, atIdx = val.lastIndexOf('@');
    const drop = document.getElementById('mentionDropdown');
    if (atIdx !== -1 && currentContact?.isGroup) {
      const q = val.slice(atIdx + 1).toLowerCase();
      const matches = (currentContact.members || []).filter(m => m.name !== 'You' && m.name.toLowerCase().startsWith(q));
      if (matches.length) {
        drop.innerHTML = matches.map(m => `<div class="ofcrm-chat-mention-opt" data-name="${m.name}" style="display:flex;align-items:center;gap:10px;padding:10px 14px;cursor:pointer;font-size:13px;transition:background .12s;" onmouseover="this.style.background='#2a3942'" onmouseout="this.style.background=''">
        <img src="${m.avatar}" style="width:28px;height:28px;border-radius:50%;"><span>${escapeHTML(m.name)}</span>
      </div>`).join('');
        drop.style.display = 'block';
        drop.querySelectorAll('.ofcrm-chat-mention-opt').forEach(opt => {
          opt.addEventListener('click', () => { this.value = val.slice(0, atIdx) + '@' + opt.dataset.name + ' '; drop.style.display = 'none'; this.focus(); });
        });
      } else { drop.style.display = 'none'; }
    } else { drop.style.display = 'none'; }
  });

  // ---------------------------------------
  //  MESSAGE SEARCH
  // ---------------------------------------
  document.getElementById('searchMsgBtn').addEventListener('click', () => {
    const bar = document.getElementById('msgSearchBar');
    bar.style.display = bar.style.display === 'flex' ? 'none' : 'flex';
    if (bar.style.display === 'flex') document.getElementById('msgSearchInput').focus();
    else clearSearchHighlights();
  });
  function closeMsgSearch() { document.getElementById('msgSearchBar').style.display = 'none'; document.getElementById('msgSearchInput').value = ''; clearSearchHighlights(); searchResults = []; }
  function runMsgSearch() {
    clearSearchHighlights();
    const q = document.getElementById('msgSearchInput').value.trim().toLowerCase();
    if (!q) { document.getElementById('msgSearchCount').textContent = ''; return; }
    searchResults = []; searchIdx = 0;
    document.querySelectorAll('.ofcrm-chat-msg-wrap').forEach(el => { if (el.textContent.toLowerCase().includes(q)) searchResults.push(el); });
    document.getElementById('msgSearchCount').textContent = searchResults.length ? `1/${searchResults.length}` : '0';
    highlightSearchResult();
  }
  function nextSearchResult() { if (!searchResults.length) return; searchIdx = (searchIdx + 1) % searchResults.length; document.getElementById('msgSearchCount').textContent = `${searchIdx + 1}/${searchResults.length}`; highlightSearchResult(); }
  function prevSearchResult() { if (!searchResults.length) return; searchIdx = (searchIdx - 1 + searchResults.length) % searchResults.length; document.getElementById('msgSearchCount').textContent = `${searchIdx + 1}/${searchResults.length}`; highlightSearchResult(); }
  function highlightSearchResult() { clearSearchHighlights(); if (!searchResults[searchIdx]) return; searchResults[searchIdx].style.outline = '2px solid #00a884'; searchResults[searchIdx].style.borderRadius = '8px'; searchResults[searchIdx].scrollIntoView({ behavior: 'smooth', block: 'center' }); }
  function clearSearchHighlights() { document.querySelectorAll('.ofcrm-chat-msg-wrap').forEach(el => { el.style.outline = ''; el.style.borderRadius = ''; }); }

  // ---------------------------------------
  //  INFINITE SCROLL (load older)
  // ---------------------------------------
  const OLDER = [
    { id: 80, text: 'Hey remember the sprint last month?', from: 'them', time: 'Last month', status: 'read', reactions: {}, pinned: false, edited: false },
    { id: 81, text: 'Yeah those were crazy deadlines', from: 'me', time: 'Last month', status: 'read', reactions: {}, pinned: false, edited: false },
    { id: 82, text: 'But we shipped it  ', from: 'them', time: 'Last month', status: 'read', reactions: {}, pinned: false, edited: false },
  ];
  let olderOffset = 0;
  document.getElementById('chatMessages').addEventListener('scroll', function () {
    if (this.scrollTop < 60 && currentContact) loadOlder();
    updateScrollBtn();
  });
  function loadOlder() {
    if (olderOffset >= OLDER.length) return;
    document.getElementById('olderLoader').style.display = 'block';
    setTimeout(() => {
      const toAdd = OLDER.slice(olderOffset, olderOffset + 2); olderOffset += 2;
      const msgs = getMsgs(currentContact.id);
      const cont = document.getElementById('chatMessages');
      const prev = cont.scrollHeight - cont.scrollTop;
      toAdd.reverse().forEach(m => msgs.unshift({ ...m }));
      renderMessages(true);
      cont.scrollTop = cont.scrollHeight - prev;
      document.getElementById('olderLoader').style.display = 'none';
      if (olderOffset >= OLDER.length) document.getElementById('olderLoader').textContent = 'No more messages';
    }, 700);
  }



  // ---------------------------------------
  //  GROUP ADMIN
  // ---------------------------------------
  document.getElementById('adminPanelBtn').addEventListener('click', () => { openChatModal('adminModal'); renderAdminPanel(); });
  document.getElementById('chatPinBtn').addEventListener('click', toggleChatPin);

function toggleChatPin() {
    if (!currentContact || currentContact.isSelf) return;
    if (currentContact.pinned) {
      currentContact.pinned = false;
      showToast('Chat unpinned');
    } else {
      if (getPinnedChatCount() >= 3) {
        showToast('You can only pin up to 3 chats');
        return;
      }
      currentContact.pinned = true;
      showToast('Chat pinned 📌');
    }
    renderwsidebar();
    renderChatPinButton();
  }
  function renderChatPinButton() {
    const btn = document.getElementById('chatPinBtn');
    if (!currentContact || currentContact.isSelf) {
      btn.style.display = 'none';
      return;
    }
    btn.style.display = 'flex';
    const icon = btn.querySelector('i');
    icon.className = currentContact.pinned ? 'ri-pushpin-fill' : 'ri-pushpin-line';
    btn.title = currentContact.pinned ? 'Unpin chat' : 'Pin chat';
    btn.style.color = currentContact.pinned ? '#00a884' : '#8696a0';
  }

  function renderAdminPanel() {
    if (!currentContact?.isGroup) return;
    document.getElementById('groupNameInput').value = currentContact.name;
    document.getElementById('groupIconImg').src = currentContact.avatar;

    const members = currentContact.members || [];
    document.getElementById('adminMemberList').innerHTML = members.map(m => `
    <div style="display:flex;align-items:center;gap:10px;padding:10px;border-radius:10px;background:#111b21;flex-wrap:wrap;">
      <img src="${m.avatar}" style="width:40px;height:40px;border-radius:50%;flex-shrink:0;">
      <div style="flex:1;min-width:0;">
        <p style="margin:0;font-size:14px;font-weight:600;display:flex;align-items:center;gap:6px;flex-wrap:wrap; color:#fff">
          ${escapeHTML(m.name)}${m.isAdmin ? '<span class="ofcrm-chat-admin-badge">ADMIN</span>' : ''}${m.muted ? '<i class=""></i>' : ''}
        </p>
      </div>
      ${m.name === 'You' ? `<button class="ofcrm-chat-adm-btn" data-action="exit" data-uid="${m.id}" style="background:rgba(100,150,200,.15);border:none;cursor:pointer;color:#64a3d9;border-radius:6px;padding:6px 10px;font-size:11px;white-space:nowrap;">Exit Group</button>` : (m.isAdmin ? '' : `<button class="ofcrm-chat-adm-btn" data-action="remove" data-uid="${m.id}" style="background:rgba(241,92,109,.15);border:none;cursor:pointer;color:#f15c6d;border-radius:6px;padding:6px 10px;font-size:11px;white-space:nowrap;">Remove</button>`)}
    </div>`).join('');

    const existing = members.map(m => m.id);
    const avail = contacts.filter(c => !c.isGroup && !c.isSelf && !existing.includes(c.id));
    const addSearchInput = document.getElementById('addMemberSearch');
    const addList = document.getElementById('adminAddMemberList');
    let filtered = avail;
    if (addSearchInput && addSearchInput.value.trim()) {
      const q = addSearchInput.value.toLowerCase();
      filtered = avail.filter(c => c.name.toLowerCase().includes(q));
    }
    if (!filtered.length) {
      addList.innerHTML = '<div style="color:#8696a0;font-size:13px;">No more contacts available.</div>';
    } else {
      addList.innerHTML = filtered.map(c => `
      <label style="display:flex;align-items:center;gap:10px;padding:8px;border-radius:10px;background:#111b21;cursor:pointer;">
        <input type="checkbox" value="${c.id}" style="width:16px;height:16px;" />
        <img src="${c.avatar}" style="width:36px;height:36px;border-radius:50%;object-fit:cover;flex-shrink:0;">
        <div style="flex:1;min-width:0;">
          <div style="font-size:13px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(c.name)}</div>
          <div style="font-size:11px;color:#8696a0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHTML(c.lastMsg)}</div>
        </div>
      </label>`).join('');
    }

    document.querySelectorAll('.ofcrm-chat-adm-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const uid = +btn.dataset.uid, action = btn.dataset.action;
        const member = members.find(m => m.id === uid); if (!member) return;
        if (action === 'exit') {
          if (!confirm('Exit group ' + currentContact.name + '?')) return;
          currentContact.members = members.filter(m => m.id !== uid);
          currentContact = null;
          closeChatModal('adminModal');
          updateChatPaneState();
          renderwsidebar();
          renderMessages();
          showToast('Left group');
        } else if (action === 'remove') {
          if (!confirm('Remove ' + member.name + '?')) return;
          currentContact.members = members.filter(m => m.id !== uid);
          showToast(member.name + ' removed');
          renderAdminPanel();
        }
      });
    });
  }

  document.getElementById('changeGroupIconBtn').addEventListener('click', () => document.getElementById('groupIconInput').click());
  document.getElementById('groupIconInput').addEventListener('change', function () {
    if (!this.files?.length) return;
    const file = this.files[0];
    const reader = new FileReader();
    reader.onload = () => {
      if (!currentContact?.isGroup) return;
      currentContact.avatar = reader.result;
      document.getElementById('groupIconImg').src = reader.result;
      document.getElementById('hdrAvatar').src = reader.result;
      renderwsidebar();
      showToast('Group icon updated');
    };
    reader.readAsDataURL(file);
    this.value = '';
  });
  document.getElementById('deleteGroupBtn').addEventListener('click', () => {
    if (!currentContact?.isGroup) return;
    if (!confirm(`Delete group ${currentContact.name}?`)) return;
    const deletedId = currentContact.id;
    contacts = contacts.filter(c => c.id !== deletedId);
    delete messagesDB[deletedId];
    currentContact = null;
    closeChatModal('adminModal');
    updateChatPaneState();
    renderwsidebar();
    renderMessages();
    showToast('Group deleted');
  });
  document.getElementById('createGroupIconBtn').addEventListener('click', () => document.getElementById('createGroupIconInput').click());
  document.getElementById('createGroupIconRemoveBtn').addEventListener('click', () => {
    createGroupIconData = '';
    document.getElementById('createGroupIconImg').src = 'https://media.istockphoto.com/id/1495088043/vector/user-profile-icon-avatar-or-person-icon-profile-picture-portrait-symbol-default-portrait.jpg?s=612x612&w=0&k=20&c=dhV2p1JwmloBTOaGAtaA3AW1KSnjsdMt7-U_3EZElZ0=';
    document.getElementById('createGroupIconRemoveBtn').style.display = 'none';
  });
  document.getElementById('createGroupIconInput').addEventListener('change', function () {
    if (!this.files?.length) return;
    const file = this.files[0];
    const reader = new FileReader();
    reader.onload = () => {
      createGroupIconData = reader.result;
      document.getElementById('createGroupIconImg').src = reader.result;
      document.getElementById('createGroupIconRemoveBtn').style.display = 'flex';
    };
    reader.readAsDataURL(file);
    this.value = '';
  });

  document.getElementById('groupNameInput').addEventListener('input', function () {
    if (!currentContact?.isGroup) return;
    currentContact.name = this.value.trim() || currentContact.name;
    document.getElementById('hdrName').textContent = currentContact.name;
    renderwsidebar();
  });

  document.getElementById('addMemberBtn').addEventListener('click', () => {
    if (!currentContact?.isGroup) return;
    const selected = [...document.querySelectorAll('#adminAddMemberList input[type=checkbox]:checked')].map(el => +el.value);
    if (!selected.length) return showToast('Select at least one contact');
    const newMembers = contacts.filter(c => selected.includes(c.id)).map(c => ({ id: c.id, name: c.name, avatar: c.avatar, isAdmin: false, muted: false }));
    currentContact.members = [...(currentContact.members || []), ...newMembers];
    showToast(`${newMembers.length} member${newMembers.length === 1 ? '' : 's'} added`);
    renderAdminPanel();
  });

  // ---------------------------------------
  //  ONLINE SIMULATION
  // ---------------------------------------
  setInterval(() => {
    contacts.forEach(c => { if (!c.isGroup && !c.isSelf && Math.random() < 0.06) c.online = !c.online; });
    if (currentContact && !currentContact.isGroup && !currentContact.isSelf) {
      const s = document.getElementById('hdrStatus'), d = document.getElementById('hdrDot');
      s.textContent = currentContact.online ? 'Online' : 'Last seen recently';
      s.style.color = currentContact.online ? '#00a884' : '#8696a0';
      d.className = currentContact.online ? 'ofcrm-chat-dot-on' : 'ofcrm-chat-dot-off';
    }
    renderwsidebar();
  }, 8000);

  // ---------------------------------------
  //  INIT
  // ---------------------------------------
  function initChatApp() {
    currentTab = 'all';
    syncSidebarTabs();
    renderwsidebar();
    updateChatPaneState();
    renderMessages();
    if (window.innerWidth <= 700) showwsidebar();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initChatApp);
  } else {
    initChatApp();
  }
</script>


<?php include 'footer.php'; ?>