<%

var a = locals.alerts || { feeds: [], manageUrl: null, lastSyncAt: null };
var c = locals.counts || {};
var ms = locals.mentions || [];
var pubs = locals.publishers || [];
var isAgencyUser = locals.showStaff;
var configured = (a.feeds || []).filter(function (f) { return f && f.url; });
var broken = configured.filter(function (f) { return f.lastError; });

var news = a.news || null;
var newsOn = !!(news && news.query);
var anySource = configured.length || newsOn || c.total > 0;
var SRC = { 'google-news': 'Google News', 'google-alerts': 'Google Alerts' };
var SENT = { positive: 'pos', negative: 'neg', neutral: 'flat' };

var _msSpan = isAgencyUser ? 'b8' : 'b12';

var srcHelp = h.ihelp('Where this comes from',
  'Articles that mention you, from <b>Google News</b> and <b>Google Alerts</b>. '
  + 'Google Alerts covers more than news and starts from the day it is connected.'
  + '<br><br>Positive or negative labels are set by your VOCTOS team.');
%>

<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Overview / My Reputation</div>
  </div>
  <div class="ph-right">

    <% if (a.lastSyncAt) { var _ck = new Date(a.lastSyncAt), _today = _ck.toDateString() === new Date().toDateString(); %><span class="rr-meta">Mentions checked <%= _today ? 'today, ' + _ck.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : h.stamp(_ck) %></span><% } %>

  </div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (anySource && c.last30) { %>
  <p class="claim-lede"><em><%= c.last30 %></em> page<%= c.last30===1?'':'s' %> published your name in the last 30 days.</p>
<% } else if (anySource && c.total) { %>
  <p class="claim-lede">Nothing new was published about you in the last 30 days.</p>
<% } else if (anySource) { %>
  <p class="claim-lede">Nothing has been published with your name in it yet.</p>
<% } else { %>
  <p class="claim-lede">Reputation monitoring isn't set up yet.</p>
<% } %>
<p class="claim-sub"><%
  if (anySource && c.total) { %><b><%= c.total %></b> in total, <b><%= c.unreviewed %></b> still to review.<%
  } else if (anySource) { %>Last checked <%= a.lastSyncAt ? h.timeAgo(a.lastSyncAt) : 'never' %>.<%
  } else { %>Mentions appear here once monitoring is set up.<% }
%></p>

<% if (!anySource) { %>

  <div class="card" style="margin-top:22px">
    <% if (isAgencyUser) { %>
      <%- include('../partials/empty', { title: 'Reputation monitoring is off',
            line: 'Add a brand name for Google News, or a Google Alerts feed, in this client\'s settings.',
            cta: workspace && workspace.slug ? { href: '/staff/clients/' + workspace.slug + '/edit', label: 'Open client settings' } : null }) %>
    <% } else { %>
      <%- include('../partials/empty', { title: 'Monitoring isn\'t running yet',
            line: 'Your VOCTOS team is setting it up.',
            cta: { href: '/messages', label: 'Message your team' } }) %>
    <% } %>
  </div>
<% } else { %>

  <% if (broken.length) { %>

    <div class="card card-p" style="margin-top:22px; padding-bottom:0">
      <div class="note" style="margin-bottom:16px">
        <span class="ic" style="background:var(--warn)">!</span>
        <div>
          <b><%= broken.length %> of <%= configured.length %> alert feed<%= configured.length===1?'':'s' %> could not be read.</b>
          The list below may be missing recent mentions until this is fixed.
          <% if (isAgencyUser) { %>
            <div class="rr-meta" style="margin-top:6px">
              <% broken.forEach(function (f) { %><div><%= f.label || f.url %>: <%= f.lastError %></div><% }) %>
            </div>
          <% } %>
        </div>
      </div>
    </div>
  <% } %>

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

    <div class="vdark vd-cut b7">
      <span class="vn-fillet"></span>

      <% if (isAgencyUser) { %>

        <form class="inline-form js-async-run" method="POST" action="/api/mentions/sync" style="position:absolute;top:0;right:0">
          <button class="vn-cut" type="submit">Check now
            <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M10 6a4 4 0 11-1.2-2.85M10 1.6V4H7.6" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
          </button>
        </form>
      <% } else { %>
        <a class="vn-cut" href="/my-reputation?show=new">Not reviewed
          <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M3 9L9 3M9 3H4.2M9 3v4.8" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </a>
      <% } %>
      <div class="vd-k">Mentions, last 30 days <%- srcHelp %></div>

      <div class="vd-row">
        <div class="vd-num tnum"><% if (c.last30 != null) { %><%= c.last30 %><% } else { %><span class="noval">—</span><% } %></div>
      </div>

      <div class="vd-sub">Positive and negative labels are set by your VOCTOS team.</div>
      <div class="ov-strip ov-1" style="margin-top:20px">

        <div class="ov">
          <div class="ovl">Marked by your team</div>

          <div class="ovv" style="font-size:var(--fs-md); gap:7px">
            <% if (c.positive || c.negative) { %>
              <span class="chip pos"><%= c.positive %> good</span>
              <span class="chip neg"><%= c.negative %> bad</span>
            <% } else { %><span class="noval">—</span><% } %>
          </div>
          <div class="rr-meta" style="margin-top:6px"><%= c.unjudged %> not marked</div>
        </div>
      </div>

    </div>

    <div class="card card-p b5">
      <div class="row-between"><span class="rr-lbl">Who is writing about you</span></div>
      <div style="margin-top:11px">
        <% if (!pubs.length) { %><div class="rr-meta">No publications yet.</div><% } %>
        <% pubs.forEach(function (p) { %>
          <div class="gc-ev-row"><span class="gc-ev-l"><%= p.name %></span><b class="gc-ev-v"><%= p.n %></b></div>
        <% }) %>
      </div>
    </div>

    <div class="card shelf-c b4 sc-violet"><div class="cl">All time</div><div class="cv tnum"><%= c.total %></div></div>
    <div class="card shelf-c b4 sc-lime"><div class="cl">Not reviewed yet</div><div class="cv tnum"><%= c.unreviewed %></div></div>
    <div class="card shelf-c b4 sc-navy"><div class="cl">Ignored (not about you)</div><div class="cv tnum"><%= c.ignored || 0 %></div></div>

    <div class="card <%= _msSpan %>" id="rep-mentions">
      <div class="card-h">
        <h3>Mentions</h3>
        <span class="hint" style="margin-left:auto">
          <a href="/my-reputation" class="<%= !show ? 'strong' : '' %>">Active</a> ·
          <a href="/my-reputation?show=new" class="<%= show==='new' ? 'strong' : '' %>">Not reviewed</a> ·
          <a href="/my-reputation?show=ignored" class="<%= show==='ignored' ? 'strong' : '' %>">Ignored</a>
        </span>
      </div>

      <% if (!ms.length) { %>
        <% if (show === 'ignored') { %><%- include('../partials/empty', { title: 'Nothing ignored', pad: 'sm' }) %>
        <% } else if (show === 'new') { %><%- include('../partials/empty', { title: 'All caught up', line: 'Every mention has been reviewed.', pad: 'sm' }) %>
        <% } else { %><%- include('../partials/empty', { title: 'No mentions yet', line: 'Last checked ' + (a.lastSyncAt ? h.timeAgo(a.lastSyncAt) : 'never') + '.', pad: 'sm' }) %><% } %>
      <% } else { %>
        <div class="card-p" style="display:flex; flex-direction:column; gap:11px">
          <% ms.forEach(function (m) { %>
            <div class="bubble" style="border-left:3px solid <%= m.sentiment==='negative' ? 'var(--neg)' : (m.sentiment==='positive' ? 'var(--pos)' : 'var(--line)') %>; <%= m.status==='ignored' ? 'opacity:.6' : '' %>">
              <div class="row-between" style="gap:10px; margin-bottom:4px">

                <a href="<%= m.url %>" target="_blank" rel="noopener noreferrer nofollow" class="strong" style="font-size:var(--fs-base)"
                   title="<%= m.source === 'google-news' ? 'Opens ' + (m.publisher || 'the article') + ' via Google News' : 'Opens ' + (m.publisher || 'the article') %>"><%= m.title %></a>
                <span style="display:inline-flex; gap:6px; align-items:center; flex:none">
                  <% if (m.sentiment) { %><span class="chip <%= SENT[m.sentiment] %>"><%= m.sentiment %></span><% } %>
                  <% if (m.status === 'ignored') { %><span class="chip flat">ignored</span>
                  <% } else if (m.status === 'new') { %><span class="chip flat">not reviewed</span><% } %>

                  <% if (isAgencyUser && m.source) { %><span class="rr-meta" style="font-size:var(--fs-2xs)"><%= SRC[m.source] || m.source %></span><% } %>
                </span>
              </div>
              <div class="rr-meta">
                <%= m.publisher %>

                · <%= m.publishedAt ? h.dateOnly(m.publishedAt) : 'date not given by the feed' %>
              </div>

              <% if (m.snippet) { %><div style="margin-top:6px; font-size:var(--fs-base)"><%= m.snippet %></div><% } %>
              <% if (m.note) { %>
                <div class="rr-meta" style="margin-top:7px; padding-top:7px; border-top:1px solid var(--line)">
                  <b style="color:var(--ink)">Note:</b> <%= m.note %>
                </div>
              <% } %>

              <% if (isAgencyUser) { %>
                <details style="margin-top:8px">

                  <summary class="more" style="cursor:pointer; font-size:var(--fs-xs)">Review</summary>
                  <form method="POST" action="/api/mentions/<%= m._id %>/review" class="addform js-ajax-form" data-refresh="#rep-mentions" style="margin-top:8px">
                    <div class="fld" style="flex:0 0 150px"><label for="rep-sent-<%= m._id %>">How it reads</label>
                      <select id="rep-sent-<%= m._id %>" name="sentiment">
                        <option value="" <%= !m.sentiment ? 'selected' : '' %>>Not marked</option>
                        <option value="positive" <%= m.sentiment==='positive'?'selected':'' %>>Positive</option>
                        <option value="neutral" <%= m.sentiment==='neutral'?'selected':'' %>>Neutral</option>
                        <option value="negative" <%= m.sentiment==='negative'?'selected':'' %>>Negative</option>
                      </select>
                    </div>
                    <div class="fld" style="flex:0 0 140px"><label for="rep-status-<%= m._id %>">Status</label>
                      <select id="rep-status-<%= m._id %>" name="status">
                        <option value="new" <%= m.status==='new'?'selected':'' %>>Not reviewed</option>
                        <option value="reviewed" <%= m.status==='reviewed'?'selected':'' %>>Reviewed</option>
                        <option value="ignored" <%= m.status==='ignored'?'selected':'' %>>Ignored (not about us)</option>
                      </select>
                    </div>
                    <div class="fld" style="flex:1 1 220px"><label for="rep-note-<%= m._id %>">Note</label><input id="rep-note-<%= m._id %>" name="note" value="<%= m.note || '' %>" placeholder="Context for the client"></div>
                    <button class="btn btn-primary btn-sm" type="submit">Save</button>
                  </form>
                </details>
              <% } %>
            </div>
          <% }) %>
        </div>
      <% } %>
    </div>

    <% if (isAgencyUser) { %>

    <div class="card card-p b4">
      <div class="rr-lbl" style="margin-bottom:9px">Sources</div>
      <% if (newsOn) { %>
        <div style="margin-bottom:11px">

          <div style="font-size:var(--fs-sm); font-weight:600">Google News</div>
          <div class="rr-meta">
            <span class="code"><%= news.query %></span> · <%= news.gl %>/<%= news.hl %>
            <br><%= news.lastCount %> item<%= news.lastCount === 1 ? '' : 's' %><%= news.lastFetchedAt ? ' · read ' + h.timeAgo(news.lastFetchedAt) : '' %>
            <br>from the <%= news.from %>
          </div>
        </div>
      <% } else if (news && news.lastError) { %>
        <div style="margin-bottom:11px">
          <div style="font-size:var(--fs-sm); font-weight:600">Google News</div>
          <div class="rr-meta"><span style="color:var(--warn-ink)"><%= news.lastError %></span> <a href="/settings#connections">Settings</a></div>
        </div>
      <% } %>
      <% if (configured.length) { %><div class="rr-lbl" style="margin:12px 0 8px">Alert feeds</div><% } %>
      <% configured.forEach(function (f) { %>
        <div style="margin-bottom:9px">

          <div style="font-size:var(--fs-sm); font-weight:600"><%= f.label || 'Alert' %></div>
          <div class="rr-meta">
            <% if (f.lastError) { %><span style="color:var(--warn-ink)"><%= f.lastError %></span>
            <% } else if (f.lastFetchedAt) { %><%= f.lastCount %> item<%= f.lastCount===1?'':'s' %> · read <%= h.timeAgo(f.lastFetchedAt) %>
            <% } else { %>not read yet<% } %>
          </div>
        </div>
      <% }) %>
      <% if (a.manageUrl) { %>
        <div class="divider" style="margin:10px 0"></div>
        <a class="btn btn-sm" href="<%= a.manageUrl %>" target="_blank" rel="noopener noreferrer">Manage in Google Alerts ↗</a>

        <div class="note-box" style="margin-top:9px">Opens Google Alerts settings. Mentions on this page come from the feeds listed above.</div>
      <% } %>
    </div>
    <% } %>
  </div>
<% } %>
