<%

var _chan = active || null;
var _msgs = messages || [];
var _people = _chan ? (_chan.participants || []) : [];
var _STAFF_ROLES = ['staff', 'admin'];

function roleOf(u) {
  if (!u) return '';
  if (u.title) return u.title;
  return _STAFF_ROLES.indexOf(u.role) !== -1 ? 'VOCTOS' : '';
}

var _STAFF = ['staff', 'admin'];
var _roster = { agency: [], client: [] };
_people.forEach(function (p) {
  (_STAFF.indexOf(p.role) !== -1 ? _roster.agency : _roster.client).push(p);
});
var _clientSide = (locals.workspace && locals.workspace.name) || 'Client';

if (/^voctos$/i.test(String(_clientSide).trim())) _clientSide = 'Client accounts';

var _isStaff = currentUser && ['staff', 'admin'].indexOf(currentUser.role) !== -1;
var _clientName = (locals.workspace && locals.workspace.name) || 'this client';
var _emptyLine = _isStaff
  ? ('Nothing here yet. Anything you write is read by ' + _clientName + ' and everyone assigned to them.')
  : 'Nothing here yet. Anything you write is read by everyone on your VOCTOS team.';
var _placeholder = _isStaff ? ('Message ' + _clientName + '…') : 'Message your VOCTOS team…';
function _dayKey(d) { var x = new Date(d); return x.getFullYear() + '-' + x.getMonth() + '-' + x.getDate(); }
function _dayLabel(d) {
  var x = new Date(d), now = new Date();
  var y = new Date(now); y.setDate(now.getDate() - 1);
  if (_dayKey(x) === _dayKey(now)) return 'Today';
  if (_dayKey(x) === _dayKey(y)) return 'Yesterday';
  var o = { weekday: 'short', day: 'numeric', month: 'short' };
  if (x.getFullYear() !== now.getFullYear()) o.year = 'numeric';
  return x.toLocaleDateString('en-GB', o);
}
%>
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Business / Messages</div>
  </div>
</div>
<h1 class="claim">Messages</h1>

<div class="bento" style="margin-top:22px">

  <div id="chatRoot" data-conv="<%= _chan ? _chan._id : '' %>" data-me="<%= me._id %>"
       data-me-name="<%= me.name || '' %>" data-me-initials="<%= me.initials || (me.name||'U').slice(0,1) %>"
       data-me-color="<%= me.avatarColor || '' %>" data-me-avatar="<%= me.avatarUrl || '' %>"

       data-me-role="<%= me.role || '' %>" data-change-window="<%= locals.changeWindowMs || 0 %>"
       data-people="<%= JSON.stringify(_people.filter(function (p) { return String(p._id) !== String(me._id); }).map(function (p) { return { id: String(p._id), name: p.name || '', initials: p.initials || '', color: p.avatarColor || '', avatar: p.avatarUrl || '', title: p.title || '' }; })) %>"
       class="msgs b12">

    <section class="chat-main">
      <% if (_chan) { %>
      <div class="chat-head">
        <%- include('../partials/avatar', { url: '/img/favicon-512.png', initials: 'V', color: 'var(--grad)', name: _chan.name || 'VOCTOS Team', cls: 'avatar', size: 38 }) %>
        <div>
          <div class="ch-name"><%= _chan.name || 'VOCTOS Team' %></div>

          <div class="ch-status"><%= _people.length %> <%= _people.length === 1 ? 'person' : 'people' %>, <%= _isStaff ? _clientName + ' and everyone assigned to them' : 'everyone working on your account' %></div>
        </div>
        <div class="ch-actions">
          <a class="btn btn-sm" href="/meetings">Book meeting</a>
        </div>
      </div>

      <div class="chat-scroll" id="chatScroll" data-clarity-mask="true" data-empty-line="<%= _emptyLine %>">

        <% if (!_msgs.length) { %>
          <div class="rr-meta" data-chat-empty style="align-self:center; margin-top:18px"><%= _emptyLine %></div>
        <% } %>
        <% var _prev = null;
           _msgs.forEach(function(m){
             var s = m.sender;
             var mine = String(s && s._id) === String(me._id);
             var who  = mine ? 'You' : ((s && s.name) || 'Team');
             var sub  = mine ? '' : roleOf(s);
             var newDay = !_prev || _dayKey(_prev.createdAt) !== _dayKey(m.createdAt);
             var cont = !newDay && _prev && String(_prev.sender && _prev.sender._id) === String(s && s._id)
                        && (new Date(m.createdAt) - new Date(_prev.createdAt)) < 5 * 60 * 1000;
             _prev = m;
        %>
          <% if (newDay) { %><div class="day-sep" data-day="<%= _dayKey(m.createdAt) %>"><%= _dayLabel(m.createdAt) %></div><% } %>

          <div class="m <%= mine?'me':'them' %><%= cont ? ' cont' : '' %>" data-id="<%= m._id %>" data-sender="<%= s && s._id %>" data-at="<%= new Date(m.createdAt).getTime() %>">

            <span class="mface"><%- include('../partials/avatar', { url: s && s.avatarUrl, initials: (s && s.initials) || (who || 'U').slice(0,1), color: s && s.avatarColor, name: who, cls: 'avatar', size: 28 }) %></span>
            <div class="mcol">
              <div class="mwho"><%= who %><% if (sub) { %><span class="mrole"><%= sub %></span><% } %></div>
              <% if (m.body) { %><div class="mb" dir="auto" data-raw="<%= m.body %>"><%- m.bodyHtml %></div><% } %>
              <% (m.attachments || []).forEach(function(a){ %>
                <% if (a.missing) { %>
                  <div class="mgone"><svg class="i-inl" viewBox="0 0 16 16" width="14" height="14" fill="none" aria-hidden="true"><path d="M13 7.5l-5.2 5.2a3.2 3.2 0 01-4.5-4.5l5.6-5.6a2.1 2.1 0 013 3L6.3 11.2a1 1 0 01-1.5-1.5L9.9 4.6" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg><span><b><%= String(a.mime||'').indexOf('audio/') === 0 ? 'Voice message' : a.name %></b> <%= a.missingLocal ? 'is not on this local copy (it lives on the live server)' : 'is no longer available' %></span></div>
                <% } else if (String(a.mime||'').indexOf('audio/') === 0) { %>
                  <audio class="mvoice" controls preload="metadata" src="<%= a.url %>"></audio>
                <% } else if (String(a.mime||'').indexOf('image/') === 0) { %>

                  <a class="mimg" href="<%= a.url %>" target="_blank" rel="noopener noreferrer"><img src="<%= a.url %>" alt="<%= a.name %>"></a>
                <% } else { %>
                  <a class="mfile" href="<%= a.url %>" target="_blank" rel="noopener noreferrer" download="<%= a.name %>">
                    <span><svg class="i-inl" viewBox="0 0 16 16" width="14" height="14" fill="none" aria-hidden="true"><path d="M13 7.5l-5.2 5.2a3.2 3.2 0 01-4.5-4.5l5.6-5.6a2.1 2.1 0 013 3L6.3 11.2a1 1 0 01-1.5-1.5L9.9 4.6" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
                    <span><b><%= a.name %></b><span class="rr-meta" style="display:block"><%= a.size %></span></span>
                  </a>
                <% } %>
              <% }) %>

              <div class="mmeta"><span><%= h.time(m.createdAt) %></span><% if (m.editedAt) { %><span class="medited" title="Edited at <%= h.time(m.editedAt) %>">edited</span><% } %></div>
            </div>

            <% if (m.canEdit || m.canUnsend) { %>
            <div class="macts" data-change-in="<%= m.changeIn %>">
              <% if (m.canEdit) { %>
              <button type="button" class="mact" data-edit="<%= m._id %>" title="Edit" aria-label="Edit this message">
                <svg viewBox="0 0 16 16" width="14" height="14" fill="none" aria-hidden="true"><path d="M11.2 2.6a1.7 1.7 0 012.4 2.4l-7 7-3.1.7.7-3.1 7-7z" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
              </button>
              <% } %>
              <% if (m.canUnsend) { %>
              <button type="button" class="mact mact-danger" data-unsend="<%= m._id %>" title="Delete" aria-label="Delete this message">
                <svg viewBox="0 0 16 16" width="14" height="14" fill="none" aria-hidden="true"><path d="M3 4.5h10M6.2 4.5V3a1 1 0 011-1h1.6a1 1 0 011 1v1.5M4.6 4.5l.5 8.2a1.3 1.3 0 001.3 1.2h3.2a1.3 1.3 0 001.3-1.2l.5-8.2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
              </button>
              <% } %>
            </div>
            <% } %>
          </div>
        <% }) %>
      </div>

      <% if (_isStaff) { %>

      <div class="sched-list" id="schedList" hidden></div>
      <% } %>
      <div class="ctray" id="chatTray" hidden></div>
      <div class="composer" id="composerBar">
        <input type="file" id="chatFileInput" multiple style="display:none">
        <button type="button" class="cbtn" id="chatAttachBtn" title="Attach"><svg width="17" height="17" viewBox="0 0 16 16" fill="none"><path d="M9.5 4.5l-4 4a1.6 1.6 0 002.3 2.3l4.2-4.2a3 3 0 00-4.3-4.3L3 6.8a4.4 4.4 0 006.2 6.2l3.3-3.3" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
        <button type="button" class="cbtn" id="chatMicBtn" title="Record a voice message"><svg width="17" height="17" viewBox="0 0 16 16" fill="none"><path d="M8 1.6a2.4 2.4 0 00-2.4 2.4v3.2a2.4 2.4 0 004.8 0V4a2.4 2.4 0 00-2.4-2.4z" stroke="currentColor" stroke-width="1.4"/><path d="M3.6 7.2V8a4.4 4.4 0 008.8 0v-.8M8 12.4v2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg></button>
        <div class="cbox ceditor">

          <div class="cfmt" id="chatFmt" role="toolbar" aria-label="Formatting">
            <button type="button" class="cfb" data-fmt="bold" title="Bold (Ctrl+B)" aria-label="Bold"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M4.5 2.8h4.3a2.6 2.6 0 010 5.2H4.5zM4.5 8h5a2.7 2.7 0 010 5.3h-5z" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></svg></button>
            <button type="button" class="cfb" data-fmt="italic" title="Italic (Ctrl+I)" aria-label="Italic"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6.5 2.8h6M3.5 13.2h6M9.6 2.8L6.4 13.2" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></button>
            <button type="button" class="cfb" data-fmt="strike" title="Strikethrough (Ctrl+Shift+X)" aria-label="Strikethrough"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M2.5 8h11M11 4.6c-.4-1.2-1.6-1.9-3.1-1.9-1.8 0-3.1.9-3.1 2.3 0 .8.4 1.4 1.2 1.8M5 11.2c.4 1.3 1.7 2.1 3.2 2.1 1.9 0 3.2-1 3.2-2.4 0-.5-.1-.9-.4-1.2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg></button>
            <span class="cfsep" aria-hidden="true"></span>
            <button type="button" class="cfb" data-fmt="link" title="Link (Ctrl+K)" aria-label="Link"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6.8 9.2a3 3 0 004.3 0l2-2a3 3 0 00-4.3-4.3l-.9.9M9.2 6.8a3 3 0 00-4.3 0l-2 2a3 3 0 004.3 4.3l.9-.9" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg></button>
            <button type="button" class="cfb" data-fmt="ol" title="Numbered list" aria-label="Numbered list"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6.5 4h7M6.5 8h7M6.5 12h7" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M2.4 2.8h.9v2.6M2.3 5.4h1.9M2.3 9.6c0-.6.4-.9.9-.9s.9.3.9.8c0 .7-1.8 1.2-1.8 2.1h1.9" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
            <button type="button" class="cfb" data-fmt="ul" title="Bulleted list" aria-label="Bulleted list"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6.5 4h7M6.5 8h7M6.5 12h7" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><circle cx="3" cy="4" r="1.1" fill="currentColor"/><circle cx="3" cy="8" r="1.1" fill="currentColor"/><circle cx="3" cy="12" r="1.1" fill="currentColor"/></svg></button>
            <span class="cfsep" aria-hidden="true"></span>
            <button type="button" class="cfb" data-fmt="code" title="Code (Ctrl+E)" aria-label="Code"><svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M5.5 4.5L2 8l3.5 3.5M10.5 4.5L14 8l-3.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
            <div class="cfmt-link" hidden>
              <input type="url" class="cfmt-url" placeholder="Paste or type a link…" aria-label="Link address" dir="ltr">
              <button type="button" class="btn btn-primary btn-sm" data-link-ok>Add</button>
              <button type="button" class="btn btn-sm" data-link-cancel>Cancel</button>
            </div>
          </div>
          <div class="cmention" id="chatMention" role="listbox" hidden></div>
          <div id="chatInput" class="crich" contenteditable="true" role="textbox" aria-multiline="true" aria-label="Message" dir="auto" spellcheck="true" data-placeholder="<%= _placeholder %>"></div>
        </div>
        <% if (_isStaff) { %><button type="button" class="cbtn" id="chatSchedBtn" title="Schedule this message" aria-label="Schedule this message"><svg width="17" height="17" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8.6" r="5.6" stroke="currentColor" stroke-width="1.4"/><path d="M8 5.6v3.2l2 1.3M6 1.6h4" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg></button><% } %>
        <button id="chatSend" class="btn btn-primary" style="padding:11px 16px">Send</button>
      </div>
      <% if (_isStaff) { %>
      <div class="sched-panel" id="schedPanel" hidden>
        <label for="schedAt" class="rr-meta" style="font-weight:600">Send on</label>
        <input type="datetime-local" id="schedAt" class="input">
        <button type="button" class="btn btn-primary btn-sm" id="schedSave">Schedule</button>
        <button type="button" class="btn btn-sm" id="schedClose">Cancel</button>
        <span class="rr-meta" id="schedHint">Uses the text in the message box.</span>
      </div>
      <% } %>

      <div class="composer" id="recordingBar" style="display:none">
        <button type="button" class="cbtn" id="chatCancelRecBtn" title="Discard"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 4.5h10M6.2 4.5V3a1 1 0 011-1h1.6a1 1 0 011 1v1.5M4.5 4.5l.6 8.2a1.3 1.3 0 001.3 1.2h3.2a1.3 1.3 0 001.3-1.2l.6-8.2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
        <div class="cbox">
          <span class="rec-dot"></span>
          <span id="recTimer" style="font-weight:600; color:var(--ink)">0:00</span>
          <span class="rr-meta">Recording voice message…</span>
        </div>
        <button type="button" class="btn btn-primary" id="chatStopRecBtn" style="padding:11px 16px" title="Stop and send">Send</button>
      </div>
      <% } else { %>

        <div class="chat-scroll" style="align-items:center;justify-content:center"><div class="muted">Pick a project to see its messages.</div></div>
      <% } %>
    </section>

    <aside class="chat-ctx">
      <div>
        <div class="rr-lbl" style="margin-bottom:12px">In this room</div>

        <%
          var _groups = [
            { label: 'VOCTOS', people: _roster.agency },
            { label: _clientSide, people: _roster.client }
          ].filter(function (g) { return g.people.length; });
        %>
        <% _groups.forEach(function (g, gi) { %>
          <div style="<%= gi ? 'margin-top:16px' : '' %>">
            <div class="rr-meta" style="font-weight:600; margin-bottom:9px"><%= g.label %></div>
            <div style="display:flex; flex-direction:column; gap:11px">
              <% g.people.forEach(function(t){ var _isMe = String(t._id) === String(me._id); %>
                <div style="display:flex; gap:10px; align-items:center">
                  <%- include('../partials/avatar', { url: t.avatarUrl, initials: t.initials, color: t.avatarColor, name: t.name, cls: 'avatar', size: 30 }) %>
                  <div style="font-size:var(--fs-sm)"><b><%= t.name %></b><%= _isMe ? ' (you)' : '' %><div class="rr-meta"><%= t.title || '' %></div></div>
                </div>
              <% }) %>
            </div>
          </div>
        <% }) %>
        <% if (!_groups.length) { %><div class="rr-meta">Nobody is in this room yet.</div><% } %>
      </div>
    </aside>
  </div>
</div>

<style>
  .ctray{display:flex; flex-wrap:wrap; gap:8px; padding:10px 14px 0}
  .ctray[hidden]{display:none}
  .ctray-i{position:relative; display:flex; align-items:center; gap:8px; max-width:220px; padding:6px 30px 6px 6px; border:1px solid var(--line); border-radius:10px; background:var(--surface); font-size:var(--fs-sm)}
  .ctray-i img{width:44px; height:44px; object-fit:cover; border-radius:7px; display:block}
  .ctray-i .ctray-f{width:44px; height:44px; border-radius:7px; background:var(--surface-2); display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:700; color:var(--muted); text-transform:uppercase}
  .ctray-i .ctray-n{min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap}
  .ctray-i .ctray-n small{display:block; color:var(--muted)}
  .ctray-x{position:absolute; top:4px; right:4px; width:22px; height:22px; border:0; border-radius:50%; background:var(--surface-2); color:var(--ink); cursor:pointer; line-height:22px; font-size:15px}
  .ctray-x:hover{background:var(--neg); color:#fff}
  .ceditor{position:relative}
  .cmention{position:absolute; left:0; right:0; bottom:calc(100% + 6px); z-index:30; max-height:240px; overflow:auto; background:var(--surface); border:1px solid var(--line); border-radius:12px; box-shadow:0 10px 30px rgba(13,23,45,.16); padding:6px}
  .cmention[hidden]{display:none}
  .cmention-i{display:flex; align-items:center; gap:10px; width:100%; padding:7px 9px; border:0; border-radius:8px; background:none; text-align:left; cursor:pointer; font-size:var(--fs-sm); color:var(--ink)}
  .cmention-i.on, .cmention-i:hover{background:var(--surface-2)}
  .cmention-i .av{width:26px; height:26px; border-radius:50%; flex:none; display:flex; align-items:center; justify-content:center; color:#fff; font-size:11px; font-weight:700; background:var(--teal); background-size:cover; background-position:center}
  .cmention-i small{color:var(--muted); margin-left:auto; white-space:nowrap}
  .mention{color:var(--teal-600, #0E8194); font-weight:600; background:rgba(18,169,192,.1); border-radius:5px; padding:0 3px}
  .composer.is-drop{outline:2px dashed var(--teal); outline-offset:-4px}
</style>
<script>
(function () {

  function init() {

    var chatInput = document.getElementById('chatInput');
    var composerBar = document.getElementById('composerBar');
    if (chatInput && composerBar) {
      var syncComposerWidth = function () {

        var v = chatInput.value != null ? chatInput.value : chatInput.textContent;
        var tray = document.getElementById('chatTray');
        composerBar.classList.toggle('has-text', String(v || '').trim().length > 0 || !!(tray && !tray.hidden));
      };
      chatInput.addEventListener('input', syncComposerWidth);
      syncComposerWidth();
    }
  }
  init();
  document.addEventListener('voctos:refreshed', function (e) {
    if (e.detail && e.detail.selector === '#chatRoot') init();
  });
})();
</script>
