@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'Discover Jobs')

@section('left_sidebar')
@include('front_end.pages.jobs.job_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- Discovery Header -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-gradient-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <a href="{{ url('/jobs') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Discover Jobs</h4>
                                    <p class="mb-0 text-white">Find opportunities that match your skills and interests</p>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <button class="btn btn-light btn-sm" id="refreshJobs">
                                    <i class="fas fa-sync-alt me-2"></i>Refresh
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Discovery Filters -->
    <div class="container mt-4">
        <!-- Trending Keywords -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-0 bg-light">
                    <div class="card-body p-3">
                        <h6 class="mb-3">Trending Keywords</h6>
                        <div class="d-flex flex-wrap gap-2" id="trendingKeywords">
                            <!-- Trending keywords will be loaded here -->
                            <div class="text-center w-100">
                                <div class="spinner-border spinner-border-sm text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Advanced Search -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-0">
                    <div class="card-header bg-transparent border-0">
                        <h5 class="mb-0">Advanced Job Search</h5>
                    </div>
                    <div class="card-body">
                        <form id="discoverySearchForm">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Job Title or Keywords</label>
                                    <input type="text" class="form-control" id="searchKeywords" placeholder="e.g., Software Developer, Marketing Manager">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Company</label>
                                    <input type="text" class="form-control" id="searchCompany" placeholder="e.g., Google, Microsoft">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Location</label>
                                    <input type="text" class="form-control" id="searchLocation" placeholder="City, State, or Remote">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Job Type</label>
                                    <select class="form-select" id="searchJobType">
                                        <option value="">All Types</option>
                                        <option value="full-time">Full-time</option>
                                        <option value="part-time">Part-time</option>
                                        <option value="contract">Contract</option>
                                        <option value="internship">Internship</option>
                                        <option value="temporary">Temporary</option>
                                        <option value="freelance">Freelance</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Experience Level</label>
                                    <select class="form-select" id="searchExperience">
                                        <option value="">Any Level</option>
                                        <option value="0-1">Entry Level (0-1 years)</option>
                                        <option value="2-4">Mid Level (2-4 years)</option>
                                        <option value="5-7">Senior Level (5-7 years)</option>
                                        <option value="8+">Expert Level (8+ years)</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Minimum Salary</label>
                                    <select class="form-select" id="searchMinSalary">
                                        <option value="">Any</option>
                                        <option value="30000">$30,000+</option>
                                        <option value="50000">$50,000+</option>
                                        <option value="75000">$75,000+</option>
                                        <option value="100000">$100,000+</option>
                                        <option value="125000">$125,000+</option>
                                        <option value="150000">$150,000+</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Posted Within</label>
                                    <select class="form-select" id="searchPostedWithin">
                                        <option value="">Any Time</option>
                                        <option value="1">Last 24 hours</option>
                                        <option value="7">Last week</option>
                                        <option value="30">Last month</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search me-2"></i>Search Jobs
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary ms-2" id="clearSearch">
                                        <i class="fas fa-times me-2"></i>Clear
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search Results -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">
                        Search Results 
                        <span class="badge bg-primary ms-2" id="resultsCount">0</span>
                    </h5>
                    <div class="d-flex gap-2">
                        <select class="form-select form-select-sm" id="sortBy" style="width: auto;">
                            <option value="created_at">Newest First</option>
                            <option value="salary_desc">Salary: High to Low</option>
                            <option value="salary_asc">Salary: Low to High</option>
                            <option value="relevance">Most Relevant</option>
                        </select>
                        <button class="btn btn-outline-secondary btn-sm" id="toggleView" title="Toggle view">
                            <i class="fas fa-th-large"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Jobs Grid/List -->
        <div class="row" id="discoveryJobsContainer">
            <!-- Jobs will be loaded here -->
            <div class="col-12 text-center py-5">
                <div class="text-muted">
                    <i class="fas fa-search fa-3x mb-3"></i>
                    <h5>Start your job search</h5>
                    <p>Use the filters above to find your perfect job opportunity</p>
                </div>
            </div>
        </div>

        <!-- Load More Button -->
        <div class="row mt-4" id="loadMoreContainer" style="display: none;">
            <div class="col-12 text-center">
                <button class="btn btn-outline-primary" id="loadMoreJobs">
                    <i class="fas fa-plus me-2"></i>Load More Jobs
                </button>
            </div>
        </div>

        <!-- Recommended Jobs Section -->
        <div class="row mt-5">
            <div class="col-12">
                <h4 class="mb-4">Recommended for You</h4>
                <div class="row" id="recommendedJobsContainer">
                    <!-- Recommended jobs will be loaded here -->
                    <div class="col-12 text-center py-3">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
$(document).ready(function() {
    let currentPage = 1;
    let isLoading = false;
    let isListView = false;
    let currentFilters = {};
    
    // Load trending keywords
    loadTrendingKeywords();
    
    // Load recommended jobs
    loadRecommendedJobs();
    
    // Handle form submission
    $('#discoverySearchForm').on('submit', function(e) {
        e.preventDefault();
        performSearch();
    });
    
    // Handle clear search
    $('#clearSearch').click(function() {
        $('#discoverySearchForm')[0].reset();
        clearResults();
    });
    
    // Handle sort change
    $('#sortBy').change(function() {
        if (Object.keys(currentFilters).length > 0) {
            performSearch();
        }
    });
    
    // Handle view toggle
    $('#toggleView').click(function() {
        isListView = !isListView;
        $(this).find('i').toggleClass('fa-th-large fa-list');
        if (Object.keys(currentFilters).length > 0) {
            renderJobs(currentFilters.jobs, true);
        }
    });
    
    // Handle load more
    $('#loadMoreJobs').click(function() {
        if (!isLoading) {
            currentPage++;
            loadMoreJobs();
        }
    });
    
    // Handle refresh
    $('#refreshJobs').click(function() {
        if (Object.keys(currentFilters).length > 0) {
            performSearch();
        }
    });
});

function loadTrendingKeywords() {
    $.ajax({
        url: '{{ url("webapi/jobs/trending-keywords") }}',
        type: 'GET',
        success: function(response) {
            if (response.status === 200 && response.data) {
                const keywordsHtml = response.data.map(keyword => 
                    `<button class="btn btn-sm btn-outline-primary trending-keyword" data-keyword="${keyword}">
                        ${keyword}
                    </button>`
                ).join('');
                $('#trendingKeywords').html(keywordsHtml);
                
                // Handle keyword clicks
                $('.trending-keyword').click(function() {
                    const keyword = $(this).data('keyword');
                    $('#searchKeywords').val(keyword);
                    performSearch();
                });
            } else {
                $('#trendingKeywords').html('<div class="text-muted">No trending keywords available</div>');
            }
        },
        error: function() {
            $('#trendingKeywords').html('<div class="text-muted">Error loading keywords</div>');
        }
    });
}

function loadRecommendedJobs() {
    $.ajax({
        url: '{{ url("webapi/jobs/recommended") }}',
        type: 'GET',
        success: function(response) {
            if (response.status === 200 && response.data && response.data.length > 0) {
                renderRecommendedJobs(response.data);
            } else {
                $('#recommendedJobsContainer').html('<div class="col-12 text-center py-3"><div class="text-muted">No recommendations available</div></div>');
            }
        },
        error: function() {
            $('#recommendedJobsContainer').html('<div class="col-12 text-center py-3"><div class="text-muted">Error loading recommendations</div></div>');
        }
    });
}

function performSearch() {
    const filters = {
        keyword: $('#searchKeywords').val(),
        company: $('#searchCompany').val(),
        location: $('#searchLocation').val(),
        job_type: $('#searchJobType').val(),
        experience: $('#searchExperience').val(),
        min_salary: $('#searchMinSalary').val(),
        posted_within: $('#searchPostedWithin').val(),
        sort_by: $('#sortBy').val(),
        limit: 10,
        offset: 0
    };
    
    currentPage = 1;
    currentFilters = filters;
    
    // Show loading
    $('#discoveryJobsContainer').html(`
        <div class="col-12 text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Searching...</span>
            </div>
            <p class="mt-3 text-muted">Searching for jobs...</p>
        </div>
    `);
    
    $.ajax({
        url: '{{ url("webapi/jobs/all") }}',
        type: 'POST',
        data: filters,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(response) {
            if (response.status === 200 && response.data) {
                currentFilters.jobs = response.data;
                currentFilters.meta = response.meta;
                renderJobs(response.data);
                updateResultsCount(response.meta.total);
                
                // Show/hide load more button
                if (response.meta.has_more) {
                    $('#loadMoreContainer').show();
                } else {
                    $('#loadMoreContainer').hide();
                }
            } else {
                showNoResults();
            }
        },
        error: function() {
            showError();
        }
    });
}

function loadMoreJobs() {
    if (isLoading) return;
    
    isLoading = true;
    $('#loadMoreJobs').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>Loading...');
    
    const filters = {
        ...currentFilters,
        offset: (currentPage - 1) * 10
    };
    
    $.ajax({
        url: '{{ url("webapi/jobs/all") }}',
        type: 'POST',
        data: filters,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(response) {
            if (response.status === 200 && response.data) {
                // Append new jobs to existing ones
                currentFilters.jobs = [...currentFilters.jobs, ...response.data];
                currentFilters.meta = response.meta;
                renderJobs(currentFilters.jobs, true);
                
                // Show/hide load more button
                if (response.meta.has_more) {
                    $('#loadMoreContainer').show();
                } else {
                    $('#loadMoreContainer').hide();
                }
            }
        },
        error: function() {
            showError();
        },
        complete: function() {
            isLoading = false;
            $('#loadMoreJobs').prop('disabled', false).html('<i class="fas fa-plus me-2"></i>Load More Jobs');
        }
    });
}

function renderJobs(jobs, append = false) {
    if (!jobs || jobs.length === 0) {
        showNoResults();
        return;
    }
    
    const jobsHtml = jobs.map(job => renderJobCard(job)).join('');
    
    if (append) {
        $('#discoveryJobsContainer').append(jobsHtml);
    } else {
        $('#discoveryJobsContainer').html(jobsHtml);
    }
}

function renderJobCard(job) {
    const isListClass = isListView ? 'col-12 mb-3' : 'col-md-6 col-lg-4 mb-4';
    const cardClass = isListView ? 'h-100' : 'h-100';
    
    return `
        <div class="${isListClass}">
            <div class="card ${cardClass} job-card" data-job-id="${job.id}">
                <div class="card-body">
                    <div class="d-flex align-items-start mb-3">
                        <div class="flex-shrink-0 me-3">
                            <img src="${job.company_logo || '/assets/images/default-company.png'}" 
                                 class="rounded" width="60" height="60" alt="${job.company_name}">
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="card-title mb-1">
                                <a href="{{ url('jobs/detail') }}/${job.id}" class="text-decoration-none">
                                    ${job.job_title}
                                </a>
                            </h6>
                            <p class="text-muted mb-1">${job.company_name}</p>
                            <div class="d-flex align-items-center text-muted small">
                                <i class="fas fa-map-marker-alt me-1"></i>
                                <span>${job.city}, ${job.state}</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="d-flex flex-wrap gap-1 mb-2">
                            <span class="badge bg-primary">${job.job_type}</span>
                            <span class="badge bg-secondary">${job.work_location_type}</span>
                        </div>
                        <p class="card-text small text-muted">
                            ${job.job_description.substring(0, 100)}...
                        </p>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-success fw-bold">
                            $${job.minimum_salary?.toLocaleString()} - $${job.maximum_salary?.toLocaleString()}
                        </div>
                        <div class="d-flex gap-2">
                            <button class="btn btn-sm btn-outline-secondary save-job" data-job-id="${job.id}">
                                <i class="fas fa-bookmark"></i>
                            </button>
                            <a href="{{ url('jobs/detail') }}/${job.id}" class="btn btn-sm btn-primary">
                                View Details
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

function renderRecommendedJobs(jobs) {
    const jobsHtml = jobs.map(job => renderJobCard(job)).join('');
    $('#recommendedJobsContainer').html(jobsHtml);
}

function updateResultsCount(count) {
    $('#resultsCount').text(count);
}

function showNoResults() {
    $('#discoveryJobsContainer').html(`
        <div class="col-12 text-center py-5">
            <i class="fas fa-search fa-3x text-muted mb-3"></i>
            <h5 class="text-muted">No jobs found</h5>
            <p class="text-muted">Try adjusting your search criteria</p>
        </div>
    `);
    $('#loadMoreContainer').hide();
    updateResultsCount(0);
}

function showError() {
    $('#discoveryJobsContainer').html(`
        <div class="col-12 text-center py-5">
            <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
            <h5 class="text-danger">Error loading jobs</h5>
            <p class="text-muted">Please try again later</p>
        </div>
    `);
    $('#loadMoreContainer').hide();
    updateResultsCount(0);
}

function clearResults() {
    $('#discoveryJobsContainer').html(`
        <div class="col-12 text-center py-5">
            <div class="text-muted">
                <i class="fas fa-search fa-3x mb-3"></i>
                <h5>Start your job search</h5>
                <p>Use the filters above to find your perfect job opportunity</p>
            </div>
        </div>
    `);
    $('#loadMoreContainer').hide();
    updateResultsCount(0);
    currentFilters = {};
}
</script>
@endpush

@endsection
