<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-l text-gray-800 leading-tight">
                {{ \App\Helpers\TranslationHelper::transFromDatabase('Accounts Tree', __('Accounts Tree')) }}
            </h2>
            <div>
                <a href="{{ route('accounting.chart-of-accounts.index') }}" class="inline-flex items-center p-4 py-2 bg-gray-600 border border-transparent rounded-md font-semibold text-s text-white uppercase tracking-widest hover:bg-gray-700 focus:bg-gray-700 active:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition ease-in-out duration-150">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                    </svg>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Back', __('Back')) }}
                </a>
            </div>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7l m-auto sm:p-6 lg:p-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <div class="mb-6">
                        <div class="flex justify-between items-start mb-6">
                            <div>
                                <h3 class="text-lg font-medium text-gray-900">{{ \App\Helpers\TranslationHelper::transFromDatabase('Accounts Tree', __('Accounts Tree')) }}</h3>
                                <p class="mt-1 text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Structure', __('Account Structure')) }}</p>
                            </div>
                        </div>

                        <!-- Search Bar -->
                        <div class="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div class="flex items-center gap-4">
                                <div class="flex-1 relative">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                                    </svg>
                                    <input 
                                        type="text" 
                                        id="search-accounts" 
                                        placeholder="{{ \App\Helpers\TranslationHelper::transFromDatabase('Search by account number or name (e.g., 1100 or Assets)', 'ابحث برقم الحساب أو الاسم (مثال: 1100 أو أصول)') }}"
                                        class="w-full pl-10 pr-10 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none transition"
                                    >
                                    <button 
                                        id="clear-search" 
                                        class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 hidden transition"
                                        title="مسح البحث"
                                    >
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                                        </svg>
                                    </button>
                                </div>
                                <div id="search-results-count" class="text-sm text-gray-600 font-medium whitespace-nowrap hidden">
                                    <span id="match-count">0</span> نتيجة
                                </div>
                            </div>
                        </div>

                        <div class="flex gap-2 flex-wrap">
                            <button id="expand-all" class="inline-flex items-center px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-150">
                                <i class="fas fa-expand-alt ml-2"></i>
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Expand All', __('Expand All')) }}
                            </button>
                            <button id="collapse-all" class="inline-flex items-center px-3 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors duration-150">
                                <i class="fas fa-compress-alt ml-2"></i>
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Collapse All', __('Collapse All')) }}
                            </button>
                            <a href="{{ route('accounting.chart-of-accounts.export') }}" class="inline-flex items-center px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors duration-150" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Export', __('Export')) }}">
                                <i class="fas fa-download ml-2"></i>
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Export', __('Export')) }}
                            </a>
                            <a href="{{ route('accounting.chart-of-accounts.import-form') }}" class="inline-flex items-center px-3 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors duration-150" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Import', __('Import')) }}">
                                <i class="fas fa-upload ml-2"></i>
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Import', __('Import')) }}
                            </a>
                            @if(session('company_id') != 1)
                            <form action="{{ route('accounting.chart-of-accounts.duplicate-from-company1') }}" method="POST" class="inline">
                                @csrf
                                <button type="submit" class="inline-flex items-center px-3 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors duration-150" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Duplicate from Company', __('Duplicate from Company')) }}" onclick="return confirm('{{ \App\Helpers\TranslationHelper::transFromDatabase('Are you sure you want to duplicate the chart of accounts?', __('Are you sure you want to duplicate the chart of accounts?')) }}')">
                                    <i class="fas fa-copy ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Duplicate from Company', __('Duplicate from Company')) }}
                                </button>
                            </form>
                            @endif
                        </div>
                    </div>

                    <div class="mt-6">
                        <div id="no-results" class="hidden p-8 text-center">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-gray-400 mb-3" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                            </svg>
                            <p class="text-gray-500">لم يتم العثور على حسابات تطابق البحث</p>
                        </div>

                        <ul class="space-y-2" id="accounts-tree">
                            @forelse ($accounts as $account)
                                <li class="border-r-2 border-gray-300 pr-4 tree-item" data-account-id="{{ $account->id }}" data-account-code="{{ $account->code }}" data-account-name="{{ $account->name }}">
                                    <div class="flex items-center">
                                        @if ($account->children && $account->children->count() > 0)
                                            <button class="toggle-btn mr-2 p-1 hover:bg-gray-100 rounded transition-colors duration-150" data-account-id="{{ $account->id }}" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Toggle', __('Toggle')) }}">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-600 transition-transform duration-200 transform" viewBox="0 0 20 20" fill="currentColor" style="transform: rotate(-90deg);">
                                                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                                </svg>
                                            </button>
                                        @else
                                            <div class="mr-2 p-1 w-8"></div>
                                        @endif
                                        
                                        <div class="flex-shrink-0">
                                            @if ($account->is_parent)
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-500" viewBox="0 0 20 20" fill="currentColor">
                                                    <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" />
                                                </svg>
                                            @else
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-500" viewBox="0 0 20 20" fill="currentColor">
                                                    <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd" />
                                                </svg>
                                            @endif
                                        </div>
                                        <div class="mr-3 flex-grow">
                                            <div class="text-sm font-medium text-gray-900">
                                                <a href="{{ route('accounting.chart-of-accounts.show', $account) }}" class="hover:underline">
                                                    <span class="account-code">{{ $account->code }}</span> - <span class="account-name">{{ $account->name }}</span>
                                                </a>
                                                @if (!$account->is_active)
                                                    <span class="inline-flex items-center p-2.5 py-0.5 rounded-full text-s font-medium bg-red-100 text-red-800 mr-2">
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Inactive', __('Inactive')) }}
                                                    </span>
                                                @endif
                                            </div>
                                            <div class="text-s text-gray-500">
                                                @switch($account->account_type)
                                                    @case('asset')
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Assets', __('Assets')) }}
                                                        @break
                                                    @case('liability')
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Liabilities', __('Liabilities')) }}
                                                        @break
                                                    @case('equity')
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Equity', __('Equity')) }}
                                                        @break
                                                    @case('revenue')
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Revenue', __('Revenue')) }}
                                                        @break
                                                    @case('expense')
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Expenses', __('Expenses')) }}
                                                        @break
                                                    @default
                                                        {{ $account->account_type }}
                                                @endswitch
                                                -
                                                @if ($account->balance_type == 'debit')
                                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Debit', __('Debit')) }}
                                                @else
                                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Credit', __('Credit')) }}
                                                @endif
                                            </div>
                                        </div>
                                    </div>

                                    @if ($account->children && $account->children->count() > 0)
                                        <ul class="children-container mt-2 space-y-2 mr-6 border-r-2 border-gray-200 pr-4" id="children-{{ $account->id }}" style="display: block;">
                                            @foreach ($account->children as $child)
                                                @include('accounting.chart-of-accounts.partials.account-tree-item', ['account' => $child])
                                            @endforeach
                                        </ul>
                                    @endif
                                </li>
                            @empty
                                <li class="text-sm text-gray-500">{{ \App\Helpers\TranslationHelper::transFromDatabase('No Accounts', __('No Accounts')) }}</li>
                            @endforelse
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search-accounts');
            const clearBtn = document.getElementById('clear-search');
            const resultsCount = document.getElementById('search-results-count');
            const noResults = document.getElementById('no-results');
            const accountsTree = document.getElementById('accounts-tree');
            const matchCountSpan = document.getElementById('match-count');

            // Toggle button functionality
            const toggleButtons = document.querySelectorAll('.toggle-btn');
            
            toggleButtons.forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const accountId = this.getAttribute('data-account-id');
                    const childrenContainer = document.getElementById('children-' + accountId);
                    const icon = this.querySelector('svg');
                    
                    if (childrenContainer) {
                        const isHidden = childrenContainer.style.display === 'none';
                        childrenContainer.style.display = isHidden ? 'block' : 'none';
                        
                        if (isHidden) {
                            icon.style.transform = 'rotate(-90deg)';
                        } else {
                            icon.style.transform = 'rotate(0deg)';
                        }
                        
                        const expanded = JSON.parse(localStorage.getItem('accountsExpanded') || '{}');
                        expanded[accountId] = isHidden;
                        localStorage.setItem('accountsExpanded', JSON.stringify(expanded));
                    }
                });
            });

            // Search functionality
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase().trim();
                
                if (searchTerm) {
                    clearBtn.classList.remove('hidden');
                } else {
                    clearBtn.classList.add('hidden');
                    noResults.classList.add('hidden');
                    resultsCount.classList.add('hidden');
                }

                filterAccounts(searchTerm);
            });

            clearBtn.addEventListener('click', function() {
                searchInput.value = '';
                clearBtn.classList.add('hidden');
                noResults.classList.add('hidden');
                resultsCount.classList.add('hidden');
                filterAccounts('');
            });

            function filterAccounts(searchTerm) {
                const allItems = document.querySelectorAll('.tree-item');
                let matchCount = 0;
                const matchedItems = new Set();
                const parentItems = new Set();

                allItems.forEach(item => {
                    const code = item.getAttribute('data-account-code').toLowerCase();
                    const name = item.getAttribute('data-account-name').toLowerCase();
                    
                    if (code.includes(searchTerm) || name.includes(searchTerm)) {
                        matchCount++;
                        matchedItems.add(item);
                        
                        // Find and mark parent items
                        let parent = item.parentElement.closest('.tree-item');
                        while (parent) {
                            parentItems.add(parent);
                            parent = parent.parentElement.closest('.tree-item');
                        }
                    }
                });

                // Hide or show items
                allItems.forEach(item => {
                    const shouldShow = matchedItems.has(item) || (searchTerm && parentItems.has(item));
                    
                    if (searchTerm && shouldShow) {
                        item.style.display = 'block';
                        
                        // Expand parents when searching
                        if (matchedItems.has(item)) {
                            let parent = item.parentElement.closest('.tree-item');
                            while (parent) {
                                const parentId = parent.getAttribute('data-account-id');
                                const childrenContainer = document.getElementById('children-' + parentId);
                                const toggleBtn = parent.querySelector('.toggle-btn');
                                
                                if (childrenContainer) {
                                    childrenContainer.style.display = 'block';
                                    if (toggleBtn) {
                                        const icon = toggleBtn.querySelector('svg');
                                        icon.style.transform = 'rotate(-90deg)';
                                    }
                                }
                                parent = parent.parentElement.closest('.tree-item');
                            }
                        }
                        
                        // Highlight matched text
                        if (matchedItems.has(item)) {
                            item.style.backgroundColor = '#fffbeb';
                            item.style.borderLeft = '4px solid #fbbf24';
                            item.style.paddingLeft = '8px';
                        } else {
                            item.style.backgroundColor = '';
                            item.style.borderLeft = '';
                            item.style.paddingLeft = '';
                        }
                    } else if (searchTerm && !shouldShow) {
                        item.style.display = 'none';
                    } else {
                        item.style.display = 'block';
                        item.style.backgroundColor = '';
                        item.style.borderLeft = '';
                        item.style.paddingLeft = '';
                    }
                });

                // Show/hide no results message and count
                if (searchTerm) {
                    if (matchCount === 0) {
                        noResults.classList.remove('hidden');
                        resultsCount.classList.add('hidden');
                    } else {
                        noResults.classList.add('hidden');
                        resultsCount.classList.remove('hidden');
                        matchCountSpan.textContent = matchCount;
                    }
                }
            }

            // Expand all functionality
            document.getElementById('expand-all').addEventListener('click', function() {
                const childContainers = document.querySelectorAll('.children-container:not([style*="display: none"])');
                const toggleBtns = document.querySelectorAll('.toggle-btn');
                
                childContainers.forEach(container => {
                    container.style.display = 'block';
                });
                
                toggleBtns.forEach(btn => {
                    const icon = btn.querySelector('svg');
                    icon.style.transform = 'rotate(-90deg)';
                    const accountId = btn.getAttribute('data-account-id');
                    const expanded = JSON.parse(localStorage.getItem('accountsExpanded') || '{}');
                    expanded[accountId] = true;
                    localStorage.setItem('accountsExpanded', JSON.stringify(expanded));
                });
            });

            // Collapse all functionality
            document.getElementById('collapse-all').addEventListener('click', function() {
                const childContainers = document.querySelectorAll('.children-container');
                const toggleBtns = document.querySelectorAll('.toggle-btn');
                
                childContainers.forEach(container => {
                    container.style.display = 'none';
                });
                
                toggleBtns.forEach(btn => {
                    const icon = btn.querySelector('svg');
                    icon.style.transform = 'rotate(0deg)';
                    const accountId = btn.getAttribute('data-account-id');
                    const expanded = JSON.parse(localStorage.getItem('accountsExpanded') || '{}');
                    expanded[accountId] = false;
                    localStorage.setItem('accountsExpanded', JSON.stringify(expanded));
                });
            });

            // Restore expanded state from localStorage
            const expanded = JSON.parse(localStorage.getItem('accountsExpanded') || '{}');
            Object.keys(expanded).forEach(accountId => {
                const childrenContainer = document.getElementById('children-' + accountId);
                const toggleBtn = document.querySelector(`[data-account-id="${accountId}"].toggle-btn`);
                
                if (childrenContainer && toggleBtn) {
                    const icon = toggleBtn.querySelector('svg');
                    if (expanded[accountId]) {
                        childrenContainer.style.display = 'block';
                        icon.style.transform = 'rotate(-90deg)';
                    } else {
                        childrenContainer.style.display = 'none';
                        icon.style.transform = 'rotate(0deg)';
                    }
                }
            });
        });
    </script>
    @endpush
</x-app-layout>