{% extends "base.html" %}

{% block title %}{{ _('Clients') }} - {{ app_name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    {% from "_components.html" import page_header %}
    <div class="row">
        <div class="col-12">
            {% set actions %}
            {% if current_user.is_admin %}
            <a href="{{ url_for('clients.create_client') }}" class="btn-header btn-primary">
                <i class="fas fa-plus me-2"></i>{{ _('New Client') }}
            </a>
            {% endif %}
            {% endset %}
            {{ page_header('fas fa-building', _('Clients'), _('Manage customers and contacts') ~ ' • ' ~ (clients|length) ~ ' ' ~ _('total'), actions) }}
        </div>
    </div>

    <!-- Client List -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm" style="border-radius: var(--border-radius);">
                <div class="card-header bg-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-list me-2"></i>{{ _('All Clients') }}
                        </h6>
                        <div class="d-flex gap-2">
                            <div class="input-group input-group-sm" style="width: 250px;">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="fas fa-search text-muted"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" id="searchInput" 
                                       placeholder="{{ _('Search clients...') }}">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    {% if clients %}
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="clientsTable">
                            <thead class="table-light">
                                <tr>
                                    <th>{{ _('Name') }}</th>
                                    <th>{{ _('Contact Person') }}</th>
                                    <th>{{ _('Email') }}</th>
                                    <th>{{ _('Phone') }}</th>
                                    <th>{{ _('Default Rate') }}</th>
                                    <th>{{ _('Projects') }}</th>
                                    <th>{{ _('Status') }}</th>
                                    <th>{{ _('Actions') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for client in clients %}
                                <tr class="client-row" data-status="{{ client.status }}">
                                    <td>
                                        <a href="{{ url_for('clients.view_client', client_id=client.id) }}" class="text-decoration-none">
                                            <strong>{{ client.name }}</strong>
                                        </a>
                                        {% if client.description %}
                                        <br><small class="text-muted">{{ client.description[:50] }}{% if client.description|length > 50 %}...{% endif %}</small>
                                        {% endif %}
                                    </td>
                                    <td>{{ client.contact_person or '-' }}</td>
                                    <td>
                                        {% if client.email %}
                                        <a href="mailto:{{ client.email }}">{{ client.email }}</a>
                                        {% else %}
                                        -
                                        {% endif %}
                                    </td>
                                    <td>{{ client.phone or '-' }}</td>
                                    <td>
                                        {% if client.default_hourly_rate %}
                                        {{ "%.2f"|format(client.default_hourly_rate) }} {{ currency }}
                                        {% else %}
                                        -
                                        {% endif %}
                                    </td>
                                    <td>
                                        <span class="badge badge-soft-primary badge-pill">{{ client.total_projects }}</span>
                                        {% if client.active_projects > 0 %}
                                        <br><small class="text-muted">{{ client.active_projects }} {{ _('active') }}</small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% set status_map = {
                                            'active':   {'bg': 'bg-success',   'label': _('Active')},
                                            'inactive': {'bg': 'bg-secondary', 'label': _('Inactive')}
                                        } %}
                                        {% set sc = status_map.get(client.status, status_map['inactive']) %}
                                        <span class="status-badge {{ sc.bg }} text-white">{{ sc.label }}</span>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="{{ url_for('clients.view_client', client_id=client.id) }}" 
                                               class="btn btn-sm btn-action btn-action--view" title="{{ _('View') }}">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            {% if current_user.is_admin %}
                                            <a href="{{ url_for('clients.edit_client', client_id=client.id) }}" 
                                               class="btn btn-sm btn-action btn-action--edit" title="{{ _('Edit') }}">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            {% if client.status == 'active' %}
                                            <button type="button" class="btn btn-sm btn-action btn-action--warning" title="{{ _('Archive') }}"
                                                    onclick="confirmArchiveClient('{{ client.id }}', '{{ client.name }}')">
                                                <i class="fas fa-archive"></i>
                                            </button>
                                            {% else %}
                                            <button type="button" class="btn btn-sm btn-action btn-action--success" title="{{ _('Activate') }}"
                                                    onclick="confirmActivateClient('{{ client.id }}', '{{ client.name }}')">
                                                <i class="fas fa-check"></i>
                                            </button>
                                            {% endif %}
                                            {% if client.total_projects == 0 %}
                                            <button type="button" class="btn btn-sm btn-action btn-action--danger" title="{{ _('Delete') }}"
                                                    onclick="confirmDeleteClient('{{ client.id }}', '{{ client.name }}')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="text-center py-5">
                        <i class="fas fa-building fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted">{{ _('No Clients Found') }}</h4>
                        <p class="text-muted">{{ _('Get started by creating your first client.') }}</p>
                        {% if current_user.is_admin %}
                        <a href="{{ url_for('clients.create_client') }}" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>{{ _('Create First Client') }}
                        </a>
                        {% endif %}
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modern styling now handled by global CSS in base.css -->

{% block extra_js %}
<script type="application/json" id="i18n-json-clients-list">
{
  "confirm_archive": {{ _('Are you sure you want to archive "{name}"?')|tojson }},
  "confirm_activate": {{ _('Are you sure you want to activate "{name}"?')|tojson }},
  "confirm_delete": {{ _('Are you sure you want to delete "{name}"? This action cannot be undone.')|tojson }}
}
</script>
<script>
var i18nClientsList = (function(){ try{ var el=document.getElementById('i18n-json-clients-list'); return el?JSON.parse(el.textContent):{}; }catch(e){ return {}; } })();
</script>
<script>
// Simple search (vanilla JS)
(function() {
  const searchInput = document.getElementById('searchInput');
  const table = document.getElementById('clientsTable');
  if (!table) return;
  const rows = Array.from(table.querySelectorAll('tbody tr'));

  function normalize(text) { return (text || '').toLowerCase(); }

  function matchesSearch(row, term) {
    if (!term) return true;
    const cellsText = Array.from(row.querySelectorAll('td')).map(td => td.innerText).join(' ');
    return normalize(cellsText).includes(term);
  }

  function applyFilters() {
    const term = normalize(searchInput ? searchInput.value : '');
    rows.forEach(row => {
      const show = matchesSearch(row, term);
      row.style.display = show ? '' : 'none';
    });
  }

  if (searchInput) {
    searchInput.addEventListener('input', applyFilters);
  }

  // Initial
  applyFilters();
})();

// Client action confirmation functions
function confirmArchiveClient(clientId, clientName) {
    const msg = (i18nClientsList.confirm_archive || 'Are you sure you want to archive "{name}"?').replace('{name}', clientName);
    if (confirm(msg)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/clients/${clientId}/archive`;
        document.body.appendChild(form);
        form.submit();
    }
}

function confirmActivateClient(clientId, clientName) {
    const msg = (i18nClientsList.confirm_activate || 'Are you sure you want to activate "{name}"?').replace('{name}', clientName);
    if (confirm(msg)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/clients/${clientId}/activate`;
        document.body.appendChild(form);
        form.submit();
    }
}

function confirmDeleteClient(clientId, clientName) {
    const msg = (i18nClientsList.confirm_delete || 'Are you sure you want to delete "{name}"? This action cannot be undone.').replace('{name}', clientName);
    if (confirm(msg)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/clients/${clientId}/delete`;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>
{% endblock %}
{% endblock %}
