@extends('layouts.brand')

@section('title', 'Content Localization')

@section('content')
<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1">Content Localization</h2>
                    <p class="text-muted">Translate and adapt your content for different markets</p>
                </div>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newLocalizationModal">
                    <i class="fas fa-plus me-2"></i>Request Translation
                </button>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1">Total Translations</p>
                            <h3 class="mb-0">{{ $stats['total'] }}</h3>
                        </div>
                        <div class="text-primary">
                            <i class="fas fa-language fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1">Approved</p>
                            <h3 class="mb-0 text-success">{{ $stats['approved'] }}</h3>
                        </div>
                        <div class="text-success">
                            <i class="fas fa-check-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1">Pending Review</p>
                            <h3 class="mb-0 text-warning">{{ $stats['pending'] }}</h3>
                        </div>
                        <div class="text-warning">
                            <i class="fas fa-clock fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1">Rejected</p>
                            <h3 class="mb-0 text-danger">{{ $stats['rejected'] }}</h3>
                        </div>
                        <div class="text-danger">
                            <i class="fas fa-times-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @if($contentType && $contentId && count($localizations) > 0)
    <!-- Localization Panel -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">Localizations for {{ ucfirst($contentType) }} #{{ $contentId }}</h5>
        </div>
        <div class="card-body">
            <div class="row">
                @foreach($localizations as $localization)
                <div class="col-md-6 mb-4">
                    <div class="card h-100 border-{{ $localization['status'] === 'approved' ? 'success' : ($localization['status'] === 'rejected' ? 'danger' : 'warning') }}">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-0">
                                    <i class="fas fa-flag me-2"></i>{{ $localization['locale_display_name'] ?? $localization['locale_code'] }}
                                </h6>
                                <small class="text-muted">Tone: {{ ucfirst($localization['tone']) }}</small>
                            </div>
                            <span class="badge bg-{{ $localization['status'] === 'approved' ? 'success' : ($localization['status'] === 'rejected' ? 'danger' : 'warning') }}">
                                {{ ucfirst($localization['status']) }}
                            </span>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Original Text:</label>
                                <div class="p-2 bg-light rounded">
                                    {{ Str::limit($localization['source_text'], 150) }}
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Localized Text:</label>
                                <div class="p-2 bg-light rounded">
                                    {{ Str::limit($localization['localized_text'], 150) }}
                                </div>
                            </div>
                            @if($localization['cultural_notes'])
                            <div class="mb-3">
                                <label class="form-label fw-bold">Cultural Notes:</label>
                                <div class="p-2 bg-info bg-opacity-10 rounded">
                                    <small>{{ $localization['cultural_notes'] }}</small>
                                </div>
                            </div>
                            @endif
                        </div>
                        <div class="card-footer">
                            <div class="btn-group w-100" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="viewLocalization({{ $localization['id'] }})">
                                    <i class="fas fa-eye me-1"></i>View
                                </button>
                                @if($localization['status'] !== 'approved')
                                <button type="button" class="btn btn-sm btn-outline-success" onclick="approveLocalization({{ $localization['id'] }})">
                                    <i class="fas fa-check me-1"></i>Approve
                                </button>
                                @endif
                                <button type="button" class="btn btn-sm btn-outline-warning" onclick="editLocalization({{ $localization['id'] }})">
                                    <i class="fas fa-edit me-1"></i>Edit
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-info" onclick="exportLocalization({{ $localization['id'] }})">
                                    <i class="fas fa-download me-1"></i>Export
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
    </div>
    @else
    <!-- Empty State -->
    <div class="card">
        <div class="card-body text-center py-5">
            <i class="fas fa-language fa-4x text-muted mb-3"></i>
            <h4>No Localizations Yet</h4>
            <p class="text-muted">Start by requesting translations for your campaign content</p>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newLocalizationModal">
                <i class="fas fa-plus me-2"></i>Request Your First Translation
            </button>
        </div>
    </div>
    @endif
</div>

<!-- New Localization Modal -->
<div class="modal fade" id="newLocalizationModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Request Translation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="localizationForm">
                @csrf
                <div class="modal-body">
                    <input type="hidden" name="brand_id" value="{{ $brand->id }}">
                    
                    <div class="mb-3">
                        <label class="form-label">Content Type</label>
                        <select class="form-select" name="content_type" required>
                            <option value="">Select content type...</option>
                            <option value="ad">Advertisement</option>
                            <option value="post">Social Post</option>
                            <option value="proposal">Proposal</option>
                            <option value="campaign">Campaign</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Content ID</label>
                        <input type="number" class="form-control" name="content_id" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Source Text</label>
                        <textarea class="form-control" name="source_text" rows="4" required></textarea>
                        <small class="text-muted">The original text to be translated</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Target Languages</label>
                        <select class="form-select" name="target_locales[]" multiple required size="8">
                            @foreach($supportedLocales as $code => $name)
                            <option value="{{ $code }}">{{ $name }}</option>
                            @endforeach
                        </select>
                        <small class="text-muted">Hold Ctrl/Cmd to select multiple languages</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Tone</label>
                        <select class="form-select" name="tone" required>
                            @foreach($supportedTones as $value => $label)
                            <option value="{{ $value }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Additional Context (Optional)</label>
                        <textarea class="form-control" name="context" rows="2"></textarea>
                        <small class="text-muted">Provide context to help with accurate translation</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane me-2"></i>Request Translation
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.getElementById('localizationForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    data.target_locales = formData.getAll('target_locales[]');
    
    try {
        const response = await fetch('{{ route("brand.localization.store") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Translation request submitted successfully!');
            location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('An error occurred. Please try again.');
        console.error(error);
    }
});

function viewLocalization(id) {
    window.location.href = `/brand/localization/${id}`;
}

async function approveLocalization(id) {
    if (!confirm('Are you sure you want to approve this translation?')) return;
    
    try {
        const response = await fetch(`/brand/localization/${id}/approve`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Translation approved successfully!');
            location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('An error occurred. Please try again.');
        console.error(error);
    }
}

function editLocalization(id) {
    // Implement edit functionality
    window.location.href = `/brand/localization/${id}`;
}

async function exportLocalization(id) {
    try {
        const response = await fetch(`/brand/localization/${id}/export`);
        const result = await response.json();
        
        if (result.success) {
            // Download as JSON
            const blob = new Blob([JSON.stringify(result.data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `localization_${id}.json`;
            a.click();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('An error occurred. Please try again.');
        console.error(error);
    }
}
</script>
@endpush
@endsection