{% extends "base.html" %}
{% from "components/ui.html" import confirm_dialog, page_header %}

{% block content %}
{% set actions %}
{% if current_user.is_admin or has_any_permission('edit_clients', 'delete_clients') or can_invoice_unbilled_time|default(false) %}
<div class="flex flex-wrap gap-2">
    {% if current_user.is_admin or has_permission('edit_clients') %}
    <a href="{{ url_for('clients.edit_client', client_id=client.id) }}" class="btn btn-primary">{{ _('Edit Client') }}</a>
    {% endif %}
    {% if can_invoice_unbilled_time|default(false) and unbilled_invoice_preview is defined and unbilled_invoice_preview %}
    {% set up = unbilled_invoice_preview %}
    {% set no_unbilled = (up.entry_count == 0) and (not up.blocked_reason) %}
    {% set blocked = up.blocked_reason == 'no_project' %}
    <button type="button" id="client-invoice-unbilled-btn"
            class="btn btn-primary {% if no_unbilled or blocked %}opacity-60 cursor-not-allowed{% endif %}"
            {% if no_unbilled or blocked %}disabled aria-disabled="true"{% endif %}
            data-api-url="{{ url_for('api_v1_clients.post_client_invoice_unbilled', client_id=client.id) }}"
            data-entries="{{ up.entry_count }}"
            data-hours="{{ '%.2f'|format(up.total_hours) }}"
            data-estimate="{{ '%.2f'|format(up.estimated_total) }}"
            data-currency="{{ up.currency }}"
            data-redirect-template="{{ url_for('invoices.view_invoice', invoice_id=client.id) }}"
            {% if blocked %}title="{{ _('Assign a project to direct time entries before invoicing.') }}"{% elif no_unbilled %}title="{{ _('No billable unbilled time for this client.') }}"{% endif %}>
        {% if no_unbilled %}{{ _('No unbilled time') }}{% else %}{{ _('Invoice unbilled time') }}{% endif %}
    </button>
    {% endif %}
    {% if current_user.is_admin or has_permission('edit_clients') %}
    {% if client.status == 'active' %}
    <form method="POST" action="{{ url_for('clients.archive_client', client_id=client.id) }}" onsubmit="event.preventDefault(); window.showConfirm('{{ _('Mark client as Inactive?')|e }}', { title: '{{ _('Change Client Status')|e }}', confirmText: '{{ _('Change')|e }}' }).then(ok=>{ if(ok) this.submit(); });" class="inline">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <button type="submit" class="px-4 py-2 rounded-lg bg-amber-500 text-white">{{ _('Mark Inactive') }}</button>
    </form>
    {% else %}
    <form method="POST" action="{{ url_for('clients.activate_client', client_id=client.id) }}" onsubmit="event.preventDefault(); window.showConfirm('{{ _('Activate client?')|e }}', { title: '{{ _('Activate Client')|e }}', confirmText: '{{ _('Activate')|e }}' }).then(ok=>{ if(ok) this.submit(); });" class="inline">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <button type="submit" class="px-4 py-2 rounded-lg bg-emerald-600 text-white">{{ _('Activate') }}</button>
    </form>
    {% endif %}
    {% endif %}
    {% if (current_user.is_admin or has_permission('delete_clients')) and client.total_projects == 0 %}
    <button type="button" class="btn btn-danger"
            onclick="document.getElementById('confirmDeleteClient-{{ client.id }}').classList.remove('hidden')">
        {{ _('Delete Client') }}
    </button>
    <form id="confirmDeleteClient-{{ client.id }}-form" method="POST" action="{{ url_for('clients.delete_client', client_id=client.id) }}" class="hidden">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    </form>
    {% endif %}
</div>
{% endif %}
{% endset %}
{{ page_header('fas fa-user', client.name, subtitle_text=_('Client details and associated projects.'), actions_html=actions, breadcrumbs=[{'text': _('Clients'), 'url': url_for('clients.list_clients')}, {'text': client.name}]) }}

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Left Column: Client Details -->
    <div class="lg:col-span-1 space-y-6">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-semibold">Contacts</h2>
                <a href="{{ url_for('contacts.list_contacts', client_id=client.id) }}" class="text-primary hover:underline text-sm">
                    {{ _('Manage') }} <i class="fas fa-arrow-right ml-1"></i>
                </a>
            </div>
            {% if contacts %}
            <div class="space-y-3">
                {% for contact in contacts[:3] %}
                <div class="border-l-4 border-primary pl-3 py-2">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="font-medium">{{ contact.full_name }}</p>
                            {% if contact.title %}
                            <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ contact.title }}</p>
                            {% endif %}
                            {% if contact.is_primary %}
                            <span class="text-xs px-2 py-0.5 bg-primary/10 text-primary rounded mt-1 inline-block">{{ _('Primary') }}</span>
                            {% endif %}
                        </div>
                    </div>
                    {% if contact.email %}
                    <a href="mailto:{{ contact.email }}" class="text-sm text-primary hover:underline mt-1 block">{{ contact.email }}</a>
                    {% endif %}
                </div>
                {% endfor %}
                {% if contacts|length > 3 %}
                <p class="text-sm text-text-muted-light dark:text-text-muted-dark text-center">
                    {{ contacts|length - 3 }} {{ _('more contact(s)') }}
                </p>
                {% endif %}
            </div>
            {% else %}
            <p class="text-text-muted-light dark:text-text-muted-dark text-sm mb-3">{{ _('No contacts yet') }}</p>
            <a href="{{ url_for('contacts.create_contact', client_id=client.id) }}" class="text-primary hover:underline text-sm">
                <i class="fas fa-plus mr-1"></i>{{ _('Add Contact') }}
            </a>
            {% endif %}
        </div>
        {% if client.contact_person or client.email or client.phone or client.address %}
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <h2 class="text-lg font-semibold mb-4">{{ _('Legacy Contact Info') }}</h2>
            <div class="space-y-4">
                {% if client.contact_person %}
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Contact Person</h3>
                    <p>{{ client.contact_person }}</p>
                </div>
                {% endif %}
                {% if client.email %}
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Email</h3>
                    <p>
                        <a href="mailto:{{ client.email }}" class="text-primary hover:underline">{{ client.email }}</a>
                    </p>
                </div>
                {% endif %}
                {% if client.phone %}
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Phone</h3>
                    <p>{{ client.phone }}</p>
                </div>
                {% endif %}
                {% if client.address %}
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Address</h3>
                    <p>{{ client.address }}</p>
                </div>
                {% endif %}
            </div>
        </div>
        {% endif %}
        {% if client.custom_fields %}
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <h2 class="text-lg font-semibold mb-4">{{ _('Custom Fields') }}</h2>
            <div class="space-y-3">
                {% for key, value in client.custom_fields.items() %}
                <div>
                    {% set field_defs = custom_field_definitions_by_key|default({}) %}
                    {% set field_definition = field_defs[key] if key in field_defs else None %}
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">
                        {% if field_definition %}{{ field_definition.label }}{% else %}{{ key }}{% endif %}
                    </h3>
                    <p class="text-text-light dark:text-text-dark">
                        {% set link_template = link_templates_by_field.get(key) if link_templates_by_field else None %}
                        {% if link_template and value %}
                            {# Render as clickable link using link template #}
                            {% set rendered_url = link_template.render_url(value) %}
                            {% if rendered_url %}
                                <a href="{{ rendered_url }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                                    {{ value }}
                                    <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                                </a>
                            {% else %}
                                {{ value }}
                            {% endif %}
                        {% elif value is string and (value.startswith('http://') or value.startswith('https://')) %}
                            {# Fallback: If the value looks like a URL, render it as a clickable link #}
                            <a href="{{ value }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                                {{ value }}
                            </a>
                        {% elif value is string and value.startswith('www.') %}
                            <a href="https://{{ value }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                                {{ value }}
                            </a>
                        {% else %}
                            {{ value }}
                        {% endif %}
                    </p>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}

        {% if prepaid_overview %}
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <h2 class="text-lg font-semibold mb-4">{{ _('Prepaid Hours') }}</h2>
            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3">
                {{ _('Plan includes %(hours)s hours per cycle. Resets on day %(day)s.', hours='%.2f'|format(prepaid_overview.plan_hours), day=client.prepaid_reset_day) }}
            </p>
            <ul class="space-y-2 text-sm text-text-light dark:text-text-dark">
                <li>
                    <span class="font-medium">{{ _('Current cycle start') }}:</span>
                    <span>{{ prepaid_overview.month_label }}</span>
                </li>
                <li>
                    <span class="font-medium text-emerald-600">{{ _('Remaining hours') }}:</span>
                    <span>{{ '%.2f'|format(prepaid_overview.remaining_hours) }} {{ _('h') }}</span>
                </li>
                <li>
                    <span class="font-medium text-amber-600">{{ _('Consumed this cycle') }}:</span>
                    <span>{{ '%.2f'|format(prepaid_overview.consumed_hours) }} {{ _('h') }}</span>
                </li>
            </ul>
        </div>
        {% endif %}

        <!-- Attachments Section -->
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-semibold">
                    <i class="fas fa-paperclip mr-2"></i>{{ _('Attachments') }}
                    {% if attachments %}
                    <span class="text-sm font-normal text-gray-500 dark:text-gray-400">({{ attachments|length }})</span>
                    {% endif %}
                </h2>
                {% if current_user.is_admin or has_permission('edit_clients') %}
                <button type="button" onclick="document.getElementById('upload-attachment-form').classList.toggle('hidden')" class="btn btn-primary btn-sm">
                    <i class="fas fa-plus mr-1"></i>{{ _('Upload') }}
                </button>
                {% endif %}
            </div>

            <!-- Upload Form -->
            {% if current_user.is_admin or has_permission('edit_clients') %}
            <div id="upload-attachment-form" class="hidden mb-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                <form method="POST" action="{{ url_for('clients.upload_client_attachment', client_id=client.id) }}" enctype="multipart/form-data" class="space-y-3">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <div>
                        <label for="attachment-file" class="form-label">{{ _('File') }}</label>
                        <input type="file" name="file" id="attachment-file" class="w-full form-input" required>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ _('Max size: 10 MB. Allowed: images, PDFs, documents, spreadsheets, archives') }}</p>
                    </div>
                    <div>
                        <label for="attachment-description" class="form-label">{{ _('Description (optional)') }}</label>
                        <input type="text" name="description" id="attachment-description" class="w-full form-input" placeholder="{{ _('e.g., Contract, Agreement, etc.') }}">
                    </div>
                    <div class="flex items-center">
                        <label class="flex items-center">
                            <input type="checkbox" name="is_visible_to_client" value="true" class="mr-2">
                            <span class="text-sm text-gray-700 dark:text-gray-300">{{ _('Visible to client in portal') }}</span>
                        </label>
                    </div>
                    <div class="flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-upload mr-1"></i>{{ _('Upload') }}
                        </button>
                        <button type="button" onclick="document.getElementById('upload-attachment-form').classList.add('hidden')" class="btn btn-secondary">
                            {{ _('Cancel') }}
                        </button>
                    </div>
                </form>
            </div>
            {% endif %}

            <!-- Attachments List -->
            <div class="space-y-2">
                {% if attachments %}
                    {% for attachment in attachments %}
                    <div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                        <div class="flex items-center gap-3 flex-1 min-w-0">
                            <div class="flex-shrink-0">
                                {% if attachment.is_pdf %}
                                <i class="fas fa-file-pdf text-red-500 text-xl"></i>
                                {% elif attachment.is_image %}
                                <i class="fas fa-file-image text-blue-500 text-xl"></i>
                                {% elif attachment.is_document %}
                                <i class="fas fa-file-word text-blue-600 text-xl"></i>
                                {% else %}
                                <i class="fas fa-file text-gray-500 text-xl"></i>
                                {% endif %}
                            </div>
                            <div class="flex-1 min-w-0">
                                <a href="{{ url_for('clients.download_client_attachment', attachment_id=attachment.id) }}" class="text-primary hover:underline font-medium block truncate" title="{{ attachment.original_filename }}">
                                    {{ attachment.original_filename }}
                                </a>
                                {% if attachment.description %}
                                <p class="text-xs text-gray-500 dark:text-gray-400 truncate">{{ attachment.description }}</p>
                                {% endif %}
                                <p class="text-xs text-gray-500 dark:text-gray-400">
                                    {{ attachment.file_size_display }} • {{ attachment.uploaded_at|user_datetime if attachment.uploaded_at else '' }}
                                    {% if attachment.is_visible_to_client %}
                                    <span class="ml-2 px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded text-xs">{{ _('Client Visible') }}</span>
                                    {% endif %}
                                </p>
                            </div>
                        </div>
                        {% if current_user.is_admin or has_permission('edit_clients') %}
                        <form method="POST" action="{{ url_for('clients.delete_client_attachment', attachment_id=attachment.id) }}" class="ml-2" onsubmit="event.preventDefault(); window.showConfirm('{{ _('Are you sure you want to delete this attachment?') }}', { title: '{{ _('Delete Attachment') }}', confirmText: '{{ _('Delete') }}', variant: 'danger' }).then(ok=>{ if(ok) this.submit(); });">
                            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                            <button type="submit" class="text-red-500 hover:text-red-700 p-1" title="{{ _('Delete') }}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                        {% endif %}
                    </div>
                    {% endfor %}
                {% else %}
                <p class="text-sm text-gray-500 dark:text-gray-400 text-center py-4">{{ _('No attachments yet') }}</p>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Right Column: Projects -->
    <div class="lg:col-span-2">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <h2 class="text-lg font-semibold mb-4">Projects</h2>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="border-b border-border-light dark:border-border-dark">
                        <tr>
                            <th class="p-4">Name</th>
                            <th class="p-4">Status</th>
                            <th class="p-4">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for project in projects %}
                        <tr class="border-b border-border-light dark:border-border-dark">
                            <td class="p-4">
                                <div class="flex items-center gap-2">
                                    <a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-primary hover:underline">{{ project.name }}</a>
                                    {% if project.code_display %}
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-semibold tracking-wide uppercase bg-gray-200 text-gray-800 dark:bg-gray-700 dark:text-gray-200">{{ project.code_display }}</span>
                                    {% endif %}
                                </div>
                            </td>
                            <td class="p-4">
                                {% set status_map = {
                                    'active':   {'cls': 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300', 'label': _('Active')},
                                    'inactive': {'cls': 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300', 'label': _('Inactive')},
                                    'archived': {'cls': 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200', 'label': _('Archived')},
                                } %}
                                {% set st = status_map.get(project.status, status_map['inactive']) %}
                                <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap {{ st.cls }}">{{ st.label }}</span>
                            </td>
                            <td class="p-4">
                                <a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-primary hover:underline">View</a>
                            </td>
                        </tr>
                        {% else %}
                        <tr>
                            <td colspan="3" class="p-4 text-center text-text-muted-light dark:text-text-muted-dark">No projects found for this client.</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Recent Hours History -->
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mt-6">
            <h2 class="text-lg font-semibold mb-4">{{ _('Recent Hours History') }}</h2>
            {% if recent_time_entries %}
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="border-b border-border-light dark:border-border-dark">
                        <tr>
                            <th class="p-3 text-sm font-medium text-text-muted-light dark:text-text-muted-dark">{{ _('Date') }}</th>
                            <th class="p-3 text-sm font-medium text-text-muted-light dark:text-text-muted-dark">{{ _('Project') }}</th>
                            <th class="p-3 text-sm font-medium text-text-muted-light dark:text-text-muted-dark">{{ _('Task') }}</th>
                            <th class="p-3 text-sm font-medium text-text-muted-light dark:text-text-muted-dark">{{ _('User') }}</th>
                            <th class="p-3 text-sm font-medium text-text-muted-light dark:text-text-muted-dark">{{ _('Duration') }}</th>
                            <th class="p-3 text-sm font-medium text-text-muted-light dark:text-text-muted-dark">{{ _('Notes') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for entry in recent_time_entries %}
                        <tr class="border-b border-border-light dark:border-border-dark hover:bg-background-light dark:hover:bg-background-dark cursor-pointer" onclick="window.location.href='{{ url_for('timer.view_timer', timer_id=entry.id) }}'">
                            <td class="p-3">
                                <div class="text-sm">
                                    {{ entry.start_time|user_date }}
                                </div>
                                <div class="text-xs text-text-muted-light dark:text-text-muted-dark">
                                    {{ entry.start_time|user_time }}
                                    {% if entry.end_time %}
                                        - {{ entry.end_time|user_time }}
                                    {% endif %}
                                </div>
                            </td>
                            <td class="p-3">
                                {% if entry.project %}
                                    <a href="{{ url_for('projects.view_project', project_id=entry.project.id) }}" class="text-primary hover:underline text-sm">
                                        {{ entry.project.name }}
                                    </a>
                                {% else %}
                                    <span class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('Direct') }}</span>
                                {% endif %}
                            </td>
                            <td class="p-3">
                                {% if entry.task %}
                                    <span class="text-sm">{{ entry.task.name }}</span>
                                {% else %}
                                    <span class="text-sm text-text-muted-light dark:text-text-muted-dark">-</span>
                                {% endif %}
                            </td>
                            <td class="p-3">
                                <span class="text-sm">{{ entry.user.display_name if entry.user else _('N/A') }}</span>
                            </td>
                            <td class="p-3">
                                <span class="font-medium text-sm">{{ "%.2f"|format(entry.duration_hours) }}h</span>
                            </td>
                            <td class="p-3">
                                {% if entry.notes %}
                                    <span class="text-sm" title="{{ entry.notes|striptags }}">
                                        {{ entry.notes|striptags|truncate(50) }}
                                    </span>
                                {% else %}
                                    <span class="text-sm text-text-muted-light dark:text-text-muted-dark">-</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                <div class="mt-4 pt-4 border-t border-border-light dark:border-border-dark">
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">
                        {{ _('Showing last %(count)s entries', count=recent_time_entries|length) }} | 
                        {{ _('Total hours') }}: {{ "%.2f"|format(recent_time_entries|sum(attribute='duration_hours')) }}h
                    </p>
                </div>
            </div>
            {% else %}
            <p class="text-text-muted-light dark:text-text-muted-dark text-center py-8">{{ _('No recent time entries found.') }}</p>
            {% endif %}
        </div>
    </div>
</div>

<!-- Client Notes Section -->
<div class="mt-6">
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">{{ _('Internal Notes') }}</h2>
            <button type="button" id="addNoteBtn" class="btn btn-primary">
                {{ _('Add Note') }}
            </button>
        </div>
        
        <!-- Add Note Form (Hidden by default) -->
        <div id="addNoteForm" class="hidden mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-border-light dark:border-border-dark">
            <form method="POST" action="{{ url_for('client_notes.create_note', client_id=client.id) }}">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <div class="mb-4">
                    <label for="note-content" class="block text-sm font-medium mb-2">{{ _('Note Content') }}</label>
                    <textarea 
                        name="content" 
                        id="note-content" 
                        class="w-full px-3 py-2 border border-border-light dark:border-border-dark rounded-lg bg-background-light dark:bg-background-dark focus:ring-2 focus:ring-primary focus:border-transparent" 
                        rows="4" 
                        required
                        placeholder="{{ _('Add an internal note about this client...') }}"
                    ></textarea>
                </div>
                <div class="mb-4">
                    <label class="flex items-center">
                        <input 
                            type="checkbox" 
                            name="is_important" 
                            value="true" 
                            class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary focus:ring-2"
                        >
                        <span class="ml-2 text-sm">{{ _('Mark as important') }}</span>
                    </label>
                </div>
                <div class="flex gap-2">
                    <button type="submit" class="btn btn-primary">
                        {{ _('Save Note') }}
                    </button>
                    <button type="button" id="cancelNoteBtn" class="btn btn-secondary">
                        {{ _('Cancel') }}
                    </button>
                </div>
            </form>
        </div>
        
        <!-- Notes List -->
        <div id="notesList" class="space-y-4">
            {% if client.notes %}
                {% for note in client.notes|sort(attribute='created_at', reverse=True) %}
                <div class="p-4 bg-background-light dark:bg-background-dark rounded-lg border border-border-light dark:border-border-dark {% if note.is_important %}border-l-4 border-l-amber-500{% endif %}">
                    <div class="flex justify-between items-start mb-2">
                        <div class="flex items-center gap-2">
                            <div class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center text-sm font-semibold">
                                {{ (note.author_name)[0].upper() }}
                            </div>
                            <div>
                                <div class="font-medium">{{ note.author_name }}</div>
                                <div class="text-xs text-text-muted-light dark:text-text-muted-dark">
                                    {{ note.created_at|user_datetime }}
                                    {% if note.created_at != note.updated_at %}
                                    <span class="ml-1">({{ _('edited') }})</span>
                                    {% endif %}
                                </div>
                            </div>
                            {% if note.is_important %}
                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300">
                                <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                                </svg>
                                {{ _('Important') }}
                            </span>
                            {% endif %}
                        </div>
                        {% if note.can_edit(current_user) %}
                        <div class="flex gap-2">
                            <button type="button" 
                                    class="text-sm text-blue-600 dark:text-blue-400 hover:underline"
                                    onclick="toggleImportant({{ note.id }}, {{ 'true' if not note.is_important else 'false' }})">
                                {% if note.is_important %}{{ _('Unmark') }}{% else %}{{ _('Mark Important') }}{% endif %}
                            </button>
                            <a href="{{ url_for('client_notes.edit_note', client_id=client.id, note_id=note.id) }}" 
                               class="text-sm text-primary hover:underline">
                                {{ _('Edit') }}
                            </a>
                            {% if note.can_delete(current_user) %}
                            <form id="deleteNoteForm-{{ note.id }}" method="POST" 
                                  action="{{ url_for('client_notes.delete_note', client_id=client.id, note_id=note.id) }}" 
                                  class="inline">
                                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                <button type="button" onclick="confirmDeleteNote({{ note.id }})" class="text-sm text-red-600 dark:text-red-400 hover:underline">
                                    {{ _('Delete') }}
                                </button>
                            </form>
                            {% endif %}
                        </div>
                        {% endif %}
                    </div>
                    <div class="text-sm whitespace-pre-wrap">{{ note.content }}</div>
                </div>
                {% endfor %}
            {% else %}
            <div class="text-center py-8 text-text-muted-light dark:text-text-muted-dark">
                <svg class="w-12 h-12 mx-auto mb-2 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                </svg>
                <p>{{ _('No notes yet. Add a note to keep track of important information about this client.') }}</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const addNoteBtn = document.getElementById('addNoteBtn');
    const addNoteForm = document.getElementById('addNoteForm');
    const cancelNoteBtn = document.getElementById('cancelNoteBtn');
    const noteContent = document.getElementById('note-content');
    
    addNoteBtn.addEventListener('click', function() {
        addNoteForm.classList.remove('hidden');
        noteContent.focus();
    });
    
    cancelNoteBtn.addEventListener('click', function() {
        addNoteForm.classList.add('hidden');
        noteContent.value = '';
    });
});

function toggleImportant(noteId, setImportant) {
    fetch(`{{ url_for('client_notes.toggle_important', client_id=client.id, note_id=0) }}`.replace('/0/', `/${noteId}/`), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('{{ _('Error updating note') }}');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{{ _('Error updating note') }}');
    });
}

{% if can_invoice_unbilled_time|default(false) and unbilled_invoice_preview is defined and unbilled_invoice_preview %}
(function () {
  const btn = document.getElementById('client-invoice-unbilled-btn');
  if (!btn || btn.disabled) return;
  btn.addEventListener('click', async function () {
    const entries = btn.dataset.entries;
    const hours = btn.dataset.hours;
    const est = btn.dataset.estimate;
    const cur = btn.dataset.currency;
    const tpl = btn.dataset.redirectTemplate;
    const msg =
      '{{ _("Entries") }}: ' +
      entries +
      ', {{ _("Total hours") }}: ' +
      hours +
      ' h, {{ _("Estimated total") }}: ' +
      cur +
      ' ' +
      est +
      '. {{ _("Create a draft invoice?") }}';
    const ok = await window.showConfirm(msg, {
      title: '{{ _("Invoice unbilled time") }}',
      confirmText: '{{ _("Create invoice") }}',
      cancelText: '{{ _("Cancel") }}',
      variant: 'primary',
    });
    if (!ok) return;
    btn.disabled = true;
    try {
      const r = await fetch(btn.dataset.apiUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
      });
      let data = {};
      try {
        data = await r.json();
      } catch (_) {}
      if (!r.ok) {
        btn.disabled = false;
        window.showAlert((data && data.message) || '{{ _("Could not create invoice.") }}');
        return;
      }
      window.location.href = tpl.replace(/[^/]+$/, String(data.invoice_id));
    } catch (e) {
      btn.disabled = false;
      window.showAlert('{{ _("Could not create invoice.") }}');
    }
  });
})();
{% endif %}

async function confirmDeleteNote(noteId) {
    const confirmed = await showConfirm(
        '{{ _("Are you sure you want to delete this note?") }}',
        {
            title: '{{ _("Delete Note") }}',
            confirmText: '{{ _("Delete") }}',
            cancelText: '{{ _("Cancel") }}',
            variant: 'danger'
        }
    );
    if (confirmed) {
        document.getElementById('deleteNoteForm-' + noteId).submit();
    }
}
</script>

{% if current_user.is_admin or has_permission('delete_clients') %}
{{ confirm_dialog(
    'confirmDeleteClient-' ~ client.id,
    'Delete Client',
    'Are you sure you want to delete this client? This action cannot be undone.',
    'Delete',
    'Cancel',
    'danger'
) }}
{% endif %}
{% endblock %}
