<%- include('../partials/header') %>

<%
function fmtDateRo(v) {
  if (!v) return '-';
  const d = new Date(v);
  if (isNaN(d.getTime())) return String(v);
  const p = n => String(n).padStart(2,'0');
  return `${p(d.getDate())}.${p(d.getMonth()+1)}.${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}`;
}

function sortUrl(field) {
  const nd = (sort===field && dir==='asc') ? 'desc' : 'asc';
  return `?store_id=${encodeURIComponent(storeId)}&customer_type=${encodeURIComponent(customerType)}&q=${encodeURIComponent(q)}&page_size=${pageSize}&sort=${field}&dir=${nd}`;
}

function sortMark(field) {
  return sort===field ? (dir==='asc' ? '▲' : '▼') : '';
}
%>

<style>
.contacts-toolbar {
  display:grid;
  grid-template-columns:minmax(170px,1fr) minmax(150px,.8fr) minmax(260px,2fr) auto auto;
  gap:10px;
  align-items:center;
}
.contacts-toolbar select,
.contacts-toolbar input,
.contacts-toolbar button {
  min-width:0;
}

.contacts-card {
  overflow:hidden;
}

.contacts-table {
  width:100%;
  table-layout:fixed;
  border-collapse:collapse;
}

.contacts-table th,
.contacts-table td {
  padding:10px 8px;
  vertical-align:middle;
  overflow-wrap:anywhere;
  word-break:normal;
}

.contacts-table th {
  white-space:normal;
  font-size:12px;
  line-height:1.15;
}

.contacts-table td {
  font-size:12px;
  line-height:1.25;
}

.contacts-table .col-email { width:17%; }
.contacts-table .col-type { width:6%; text-align:center; }
.contacts-table .col-company { width:16%; }
.contacts-table .col-contact { width:17%; }
.contacts-table .col-location { width:12%; }
.contacts-table .col-orders { width:15%; }
.contacts-table .col-emailstats { width:10%; }
.contacts-table .col-action { width:7%; text-align:center; }

.customer-badge {
  display:inline-block;
  padding:3px 7px;
  border-radius:999px;
  font-size:11px;
  font-weight:800;
  white-space:nowrap;
  background:#eef2ff;
}

.customer-badge.pj { background:#e0f2fe; }
.customer-badge.pf { background:#ecfdf5; }

.cell-main {
  font-weight:700;
}

.cell-sub {
  color:#64748b;
  font-size:11px;
  margin-top:2px;
}

.stat-line {
  white-space:nowrap;
}

.contacts-pagination {
  display:flex;
  flex-wrap:wrap;
  gap:8px;
  align-items:center;
  justify-content:flex-end;
  margin-top:12px;
}
.contacts-pagination .count {
  margin-right:auto;
}

/* Laptop / desktop mai îngust */
@media (max-width: 1450px) {
  .contacts-table th,
  .contacts-table td {
    padding:8px 6px;
    font-size:11px;
  }

  .contacts-table th {
    font-size:11px;
  }

  .contacts-table .col-email { width:18%; }
  .contacts-table .col-company { width:17%; }
  .contacts-table .col-contact { width:16%; }
  .contacts-table .col-location { width:11%; }
  .contacts-table .col-orders { width:15%; }
  .contacts-table .col-emailstats { width:9%; }
}

/* Tablet landscape */
@media (max-width: 1180px) {
  .contacts-toolbar {
    grid-template-columns:1fr 1fr;
  }

  .contacts-toolbar input {
    grid-column:1 / -1;
  }

  .contacts-table .col-emailstats {
    display:none;
  }

  .contacts-table .col-email { width:19%; }
  .contacts-table .col-type { width:7%; }
  .contacts-table .col-company { width:18%; }
  .contacts-table .col-contact { width:18%; }
  .contacts-table .col-location { width:13%; }
  .contacts-table .col-orders { width:17%; }
  .contacts-table .col-action { width:8%; }
}

/* Tablet portrait / ecran mic: carduri, fără scroll orizontal */
@media (max-width: 900px) {
  .contacts-card {
    background:transparent;
    box-shadow:none;
    padding:0;
    overflow:visible;
  }

  .contacts-table,
  .contacts-table tbody,
  .contacts-table tr,
  .contacts-table td {
    display:block;
    width:100% !important;
  }

  .contacts-table thead {
    display:none;
  }

  .contacts-table tr {
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:12px;
    padding:12px;
    margin-bottom:10px;
  }

  .contacts-table td {
    border:0;
    padding:5px 0;
    font-size:12px;
  }

  .contacts-table td::before {
    content:attr(data-label);
    display:inline-block;
    width:105px;
    color:#64748b;
    font-size:11px;
    font-weight:700;
    vertical-align:top;
  }

  .contacts-table .col-type {
    text-align:left;
  }

  .contacts-table .col-emailstats {
    display:block;
  }

  .contacts-table .col-action {
    text-align:left;
    padding-top:8px;
  }

  .contacts-table .col-action::before {
    content:'';
    width:105px;
  }

  .contacts-pagination {
    justify-content:center;
  }

  .contacts-pagination .count {
    width:100%;
    text-align:center;
    margin-right:0;
  }
}

@media (max-width: 600px) {
  .contacts-toolbar {
    grid-template-columns:1fr;
  }

  .contacts-toolbar input {
    grid-column:auto;
  }

  .contacts-toolbar select,
  .contacts-toolbar input,
  .contacts-toolbar button {
    width:100%;
  }
}
</style>

<form class="toolbar contacts-toolbar" method="get">
  <select name="store_id">
    <option value="">Toate magazinele</option>
    <% stores.forEach(s => { %>
      <option value="<%= s.id %>" <%= String(storeId)===String(s.id)?'selected':'' %>><%= s.name %></option>
    <% }) %>
  </select>

  <select name="customer_type">
    <option value="">PF + PJ</option>
    <option value="PF" <%= customerType==='PF'?'selected':'' %>>Persoană fizică</option>
    <option value="PJ" <%= customerType==='PJ'?'selected':'' %>>Firmă</option>
    <option value="NECUNOSCUT" <%= customerType==='NECUNOSCUT'?'selected':'' %>>Necunoscut</option>
  </select>

  <input
    name="q"
    value="<%= q %>"
    placeholder="Email / nume / telefon / firmă / CUI / oraș"
  >

  <select name="page_size" style="width:auto">
    <% [20,50,100,200].forEach(n => { %>
      <option value="<%= n %>" <%= pageSize===n?'selected':'' %>><%= n %>/pagină</option>
    <% }) %>
  </select>

  <button class="btn">Caută</button>
</form>

<div class="card contacts-card">
  <table class="contacts-table">
    <thead>
      <tr>
        <th class="col-email">
          <a href="<%= sortUrl('email') %>">Email <%= sortMark('email') %></a>
        </th>

        <th class="col-type">
          <a href="<%= sortUrl('customer_type') %>">Tip <%= sortMark('customer_type') %></a>
        </th>

        <th class="col-company">
          <a href="<%= sortUrl('company_name') %>">Firmă / CUI <%= sortMark('company_name') %></a>
        </th>

        <th class="col-contact">
          <a href="<%= sortUrl('last_name') %>">Contact <%= sortMark('last_name') %></a>
        </th>

        <th class="col-location">
          <a href="<%= sortUrl('city') %>">Locație <%= sortMark('city') %></a>
        </th>

        <th class="col-orders">
          <a href="<%= sortUrl('total_orders') %>">Comenzi / Valoare <%= sortMark('total_orders') %></a>
        </th>

        <th class="col-emailstats">
          <a href="<%= sortUrl('emails_sent') %>">Email E/D/C <%= sortMark('emails_sent') %></a>
        </th>

        <th class="col-action">360°</th>
      </tr>
    </thead>

    <tbody>
      <% contacts.forEach(c => { %>
        <tr>
          <td class="col-email" data-label="Email">
            <div class="cell-main"><%= c.email %></div>
          </td>

          <td class="col-type" data-label="Tip">
            <span class="customer-badge <%= String(c.customer_type || '').toLowerCase() %>">
              <%= c.customer_type === 'PJ'
                ? 'PJ'
                : (c.customer_type === 'PF' ? 'PF' : '?') %>
            </span>
          </td>

          <td class="col-company" data-label="Firmă / CUI">
            <% if (c.company_name) { %>
              <div class="cell-main"><%= c.company_name %></div>
              <div class="cell-sub">CUI: <%= c.cui || '-' %></div>
            <% } else { %>
              <div>-</div>
            <% } %>
          </td>

          <td class="col-contact" data-label="Contact">
            <div class="cell-main">
              <%= [c.first_name,c.last_name].filter(Boolean).join(' ') || '-' %>
            </div>
            <div class="cell-sub"><%= c.phone || '-' %></div>
          </td>

          <td class="col-location" data-label="Locație">
            <div><%= c.city || '-' %></div>
            <div class="cell-sub"><%= c.county || '-' %></div>
          </td>

          <td class="col-orders" data-label="Comenzi">
            <div class="stat-line">
              <strong><%= c.total_orders || 0 %></strong> comenzi
            </div>
            <div class="stat-line">
              <strong><%= Number(c.total_spent || 0).toFixed(2) %></strong> RON
            </div>
            <div class="cell-sub">
              Ultima: <%= fmtDateRo(c.last_order_at) %>
            </div>
          </td>

          <td class="col-emailstats" data-label="Email E/D/C">
            <div class="stat-line">
              <strong><%= c.emails_sent || 0 %></strong> /
              <strong><%= c.emails_opened || 0 %></strong> /
              <strong><%= c.email_clicks || 0 %></strong>
            </div>
            <div class="cell-sub">trimise / deschise / clickuri</div>
          </td>

          <td class="col-action" data-label="">
            <a class="btn" href="/contacts/<%= c.id %>">360°</a>
          </td>
        </tr>
      <% }) %>
    </tbody>
  </table>

  <div class="contacts-pagination">
    <span class="count"><strong><%= total %></strong> contacte</span>

    <% if (page>1) { %>
      <a class="btn" href="?store_id=<%= encodeURIComponent(storeId) %>&customer_type=<%= encodeURIComponent(customerType) %>&q=<%= encodeURIComponent(q) %>&page_size=<%= pageSize %>&sort=<%= sort %>&dir=<%= dir %>&page=1">« Prima</a>
      <a class="btn" href="?store_id=<%= encodeURIComponent(storeId) %>&customer_type=<%= encodeURIComponent(customerType) %>&q=<%= encodeURIComponent(q) %>&page_size=<%= pageSize %>&sort=<%= sort %>&dir=<%= dir %>&page=<%= page-1 %>">← Înapoi</a>
    <% } %>

    <span>Pagina <strong><%= page %></strong> / <%= totalPages %></span>

    <% if (page<totalPages) { %>
      <a class="btn" href="?store_id=<%= encodeURIComponent(storeId) %>&customer_type=<%= encodeURIComponent(customerType) %>&q=<%= encodeURIComponent(q) %>&page_size=<%= pageSize %>&sort=<%= sort %>&dir=<%= dir %>&page=<%= page+1 %>">Înainte →</a>
      <a class="btn" href="?store_id=<%= encodeURIComponent(storeId) %>&customer_type=<%= encodeURIComponent(customerType) %>&q=<%= encodeURIComponent(q) %>&page_size=<%= pageSize %>&sort=<%= sort %>&dir=<%= dir %>&page=<%= totalPages %>">Ultima »</a>
    <% } %>
  </div>
</div>

<%- include('../partials/footer') %>
