<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/TenantClient.php';
require_once __DIR__ . '/../src/ActivityLog.php';

// Check permission
requirePermission('clients_view');

// Get action-specific permissions for UI display
$canCreateClient = hasPermission('clients_create');
$canEditClient = hasPermission('clients_edit');
$canDeleteClient = hasPermission('clients_delete');

// Check plan limits for creating clients
$canAddMoreClients = canAddWithinLimits('clients');
$remainingClients = getRemainingLimit('clients');

// UI theme (dark by default, for compatibility with app shell)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

function getClientDependencyMessage(int $clientId, ?int $companyId): ?string {
    if (!$companyId) {
        $companyId = TenantDB::getTenant();
    }

    if (!$companyId) {
        return null;
    }

    $pdo = getPDO();
    $dependencyMap = [
        'proposals' => 'proposal(s)',
        'invoices' => 'invoice(s)',
        'contracts' => 'contract(s)'
    ];

    $messages = [];
    foreach ($dependencyMap as $table => $label) {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM {$table} WHERE client_id = ? AND company_id = ?");
        $stmt->execute([$clientId, $companyId]);
        $count = (int) ($stmt->fetch()['count'] ?? 0);
        if ($count > 0) {
            $messages[] = "$count $label";
        }
    }

    if (!$messages) {
        return null;
    }

    $list = implode(', ', $messages);
    return 'Client cannot be deleted because they are referenced by ' . $list . '. Remove those dependencies first.';
}

$errors = [];
$successMessage = $_GET['success'] ?? null;

$defaults = [
    'name' => '',
    'company' => '',
    'email' => '',
    'phone' => '',
    'address' => '',
    'notes' => '',
    'display_name_option' => 'client_name',
    'custom_display_name' => '',
];

$formDataCreate = $defaults;
$formDataEdit = $defaults;
$editingClient = null;

$activeWorkspaceName = $company['name'] ?? null;
if (!$activeWorkspaceName && $workspaceParam) {
    $activeWorkspaceName = ucwords(str_replace(['-', '_'], ' ', $workspaceParam));
}
$activeWorkspaceName = $activeWorkspaceName ?: 'Your workspace';

$workspaceSlug = $workspaceParam
    ?: ($company['username'] ?? ($company['id'] ?? null));
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';

$canAccessClientForm = ($canCreateClient && !$editingClient) || ($canEditClient && $editingClient);
$formPanelShouldStartOpen = $editingClient !== null || ($_GET['action'] ?? '') === 'create';

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    if ($editId > 0) {
        try {
            // Get current workspace company ID
            $currentCompanyId = null;
            if ($workspaceParam) {
                $pdo = getPDO();
                $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
                $stmt->execute([$workspaceParam]);
                $company = $stmt->fetch();
                $currentCompanyId = $company['id'] ?? null;
            }
            
            // Fallback to tenant context if workspace param fails
            if (!$currentCompanyId) {
                $currentCompanyId = TenantDB::getTenant();
            }
            
            error_log("DEBUG: Edit client - using company ID: $currentCompanyId for workspace: " . ($workspaceParam ?? 'none'));
            
            // Use direct query to get client from current workspace
            $pdo = getPDO();
            $stmt = $pdo->prepare("SELECT * FROM clients WHERE id = ? AND company_id = ?");
            $stmt->execute([$editId, $currentCompanyId]);
            $editingClient = $stmt->fetch();
            
            if ($editingClient) {
                $formDataEdit = array_merge($formDataEdit, $editingClient);
                error_log("DEBUG: Edit client found: " . json_encode($editingClient));
            } else {
                error_log("DEBUG: Edit client not found - ID: $editId, Company ID: $currentCompanyId");
                $errors[] = 'Client not found or you do not have access to this client.';
            }
        } catch (Exception $e) {
            error_log("DEBUG: Edit client error: " . $e->getMessage());
            $errors[] = 'Error loading client: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    $payload = [
        'name' => sanitizeText($_POST['name'] ?? ''),
        'company' => sanitizeText($_POST['company'] ?? ''),
        'email' => sanitizeEmail($_POST['email'] ?? null),
        'phone' => sanitizeText($_POST['phone'] ?? ''),
        'address' => sanitizeText($_POST['address'] ?? ''),
        'notes' => sanitizeText($_POST['notes'] ?? ''),
        'display_name_option' => sanitizeText($_POST['display_name_option'] ?? 'client_name'),
        'custom_display_name' => sanitizeText($_POST['custom_display_name'] ?? ''),
    ];

    if ($payload['name'] === '') {
        $errors[] = 'Client name is required.';
    }

    $payload['company'] = $payload['company'] !== '' ? $payload['company'] : null;
    $payload['phone'] = $payload['phone'] !== '' ? $payload['phone'] : null;
    $payload['address'] = $payload['address'] !== '' ? $payload['address'] : null;
    $payload['notes'] = $payload['notes'] !== '' ? $payload['notes'] : null;

    if ($action === 'create') {
        // Check permission
        if (!$canCreateClient) {
            $errors[] = 'You do not have permission to create clients.';
        }
        // Check plan limits
        if ($canCreateClient && !$canAddMoreClients) {
            $errors[] = 'You have reached your plan limit for clients. Please upgrade your plan to add more clients.';
        }
        
        $formDataCreate = array_merge($formDataCreate, $_POST);
        if (!$errors) {
            try {
                $newClientId = TenantClient::create($payload);

                // Log client creation in workspace activity
                try {
                    if (!empty($companyId)) {
                        $actorId = isset($user['id']) ? (int) $user['id'] : null;
                        ActivityLog::log(
                            (int) $companyId,
                            $actorId,
                            'client_created',
                            'client',
                            (int) $newClientId,
                            $payload['name'] ?? null,
                            null,
                            [
                                'email' => $payload['email'] ?? null,
                                'company' => $payload['company'] ?? null,
                            ]
                        );
                    }
                } catch (Throwable $e) {
                    // Ignore logging failures
                }
                $redirectUrl = '/clients.php';
                if ($workspaceParam) {
                    $redirectUrl .= '?workspace=' . urlencode($workspaceParam);
                }
                redirect($redirectUrl, ['success' => 'Client created successfully.']);
            } catch (Exception $e) {
                $errors[] = 'Error creating client: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'update') {
        // Check permission
        if (!$canEditClient) {
            $errors[] = 'You do not have permission to edit clients.';
        }
        
        $clientId = isset($_POST['id']) ? (int) $_POST['id'] : 0;
        if ($clientId <= 0) {
            $errors[] = 'Invalid client selected for update.';
        }

        $formDataEdit = array_merge($formDataEdit, $_POST);

        if (!$errors && $clientId > 0) {
            try {
                // Load existing client for logging
                $existingClient = TenantClient::getById($clientId);

                TenantClient::update($clientId, $payload);

                // Log client update
                try {
                    if (!empty($companyId)) {
                        $actorId = isset($user['id']) ? (int) $user['id'] : null;
                        ActivityLog::log(
                            (int) $companyId,
                            $actorId,
                            'client_updated',
                            'client',
                            (int) $clientId,
                            $payload['name'] ?: ($existingClient['name'] ?? null),
                            $existingClient ? [
                                'name' => $existingClient['name'] ?? null,
                                'company' => $existingClient['company'] ?? null,
                                'email' => $existingClient['email'] ?? null,
                                'phone' => $existingClient['phone'] ?? null,
                            ] : null,
                            [
                                'name' => $payload['name'] ?? null,
                                'company' => $payload['company'] ?? null,
                                'email' => $payload['email'] ?? null,
                                'phone' => $payload['phone'] ?? null,
                            ]
                        );
                    }
                } catch (Throwable $e) {
                    // Ignore logging failures
                }
                $redirectUrl = '/clients.php';
                if ($workspaceParam) {
                    $redirectUrl .= '?workspace=' . urlencode($workspaceParam);
                }
                redirect($redirectUrl, ['success' => 'Client updated successfully.']);
            } catch (Exception $e) {
                $errors[] = 'Error updating client: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'delete') {
        // Check permission
        if (!$canDeleteClient) {
            $errors[] = 'You do not have permission to delete clients.';
        } else {
            $clientId = isset($_POST['id']) ? (int) $_POST['id'] : 0;
            if ($clientId > 0) {
                $companyContextId = $companyId ?? TenantDB::getTenant();
                $dependencyMessage = getClientDependencyMessage($clientId, $companyContextId);

                if ($dependencyMessage) {
                    $errors[] = $dependencyMessage;
                } else {
                    try {
                        // Load existing client for logging before deletion
                        $existingClient = TenantClient::getById($clientId);

                        $deleted = TenantClient::delete($clientId);
                        if (!$deleted) {
                            $errors[] = 'Client could not be deleted. Please try again.';
                        } else {
                            // Log client deletion
                            try {
                                if (!empty($companyId)) {
                                    $actorId = isset($user['id']) ? (int) $user['id'] : null;
                                    ActivityLog::log(
                                        (int) $companyId,
                                        $actorId,
                                        'client_deleted',
                                        'client',
                                        (int) $clientId,
                                        $existingClient['name'] ?? null,
                                        $existingClient ? [
                                            'company' => $existingClient['company'] ?? null,
                                            'email' => $existingClient['email'] ?? null,
                                        ] : null,
                                        null
                                    );
                                }
                            } catch (Throwable $e) {
                                // Ignore logging failures
                            }
                            $redirectUrl = '/clients.php';
                            if ($workspaceParam) {
                                $redirectUrl .= '?workspace=' . urlencode($workspaceParam);
                            }
                            redirect($redirectUrl, ['success' => 'Client removed.']);
                        }
                    } catch (Exception $e) {
                        $errors[] = 'Error deleting client: ' . $e->getMessage();
                    }
                }
            } else {
                $errors[] = 'Invalid client selected for deletion.';
            }
        }
    }
}

$search = $_GET['search'] ?? '';

// Debug: Check tenant context
$tenantId = TenantDB::getTenant();
error_log("DEBUG: Tenant ID in clients.php: " . ($tenantId ?: 'NULL'));

// Fallback: If tenant context is not set, try to set it manually
if (!$tenantId && isset($companyId)) {
    TenantDB::setTenant($companyId);
    $tenantId = TenantDB::getTenant();
    error_log("DEBUG: Manually set tenant ID to: $tenantId");
}

// Final fallback: Try to get company from workspace parameter
if (!$tenantId && $workspaceParam) {
    $pdo = getPDO();
    $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
    $stmt->execute([$workspaceParam]);
    $company = $stmt->fetch();
    if ($company) {
        TenantDB::setTenant($company['id']);
        $tenantId = TenantDB::getTenant();
        error_log("DEBUG: Set tenant ID from workspace parameter: $tenantId");
    }
}

try {
    // Use direct query with proper workspace filtering
    $pdo = getPDO();
    
    // Get current workspace company ID from URL parameter
    $currentCompanyId = null;
    if ($workspaceParam) {
        $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
        $stmt->execute([$workspaceParam]);
        $company = $stmt->fetch();
        $currentCompanyId = $company['id'] ?? null;
    }
    
    // Fallback to tenant context if workspace param fails
    if (!$currentCompanyId) {
        $currentCompanyId = $tenantId;
    }
    
    error_log("DEBUG: Using company ID: $currentCompanyId for workspace: " . ($workspaceParam ?? 'none'));
    
    $directQuery = "SELECT * FROM clients WHERE company_id = ? ORDER BY created_at DESC";
    $stmt = $pdo->prepare($directQuery);
    $stmt->execute([$currentCompanyId]);
    $clients = $stmt->fetchAll();
    
    error_log("DEBUG: Using direct query, found " . count($clients) . " clients");
    
    // Also test TenantDB for comparison
    $tenantClients = TenantClient::getAll();
    error_log("DEBUG: TenantClient::getAll() returned " . count($tenantClients) . " clients");
    
} catch (Exception $e) {
    error_log("DEBUG: Direct query error: " . $e->getMessage());
    $errors[] = 'Error loading clients: ' . $e->getMessage();
    $clients = [];
}

// Debug: Show client data
if (!empty($clients)) {
    error_log("DEBUG: First client data: " . json_encode($clients[0]));
} else {
    error_log("DEBUG: No clients found");
}

// Add visible debug info
echo "<!-- DEBUG INFO -->\n";
echo "<!-- Tenant ID: " . ($tenantId ?: 'NULL') . " -->\n";
echo "<!-- Current company ID: " . ($currentCompanyId ?? 'NULL') . " -->\n";
echo "<!-- Client count (direct query): " . count($clients) . " -->\n";
echo "<!-- TenantDB count: " . (isset($tenantClients) ? count($tenantClients) : 'N/A') . " -->\n";
echo "<!-- Workspace param: " . ($workspaceParam ?? 'none') . " -->\n";
echo "<!-- Company ID from secure_workspace: " . ($companyId ?? 'NULL') . " -->\n";
if (!empty($clients)) {
    echo "<!-- First client: " . json_encode($clients[0]) . " -->\n";
}
echo "<!-- END DEBUG -->\n";

// Client filtering is now handled client-side for instant feedback. Server keeps full dataset for graceful degradation.
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clients · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
    <?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Clients', $currentTheme); ?>

    <div class="main-container">
        <?php
        require_once __DIR__ . '/components/headers/page-header.php';
        
        $actions = [];
        if ($canCreateClient && $canAddMoreClients) {
            $actions[] = ['label' => 'New Client', 'id' => 'header-new-client-btn', 'type' => 'primary', 'icon' => 'M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z'];
        }
        
        renderPageHeader(
            breadcrumbs: [
                ['label' => htmlspecialchars($activeWorkspaceName), 'url' => '/index.php', 'icon' => 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2z']
            ],
            currentPage: 'Clients',
            actions: $actions,
            workspaceQuery: $workspaceQuery
        );
        ?>

        <div class="dash-container">
            <!-- Success/Error Messages -->
            <?php if ($successMessage): ?>
                <div class="status-banner success" style="margin-bottom: 16px;">
                    <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                    </svg>
                    <span><?= h($successMessage) ?></span>
                </div>
            <?php endif; ?>

            <?php if ($errors): ?>
                <div class="status-banner error" style="margin-bottom: 16px;">
                    <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                    </svg>
                    <div>
                        <span style="font-weight: 500; font-size: 12px;">Please fix the following errors:</span>
                        <ul style="list-style: disc; list-style-position: inside; margin-top: 4px; font-size: 11px;">
                            <?php foreach ($errors as $error): ?>
                                <li><?= h($error) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            <?php endif; ?>

            <div class="dash-section">
                <div class="card">
                    <div style="display: flex; flex-direction: column; gap: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                        <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
                            <div>
                                <p class="section-title">Directory</p>
                                <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">Clients</h2>
                                <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;"><span data-client-count><?= count($clients) ?></span> total clients</p>
                            </div>
                            <div class="view-toggle" data-view-toggle>
                                <button type="button" class="active" data-view="grid" title="Grid view">
                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"></path>
                                    </svg>
                                </button>
                                <button type="button" data-view="list" title="List view">
                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <div style="display: flex; flex-direction: column; gap: 8px;">
                            <div style="display: flex; gap: 8px; align-items: stretch;">
                                <form method="GET" style="display: flex; gap: 8px; flex: 1;" id="client-search-form">
                                    <div class="input-with-icon" style="flex: 1;">
                                        <input type="text" id="client-search-input" name="search" value="<?= h($search) ?>" placeholder="Search clients" class="input">
                                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                        </svg>
                                        <?php if ($search !== ''): ?>
                                            <a href="/clients.php<?= $workspaceQuery ?>" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: var(--text-tertiary); text-decoration: none; z-index: 1;">
                                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                                </svg>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                    <button type="submit" class="btn-search">Search</button>
                                </form>
                                <?php if ($canAccessClientForm): ?>
                                    <button id="client-form-toggle" type="button" class="btn-secondary">
                                        <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                        </svg>
                                        <span>Add client</span>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <?php if ($canAccessClientForm): ?>
                        <div
                            id="client-form-panel"
                            style="overflow: hidden; transition: height 0.3s ease-out; border-top: 1px solid var(--border-subtle); height: <?= $formPanelShouldStartOpen ? 'auto' : '0px' ?>;"
                            data-form-panel
                            data-open="<?= $formPanelShouldStartOpen ? 'true' : 'false' ?>"
                        >
                            <div style="padding: 16px; display: flex; flex-direction: column; gap: 12px;" data-form-panel-body>
                                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
                                    <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;" data-form-title><?= $editingClient ? 'Edit Client' : 'Add Client' ?></h3>
                                    <button id="client-form-toggle" type="button" class="btn-secondary" style="padding: 4px 8px;">
                                        <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                        </svg>
                                    </button>
                                </div>
                                <?php if (!$canAddMoreClients && !$editingClient): ?>
                                    <div class="status-banner error" style="margin-bottom: 16px;" data-limit-banner>
                                        <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                                        </svg>
                                        <div>
                                            <span style="font-weight: 500; font-size: 12px;">Client limit reached</span>
                                            <p style="font-size: 11px; margin-top: 4px;">Upgrade your plan to add more clients.</p>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <form
                                    method="POST"
                                    style="display: flex; flex-direction: column; gap: 16px;"
                                    data-client-form
                                    data-defaults='<?= htmlspecialchars(json_encode($formDataCreate, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP), ENT_QUOTES, 'UTF-8') ?>'
                                    data-initial-client='<?= $editingClient ? htmlspecialchars(json_encode($formDataEdit, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP), ENT_QUOTES, 'UTF-8') : '' ?>'
                                    data-initial-mode="<?= $editingClient ? 'edit' : 'create' ?>"
                                    data-create-disabled="<?= $canAddMoreClients ? 'false' : 'true' ?>"
                                    data-create-disabled-message="<?= !$canAddMoreClients ? 'Client limit reached. Upgrade your plan to add more clients.' : '' ?>"
                                    data-create-subtitle="<?= htmlspecialchars($remainingClients !== -1 ? $remainingClients . ' slots remaining' : '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-edit-subtitle="Editing existing client"
                                    data-create-title="Add Client"
                                    data-edit-title="Edit Client"
                                >
                                    <input type="hidden" name="action" id="client-form-action" value="<?= $editingClient ? 'update' : 'create' ?>">
                                    <input type="hidden" name="id" id="client-form-id" value="<?= $editingClient ? (int) $editingClient['id'] : '' ?>">

                                    <div class="form-grid">
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Client Name <span style="color: var(--danger);">*</span></label>
                                            <input type="text" name="name" value="<?= h($editingClient ? $formDataEdit['name'] : $formDataCreate['name']) ?>" required class="input" placeholder="Enter client name" data-field="name">
                                        </div>

                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Company</label>
                                            <input type="text" name="company" value="<?= h($editingClient ? $formDataEdit['company'] : $formDataCreate['company']) ?>" class="input" placeholder="Company name (optional)" data-field="company">
                                        </div>

                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Display Name on Invoice</label>
                                            <select name="display_name_option" id="display_name_option" onchange="updateCustomDisplayName()" class="input" data-field="display_name_option">
                                                <?php 
                                                $clientName = $editingClient ? $formDataEdit['name'] : $formDataCreate['name'];
                                                $companyName = $editingClient ? $formDataEdit['company'] : $formDataCreate['company'];
                                                ?>
                                                <option value="client_name" <?= ($editingClient ? ($formDataEdit['display_name_option'] ?? 'client_name') : ($formDataCreate['display_name_option'] ?? 'client_name')) === 'client_name' ? 'selected' : '' ?>>
                                                    <?= h($clientName) ?> (Client)
                                                </option>
                                                <?php if (!empty($companyName)): ?>
                                                    <option value="company_name" <?= ($editingClient ? ($formDataEdit['display_name_option'] ?? '') : ($formDataCreate['display_name_option'] ?? '')) === 'company_name' ? 'selected' : '' ?>>
                                                        <?= h($companyName) ?> (Company)
                                                    </option>
                                                <?php endif; ?>
                                                <option value="custom" <?= ($editingClient ? ($formDataEdit['display_name_option'] ?? '') : ($formDataCreate['display_name_option'] ?? '')) === 'custom' ? 'selected' : '' ?>>
                                                    Custom Name (Custom)
                                                </option>
                                            </select>
                                        </div>

                                        <div id="custom_display_name_div" style="<?= ($editingClient ? ($formDataEdit['display_name_option'] ?? 'client_name') : ($formDataCreate['display_name_option'] ?? 'client_name')) !== 'custom' ? 'display: none;' : '' ?>">
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Custom Display Name</label>
                                            <input type="text" name="custom_display_name" id="custom_display_name" value="<?= h($editingClient ? $formDataEdit['custom_display_name'] : $formDataCreate['custom_display_name']) ?>" class="input" placeholder="Enter custom display name" data-field="custom_display_name">
                                        </div>

                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Email Address</label>
                                            <input type="email" name="email" value="<?= h($editingClient ? $formDataEdit['email'] : $formDataCreate['email']) ?>" class="input" placeholder="client@example.com" data-field="email">
                                        </div>

                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Phone Number</label>
                                            <input type="text" name="phone" value="<?= h($editingClient ? $formDataEdit['phone'] : $formDataCreate['phone']) ?>" class="input" placeholder="+1 (555) 123-4567" data-field="phone">
                                        </div>

                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Address</label>
                                            <input type="text" name="address" value="<?= h($editingClient ? $formDataEdit['address'] : $formDataCreate['address']) ?>" class="input" placeholder="123 Main St, City, State 12345" data-field="address">
                                        </div>
                                    </div>

                                    <div>
                                        <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Notes</label>
                                        <textarea name="notes" rows="3" class="input" placeholder="Additional notes about this client..." data-field="notes"><?= h($editingClient ? $formDataEdit['notes'] : $formDataCreate['notes']) ?></textarea>
                                    </div>

                                    <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 8px;">
                                        <button type="submit" class="btn-primary" data-form-submit>
                                            <span data-form-submit-label><?= $editingClient ? 'Update Client' : 'Add Client' ?></span>
                                        </button>
                                        <button type="button" class="btn-secondary" style="display: <?= $editingClient ? 'inline-flex' : 'none' ?>;" data-cancel-edit>
                                            Cancel
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endif; ?>

                        <?php if ($clients): ?>
                        <div class="client-grid" data-client-grid data-view-container style="margin-top: 20px;">
                        <?php foreach ($clients as $client): ?>
                        <?php 
                            $searchText = strtolower(trim(
                                ($client['name'] ?? '') . ' ' .
                                ($client['company'] ?? '') . ' ' .
                                ($client['email'] ?? '') . ' ' .
                                ($client['phone'] ?? '') . ' ' .
                                ($client['notes'] ?? '')
                            ));
                            $clientPayload = [
                                'id' => (int) ($client['id'] ?? 0),
                                'name' => $client['name'] ?? '',
                                'company' => $client['company'] ?? '',
                                'email' => $client['email'] ?? '',
                                'phone' => $client['phone'] ?? '',
                                'address' => $client['address'] ?? '',
                                'notes' => $client['notes'] ?? '',
                                'display_name_option' => $client['display_name_option'] ?? 'client_name',
                                'custom_display_name' => $client['custom_display_name'] ?? '',
                            ];
                            $clientInitialSource = $client['name'] ?? 'C';
                            if (function_exists('mb_substr')) {
                                $clientInitial = mb_strtoupper(mb_substr($clientInitialSource, 0, 1, 'UTF-8'), 'UTF-8');
                            } else {
                                $clientInitial = strtoupper(substr($clientInitialSource, 0, 1));
                            }
                        ?>
                            <div
                                class="client-card"
                                data-client-card
                                data-search-text="<?= htmlspecialchars($searchText) ?>"
                                data-client='<?= htmlspecialchars(json_encode($clientPayload, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP), ENT_QUOTES, 'UTF-8') ?>'
                            >
                                <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 12px;">
                                    <div style="display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0;">
                                        <div style="width: 32px; height: 32px; border-radius: 3px; display: flex; align-items: center; justify-content: center; background: var(--bg-surface); border: 1px solid var(--border-default); color: var(--text-primary); font-size: 12px; font-weight: 600; flex-shrink: 0;">
                                            <?= h($clientInitial ?: 'C') ?>
                                        </div>
                                        <div style="flex: 1; min-width: 0;">
                                            <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-bottom: 4px;">
                                                <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;">
                                                    <?= h($client['name']) ?>
                                                </h3>
                                                <?php if ($client['company']): ?>
                                                    <span style="display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 3px; background: var(--bg-surface); color: var(--text-secondary); font-size: 10px; font-weight: 500;">
                                                        <?= h($client['company']) ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                            <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;">ID: <?= h($client['client_number'] ?? 'CLI-' . $client['id']) ?></p>
                                        </div>
                                    </div>
                                    <?php if ($canEditClient || $canDeleteClient): ?>
                                        <div style="display: flex; align-items: center; gap: 4px; flex-shrink: 0;">
                                            <?php if ($canEditClient): ?>
                                                <a
                                                    href="/clients.php?edit=<?= (int) $client['id'] ?><?= $workspaceQuery ?>"
                                                    style="padding: 6px; border-radius: 4px; color: var(--text-tertiary); text-decoration: none; transition: background 0.1s ease;"
                                                    onmouseover="this.style.background='var(--bg-hover)'; this.style.color='var(--text-primary)'"
                                                    onmouseout="this.style.background='transparent'; this.style.color='var(--text-tertiary)'"
                                                    data-client-edit
                                                >
                                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                                    </svg>
                                                </a>
                                            <?php endif; ?>
                                            <?php if ($canDeleteClient): ?>
                                                <button
                                                    type="button"
                                                    style="padding: 6px; border-radius: 4px; color: var(--text-tertiary); background: transparent; border: none; cursor: pointer; transition: all 0.1s ease;"
                                                    onmouseover="this.style.background='rgba(235,87,87,0.1)'; this.style.color='var(--danger)'"
                                                    onmouseout="this.style.background='transparent'; this.style.color='var(--text-tertiary)'"
                                                    data-client-delete="<?= (int) $client['id'] ?>"
                                                    data-client-name="<?= h($client['name']) ?>"
                                                >
                                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                    </svg>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div style="display: flex; align-items: center; justify-content: space-between; padding-top: 12px; border-top: 1px solid var(--border-subtle); margin-top: 12px;">
                                    <div style="display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-tertiary);">
                                        <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                                        </svg>
                                        <span>Added <?= h(date('M j, Y', strtotime($client['created_at']))) ?></span>
                                    </div>
                                    <button type="button" class="btn-secondary" style="padding: 4px 8px; font-size: 11px;" data-card-toggle>
                                        <span>View details</span>
                                        <svg style="width: 12px; height: 12px; transition: transform 0.12s ease;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                        </svg>
                                    </button>
                                </div>

                                <div style="margin-top: 12px; display: none; flex-direction: column; gap: 12px;" data-card-details>
                                    <div style="display: flex; flex-direction: column; gap: 8px; font-size: 12px; color: var(--text-secondary);">
                                        <?php if (!empty($client['email'])): ?>
                                            <div style="display: flex; align-items: center; gap: 8px;">
                                                <svg style="width: 14px; height: 14px; opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                                                </svg>
                                                <a href="mailto:<?= h($client['email']) ?>" style="color: inherit; text-decoration: none; transition: color 0.1s ease;" onmouseover="this.style.color='var(--success)'" onmouseout="this.style.color='var(--text-secondary)'"><?= h($client['email']) ?></a>
                                            </div>
                                        <?php endif; ?>
                                        <?php if (!empty($client['phone'])): ?>
                                            <div style="display: flex; align-items: center; gap: 8px;">
                                                <svg style="width: 14px; height: 14px; opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.163 21 3 14.837 3 7V5z"></path>
                                                </svg>
                                                <a href="tel:<?= h($client['phone']) ?>" style="color: inherit; text-decoration: none; transition: color 0.1s ease;" onmouseover="this.style.color='var(--success)'" onmouseout="this.style.color='var(--text-secondary)'"><?= h($client['phone']) ?></a>
                                            </div>
                                        <?php endif; ?>
                                        <?php if (!empty($client['address'])): ?>
                                            <div style="display: flex; align-items: center; gap: 8px;">
                                                <svg style="width: 14px; height: 14px; opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 11c1.657 0 3-1.343 3-3S13.657 5 12 5 9 6.343 9 8s1.343 3 3 3z"></path>
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.5 8c0 7.732-7.5 13-7.5 13S4.5 15.732 4.5 8a7.5 7.5 0 1115 0z"></path>
                                                </svg>
                                                <span><?= h($client['address']) ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <?php if (!empty($client['notes'])): ?>
                                        <div style="padding: 12px 14px; border-radius: 6px; background: var(--bg-surface); border: 1px solid var(--border-subtle);">
                                            <div style="display: flex; align-items: flex-start; gap: 8px;">
                                                <svg style="width: 14px; height: 14px; opacity: 0.5; flex-shrink: 0; margin-top: 2px;" 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 style="font-size: 12px; line-height: 1.5; color: var(--text-secondary); margin: 0;"><?= h($client['notes']) ?></p>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                            <div class="empty-state" style="display: none;" data-client-empty>
                                <div class="empty-icon">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                                    </svg>
                                </div>
                                <h3 class="empty-title">No matching clients</h3>
                                <p class="empty-desc">Try adjusting your search terms.</p>
                            </div>
                        <?php else: ?>
                            <div class="empty-state">
                                <div class="empty-icon">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                                    </svg>
                                </div>
                                <h3 class="empty-title">No clients found</h3>
                                <p class="empty-desc"><?= $search ? 'Try adjusting your search terms' : 'Get started by adding your first client' ?></p>
                                <?php if ($search): ?>
                                    <a href="/clients.php<?= $workspaceQuery ?>" class="btn-secondary">
                                        <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                        </svg>
                                        <span>Clear Search</span>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="delete-modal-overlay" style="position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; padding: 16px;" data-delete-modal>
        <div class="delete-modal-content">
            <div class="delete-modal-header">
                <p style="font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.03em; color: var(--danger); margin: 0 0 8px;">Danger zone</p>
                <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0 0 4px;">Delete client</h3>
                <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;">This action cannot be undone. All associated records will remain but lose this link.</p>
            </div>
            <div class="delete-modal-body">
                <div class="delete-modal-client-info">
                    <p style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 0 0 4px;">Client</p>
                    <p style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0 0 2px;" data-delete-client-name></p>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;" data-delete-client-meta></p>
                </div>
                <div>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin: 0 0 8px;">Type DELETE to confirm.</p>
                    <input type="text" class="input" placeholder="DELETE" data-delete-confirm-input style="font-family: monospace; text-transform: uppercase;">
                </div>
            </div>
            <div class="delete-modal-footer">
                <button type="button" class="btn-secondary" style="flex: 1;" data-delete-cancel>Cancel</button>
                <button type="button" class="btn-danger" style="flex: 1;" data-delete-confirm disabled>
                    Delete client
                </button>
            </div>
        </div>
    </div>

<script>
function updateCustomDisplayName() {
    const dropdown = document.getElementById('display_name_option');
    const customField = document.getElementById('custom_display_name_div');
    
    if (dropdown.value === 'custom') {
        customField.style.display = 'block';
    } else {
        customField.style.display = 'none';
    }
}

// Wire mobile menu button to app sidebar toggle from navigation.php
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }

    const formPanel = document.querySelector('[data-form-panel]');
    const formPanelBody = formPanel ? formPanel.querySelector('[data-form-panel-body]') : null;
    const formToggle = document.getElementById('client-form-toggle');
    const form = document.querySelector('[data-client-form]');
    const formTitle = formPanelBody ? formPanelBody.querySelector('[data-form-title]') : null;
    const formSubtitle = form ? form.querySelector('[data-form-subtitle]') : null;
    const formSubmitBtn = form ? form.querySelector('[data-form-submit]') : null;
    const formSubmitLabel = formSubmitBtn ? formSubmitBtn.querySelector('[data-form-submit-label]') : null;
    const formCancelEdit = form ? form.querySelector('[data-cancel-edit]') : null;

    let openPanelHandler = null;
    let closePanelHandler = null;

    if (formPanel && formPanelBody && formToggle) {
        let isOpen = formPanel.dataset.open === 'true';

        const setHeight = (value) => {
            formPanel.style.height = value;
        };

        if (isOpen) {
            setHeight('auto');
        } else {
            setHeight('0px');
        }

        formPanel.addEventListener('transitionend', (event) => {
            if (event.propertyName !== 'height') return;
            if (isOpen) {
                setHeight('auto');
            }
        });

        const openPanel = () => {
            const targetHeight = formPanelBody.offsetHeight;
            setHeight(targetHeight + 'px');
            isOpen = true;
            formPanel.dataset.open = 'true';
        };

        const closePanel = () => {
            const currentHeight = formPanelBody.offsetHeight;
            setHeight(currentHeight + 'px');
            requestAnimationFrame(() => {
                setHeight('0px');
            });
            isOpen = false;
            formPanel.dataset.open = 'false';
        };

        openPanelHandler = openPanel;
        closePanelHandler = closePanel;

        formToggle.addEventListener('click', () => {
            if (isOpen) {
                closePanel();
            } else {
                openPanel();
            }
        });
    }

    const formDefaults = form ? JSON.parse(form.dataset.defaults || '{}') : {};
    const initialClientData = form && form.dataset.initialClient ? JSON.parse(form.dataset.initialClient) : null;
    const initialMode = form ? (form.dataset.initialMode || 'create') : 'create';

    const setFormMode = (mode, payload = null) => {
        if (!form) return;
        const title = mode === 'edit' ? form.dataset.editTitle : form.dataset.createTitle;
        const subtitle = mode === 'edit' ? form.dataset.editSubtitle : form.dataset.createSubtitle;

        if (formTitle && title) formTitle.textContent = title;
        if (formSubtitle) formSubtitle.textContent = subtitle || '';
        if (formSubmitLabel) formSubmitLabel.textContent = mode === 'edit' ? 'Update Client' : 'Add Client';
        if (formCancelEdit) formCancelEdit.style.display = mode === 'edit' ? 'inline-flex' : 'none';

        const actionInput = document.getElementById('client-form-action');
        const idInput = document.getElementById('client-form-id');
        if (actionInput) actionInput.value = mode === 'edit' ? 'update' : 'create';
        if (idInput) idInput.value = payload && payload.id ? payload.id : '';

        const data = mode === 'edit' && payload ? { ...formDefaults, ...payload } : { ...formDefaults };

        form.querySelectorAll('[data-field]').forEach(field => {
            const key = field.dataset.field;
            if (typeof data[key] !== 'undefined') {
                field.value = data[key];
            } else {
                field.value = '';
            }
        });

        updateCustomDisplayName();
        if (mode === 'edit' && openPanelHandler) {
            openPanelHandler();
            form.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    };

    if (formCancelEdit) {
        formCancelEdit.addEventListener('click', () => {
            setFormMode('create');
            if (closePanelHandler) {
                closePanelHandler();
            }
        });
    }

    document.querySelectorAll('[data-open-form]').forEach(link => {
        link.addEventListener('click', (event) => {
            event.preventDefault();
            const isOpen = formPanel && formPanel.dataset.open === 'true';
            const isEditing = formCancelEdit && !formCancelEdit.classList.contains('hidden');

            if (isOpen && !isEditing) {
                if (closePanelHandler) {
                    closePanelHandler();
                }
            } else {
                setFormMode('create');
                if (openPanelHandler) {
                    openPanelHandler();
                }
            }
            link.blur();
        });
    });

    document.querySelectorAll('[data-client-edit]').forEach(button => {
        button.addEventListener('click', event => {
            event.preventDefault();
            const card = button.closest('[data-client-card]');
            if (!card) return;
            const payload = card.dataset.client ? JSON.parse(card.dataset.client) : null;
            if (!payload) return;
            setFormMode('edit', payload);
        });
    });

    if (form) {
        setFormMode(initialMode === 'edit' ? 'edit' : 'create', initialMode === 'edit' ? initialClientData : null);
        if (initialMode === 'edit' && openPanelHandler) {
            openPanelHandler();
        }
    }

    const deleteModal = document.querySelector('[data-delete-modal]');
    const deleteConfirmInput = deleteModal ? deleteModal.querySelector('[data-delete-confirm-input]') : null;
    const deleteConfirmBtn = deleteModal ? deleteModal.querySelector('[data-delete-confirm]') : null;
    const deleteClientName = deleteModal ? deleteModal.querySelector('[data-delete-client-name]') : null;
    const deleteClientMeta = deleteModal ? deleteModal.querySelector('[data-delete-client-meta]') : null;
    const deleteCancelBtn = deleteModal ? deleteModal.querySelector('[data-delete-cancel]') : null;
    const deleteForm = document.createElement('form');
    deleteForm.method = 'POST';
    deleteForm.classList.add('hidden');
    deleteForm.innerHTML = '<input type="hidden" name="id"><input type="hidden" name="action" value="delete">';
    document.body.appendChild(deleteForm);
    const deleteIdInput = deleteForm.querySelector('input[name="id"]');

    const toggleDeleteModal = (show) => {
        if (!deleteModal) return;
        if (show) {
            deleteModal.style.display = 'flex';
        } else {
            deleteModal.style.display = 'none';
        }
        if (show && deleteConfirmInput) {
            deleteConfirmInput.value = '';
            deleteConfirmInput.focus();
        }
        if (deleteConfirmBtn) {
            deleteConfirmBtn.disabled = true;
        }
        if (!show && deleteConfirmInput) {
            deleteConfirmInput.value = '';
        }
    };

    document.querySelectorAll('[data-client-delete]').forEach(button => {
        button.addEventListener('click', () => {
            const clientId = button.getAttribute('data-client-delete');
            const clientName = button.getAttribute('data-client-name');
            if (deleteClientName) deleteClientName.textContent = clientName || 'Unnamed client';
            if (deleteClientMeta) deleteClientMeta.textContent = `ID ${clientId}`;
            if (deleteIdInput) deleteIdInput.value = clientId;
            toggleDeleteModal(true);
        });
    });

    if (deleteConfirmInput && deleteConfirmBtn) {
        deleteConfirmInput.addEventListener('input', () => {
            deleteConfirmBtn.disabled = deleteConfirmInput.value.trim().toUpperCase() !== 'DELETE';
        });

        deleteConfirmBtn.addEventListener('click', () => {
            if (deleteConfirmBtn.disabled) return;
            deleteForm.submit();
        });
    }

    if (deleteCancelBtn) {
        deleteCancelBtn.addEventListener('click', () => toggleDeleteModal(false));
    }

        if (deleteModal) {
            deleteModal.addEventListener('click', (event) => {
                if (event.target === deleteModal) {
                    toggleDeleteModal(false);
                }
            });
            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape' && deleteModal.style.display !== 'none') {
                    toggleDeleteModal(false);
                }
            });
        }

    document.querySelectorAll('[data-card-toggle]').forEach(toggle => {
        const card = toggle.closest('[data-client-card]');
        const details = card ? card.querySelector('[data-card-details]') : null;
        const chevron = toggle.querySelector('svg');
        if (!card || !details) return;
        toggle.addEventListener('click', () => {
            const isOpen = details.style.display !== 'none';
            details.style.display = isOpen ? 'none' : 'flex';
            if (chevron) {
                if (isOpen) {
                    chevron.style.transform = '';
                } else {
                    chevron.style.transform = 'rotate(180deg)';
                }
            }
            toggle.querySelector('span').textContent = isOpen ? 'View details' : 'Hide details';
        });
    });

    // Instant client filtering
    const searchForm = document.getElementById('client-search-form');
    const searchInput = document.getElementById('client-search-input');
    const clientCards = Array.from(document.querySelectorAll('[data-client-card]'));
    const clientCountEl = document.querySelector('[data-client-count]');
    const emptyState = document.querySelector('[data-client-empty]');

    if (searchInput && clientCards.length) {
        const applyFilter = () => {
            const query = searchInput.value.trim().toLowerCase();
            let visibleCount = 0;

            clientCards.forEach(card => {
                const text = card.dataset.searchText || '';
                const matches = query === '' || text.includes(query);
                card.style.display = matches ? 'block' : 'none';
                if (matches) {
                    visibleCount += 1;
                }
            });

            if (clientCountEl) {
                clientCountEl.textContent = visibleCount;
            }

            if (emptyState) {
                emptyState.style.display = visibleCount === 0 ? 'block' : 'none';
            }
        };

        searchInput.addEventListener('input', applyFilter);
        searchInput.addEventListener('search', applyFilter);

        if (searchForm) {
            searchForm.addEventListener('submit', function (event) {
                event.preventDefault();
                applyFilter();
            });
        }

        applyFilter();
    }

    // View toggle (grid/list)
    const viewToggle = document.querySelector('[data-view-toggle]');
    const viewContainer = document.querySelector('[data-view-container]');
    const viewButtons = viewToggle ? viewToggle.querySelectorAll('button[data-view]') : [];
    let currentView = localStorage.getItem('client-view') || 'grid';

    const setView = (view) => {
        if (!viewContainer) return;
        currentView = view;
        localStorage.setItem('client-view', view);
        
        viewButtons.forEach(btn => {
            if (btn.dataset.view === view) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });

        if (view === 'list') {
            viewContainer.classList.add('client-list-view');
            viewContainer.classList.remove('client-grid');
        } else {
            viewContainer.classList.remove('client-list-view');
            viewContainer.classList.add('client-grid');
        }
    };

    viewButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            setView(btn.dataset.view);
        });
    });

    // Set initial view
    if (viewContainer) {
        setView(currentView);
    }

    // Handle "New Client" button in header
    const headerNewClientBtn = document.getElementById('header-new-client-btn');
    if (headerNewClientBtn && formToggle && openPanelHandler && closePanelHandler) {
        headerNewClientBtn.addEventListener('click', (e) => {
            e.preventDefault();
            if (formPanel) {
                const isOpen = formPanel.dataset.open === 'true';
                if (isOpen) {
                    closePanelHandler();
                } else {
                    openPanelHandler();
                    // Scroll to form
                    formPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            }
        });
    }

    // Auto-open form if action=create in URL
    if (window.location.search.includes('action=create') && openPanelHandler) {
        openPanelHandler();
        // Clean URL
        const url = new URL(window.location);
        url.searchParams.delete('action');
        window.history.replaceState({}, '', url);
    }
});
</script>

</body>
</html>
