#!/usr/bin/env python3
"""
rowjobs.site
rowjobs
This script generates a static homepage (index.html) using the provided template.
It reads job metadata from a JSON index file (jobs_index.json) in the job directory,
selects 20 jobs, and renders them into the homepage template using Jinja2.
The homepage includes a client-side search that updates the URL with a "search" query parameter.
 
Usage:
    python generate_homepage.py --jobs_dir /path/to/job --output_dir /path/to/output
"""

import os
import json
import argparse
from jinja2 import Template

def load_jobs(jobs_dir, index_filename="jobs_index.json"):
    """Load job metadata from the JSON index file located in jobs_dir."""
    index_path = os.path.join(jobs_dir, index_filename)
    with open(index_path, "r", encoding="utf-8") as f:
        jobs = json.load(f)
    return jobs

def main(jobs_dir, output_dir):
    # Load all job metadata
    all_jobs = load_jobs(jobs_dir)
    
    # Select 20 jobs (adjust logic if needed)
    selected_jobs = all_jobs[:20]
    
    # Homepage template from above
    template_home = r"""<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Remote Jobs In USA | Find Your Next Remote Job - rowjobs.site</title>
        
        <!-- Internal Styles -->
        <style>
            /* Base Styles */
            :root {
                --blue-500: #3B82F6;
                --blue-600: #2563EB;
                --blue-700: #1D4ED8;
                --blue-800: #1E40AF;
                --gray-50: #F9FAFB;
                --gray-100: #F3F4F6;
                --gray-200: #E5E7EB;
                --gray-300: #D1D5DB;
                --gray-400: #9CA3AF;
                --gray-500: #6B7280;
                --gray-600: #4B5563;
                --gray-700: #374151;
                --gray-800: #1F2937;
                --gray-900: #111827;
            }
            /* Reset */
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                margin: 0;
                font-family: system-ui, -apple-system, sans-serif;
                background-color: var(--gray-50);
                color: var(--gray-900);
                line-height: 1.5;
                min-height: 100vh;
                display: flex;
                flex-direction: column;
            }
            /* Typography */
            h1 {
                font-size: 2.5rem;
                font-weight: 700;
                margin-bottom: 1rem;
            }
            h2 {
                font-size: 1.5rem;
                font-weight: 600;
                margin-bottom: 0.5rem;
            }
            p {
                margin-bottom: 1rem;
            }
            /* Links and Buttons */
            a {
                color: inherit;
                text-decoration: none;
            }
            a:hover {
                text-decoration: none;
            }
            button {
                text-decoration: none;
            }
            .no-results a {
                color: var(--blue-600);
                text-decoration: underline;
            }
            .no-results a:hover {
                color: var(--blue-700);
            }
            /* Layout */
            .container {
                max-width: 1200px;
                margin: 0 auto;
                padding: 0 1rem;
                width: 100%;
            }
            main {
                flex: 1;
                padding: 2rem 0;
            }
            /* Header */
            .header {
                background: linear-gradient(to right, var(--blue-600), var(--blue-800));
                color: white;
                padding: 4rem 1rem;
                text-align: center;
            }
            /* Search Form */
            .search-form {
                max-width: 600px;
                margin: 2rem auto;
                display: flex;
                gap: 0.5rem;
                background: white;
                padding: 0.75rem;
                border-radius: 9999px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .search-input {
                flex: 1;
                padding: 0.75rem 1.5rem;
                border: none;
                border-radius: 9999px;
                outline: none;
                font-size: 1rem;
            }
            .search-button {
                padding: 0.75rem 2rem;
                background: var(--blue-600);
                color: white;
                border: none;
                border-radius: 9999px;
                cursor: pointer;
                transition: all 0.3s ease;
                font-size: 1rem;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
            .search-button:hover {
                background: var(--blue-700);
                transform: translateY(-1px);
            }
            /* Jobs Grid */
            .jobs-grid {
                display: grid;
                gap: 1.5rem;
                margin-bottom: 2rem;
            }
            @media (min-width: 640px) {
                .jobs-grid {
                    grid-template-columns: repeat(2, 1fr);
                }
            }
            /* Job Card */
            .job-card {
                background: white;
                border-radius: 1rem;
                padding: 1.5rem;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
                transition: all 0.3s ease;
                display: block;
                border: 1px solid var(--gray-300);
            }
            .job-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                border-color: var(--blue-500);
            }
            .job-title {
                font-size: 1.25rem;
                font-weight: 600;
                color: var(--gray-900);
                margin-bottom: 0.75rem;
                line-height: 1.4;
            }
            .job-meta {
                display: flex;
                gap: 1rem;
                color: var(--gray-600);
                font-size: 0.875rem;
                align-items: center;
            }
            /* Pagination */
            .pagination {
                display: flex;
                justify-content: center;
                gap: 1rem;
                margin-top: 2rem;
            }
            .pagination-button {
                padding: 0.75rem 2rem;
                border-radius: 9999px;
                font-weight: 500;
                transition: all 0.3s ease;
            }
            .pagination-button.next {
                background: var(--blue-600);
                color: white;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            .pagination-button.next:hover {
                background: var(--blue-700);
                transform: translateY(-1px);
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .pagination-button.prev {
                background: white;
                color: var(--gray-700);
                border: 1px solid var(--gray-300);
            }
            .pagination-button.prev:hover {
                background: var(--gray-50);
                border-color: var(--gray-400);
            }
            /* No Results */
            .no-results {
                text-align: center;
                padding: 3rem 1rem;
                background: white;
                border-radius: 1rem;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            }
            .no-results p {
                color: var(--gray-600);
                margin-bottom: 1rem;
            }
            .no-results a {
                color: var(--blue-600);
                text-decoration: underline;
            }
            .no-results a:hover {
                color: var(--blue-700);
            }
            /* Footer */
            footer {
                background: white;
                border-top: 1px solid var(--gray-300);
                padding: 2rem 0;
                margin-top: auto;
                text-align: center;
                color: var(--gray-600);
            }
            /* Icons */
            .icon {
                width: 1.25em;
                height: 1.25em;
                vertical-align: -0.125em;
                fill: currentColor;
            }
            /* Job Categories Styles */
            .job-categories {
                margin-top: 2rem;
                padding: 1rem;
                text-align: center;
            }
            .category-link {
                display: inline-block;
                padding: 0.5rem 1rem;
                background: rgba(255, 255, 255, 0.1);
                color: white;
                border-radius: 9999px;
                font-size: 0.875rem;
                transition: all 0.3s ease;
                border: 1px solid rgba(255, 255, 255, 0.2);
            }
            .category-link:hover {
                background: rgba(255, 255, 255, 0.2);
                transform: translateY(-1px);
                border-color: rgba(255, 255, 255, 0.3);
            }
            @media (max-width: 640px) {
                .job-categories {
                    margin-top: 1.5rem;
                }
                .category-link {
                    font-size: 0.75rem;
                    padding: 0.375rem 0.75rem;
                }
            }
        </style>

        <!-- SVG Icons -->
        <svg style="display: none;">
            <symbol id="icon-search" viewBox="0 0 24 24">
                <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
            </symbol>
        </svg>

        <!-- SEO Meta Tags -->
        <meta name="description" content="rowjobs Find the best remote jobs in the USA. Browse through hundreds of work-from-home opportunities across various industries and skill levels.">
        <meta name="keywords" content="remote jobs, work from home, USA jobs, remote work, remote career, job search">
        <meta name="robots" content="index, follow">
        <meta name="author" content="rowjobs">
        
        <!-- Open Graph Tags -->
        <meta property="og:title" content="Remote Jobs In USA | Find Your Next Remote Job">
        <meta property="og:description" content="Find the best remote jobs in the USA. Browse through hundreds of work-from-home opportunities across various industries and skill levels.">
        <meta property="og:type" content="website">
        <meta property="og:url" content="https://rowjobs.site">
        <meta property="og:site_name" content="rowjobs">
        
        <!-- Canonical URL -->
        <link rel="canonical" href="https://rowjobs.site">
        <!-- Search results are not canonical -->
        <meta name="robots" content="noindex, follow">
    </head>
    <body>
        <header class="header">
            <div class="container">
                <a href="/" aria-label="Remote Jobs USA - Home">
                    <svg class="icon" aria-hidden="true">
                        <!-- Include your laptop-house icon here -->
                        <use href="#icon-laptop-house"/>
                    </svg>
                    <span>Remote Jobs USA - rowjobs</span>
                </a>
                <p>Find your next remote opportunity</p>
                
                <form id="searchForm" action="/" method="GET" class="search-form">
                    <input 
                        type="search" 
                        name="search" 
                        placeholder="Search remote jobs..." 
                        value=""
                        class="search-input"
                    >
                    <button type="submit" class="search-button">
                        <svg class="icon"><use href="#icon-search"/></svg>
                        Search
                    </button>
                </form>

                <!-- Popular Job Categories -->
                <div class="job-categories">
                    <h2 class="text-xl font-semibold text-white mb-4">Popular Remote Job Categories</h2>
                    <div class="flex flex-wrap justify-center gap-3">
                        <a href="/?search=Data+entry+jobs" class="category-link">Data Entry Jobs</a>
                        <a href="/?search=Customer+service" class="category-link">Customer Service</a>
                        <a href="/?search=Software+developer" class="category-link">Software Development</a>
                        <a href="/?search=Virtual+assistant" class="category-link">Virtual Assistant</a>
                        <a href="/?search=Project+manager" class="category-link">Project Management</a>
                        <a href="/?search=Content+writer" class="category-link">Content Writing</a>
                        <a href="/?search=Digital+marketing" class="category-link">Digital Marketing</a>
                        <a href="/?search=Graphic+designer" class="category-link">Graphic Design</a>
                        <a href="/?search=Accounting" class="category-link">Accounting</a>
                        <a href="/?search=Sales+representative" class="category-link">Sales</a>
                    </div>
                </div>
            </div>
        </header>

        <main class="container">
            <div class="jobs-grid">
                {% for job in jobs %}
                <a href="{{ job.job_url }}" class="job-card">
                    <h2 class="job-title">{{ job.job_title }}</h2>
                    <div class="job-meta">
                        <span>{{ job.location }}</span>
                        <span>{{ job.employment_type }}</span>
                    </div>
                </a>
                {% endfor %}
            </div>
            
            <div class="pagination">
                <!-- Pagination links can be inserted here if needed -->
            </div>
        </main>

        <footer>
            <div class="container">
                <p>Find the best remote jobs in USA - rowjobs</p>
            </div>
        </footer>

        <!-- Client-Side Search Script -->
        <script>
            (function () {
                // Updated: Use the JSON file only to perform search from the 'job' directory.
                const jobsIndexUrl = 'job/jobs_index.json';
                let allJobs = [];
                const jobsGrid = document.querySelector('.jobs-grid');
                const searchForm = document.querySelector('#searchForm');
                const searchInput = document.querySelector('.search-input');

                // Helper: update the URL with the search query parameter (using History API)
                function updateURLParameter(query) {
                    const url = new URL(window.location);
                    if (query) {
                        url.searchParams.set('search', query);
                    } else {
                        url.searchParams.delete('search');
                    }
                    window.history.pushState({}, '', url);
                }

                // Render job cards based on the provided jobs array.
                function renderJobs(jobs) {
                    jobsGrid.innerHTML = '';
                    if (jobs.length === 0) {
                        const noResults = document.createElement('div');
                        noResults.className = 'no-results';
                        noResults.innerHTML = '<p>No jobs found matching your search.</p>';
                        jobsGrid.appendChild(noResults);
                        return;
                    }
                    jobs.forEach(job => {
                        const card = document.createElement('a');
                        card.href = job.job_url;
                        card.className = 'job-card';
                        card.innerHTML = `
                            <h2 class="job-title">${job.job_title}</h2>
                            <div class="job-meta">
                                <span>${job.location}</span>
                                <span>${job.employment_type}</span>
                            </div>
                        `;
                        jobsGrid.appendChild(card);
                    });
                }

                // Load all jobs from the JSON index file.
                function loadJobs() {
                    fetch(jobsIndexUrl)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok: ' + response.status);
                            }
                            return response.json();
                        })
                        .then(data => {
                            allJobs = data;
                            // On initial load, check if a search query exists in the URL.
                            const params = new URLSearchParams(window.location.search);
                            const initialQuery = params.get('search') || "";
                            searchInput.value = initialQuery;
                            const filteredJobs = performSearch(initialQuery);
                            renderJobs(filteredJobs);
                        })
                        .catch(error => {
                            console.error('Error loading jobs index:', error);
                        });
                }

                // Filter jobs based on the search query.
                // The filter checks both the job title and the job_url (slug) for the query.
                // Only return the first 20 matches.
                function performSearch(query) {
                    const q = (query || searchInput.value).toLowerCase().trim();
                    return allJobs.filter(job =>
                        job.job_title.toLowerCase().includes(q) ||
                        job.job_url.toLowerCase().includes(q)
                    ).slice(0, 20);
                }

                // Event listener: when the form is submitted, update URL and render filtered jobs.
                searchForm.addEventListener('submit', function (event) {
                    event.preventDefault();
                    const query = searchInput.value;
                    updateURLParameter(query);
                    renderJobs(performSearch(query));
                });

                // Live filtering as the user types, also update the URL.
                searchInput.addEventListener('input', function () {
                    const query = searchInput.value;
                    updateURLParameter(query);
                    renderJobs(performSearch(query));
                });

                // Initial load.
                loadJobs();
            })();
        </script>
    </body>
</html>
"""

    # Render the homepage template with the selected 20 jobs.
    template = Template(template_home)
    rendered_html = template.render(jobs=selected_jobs)

    # Create the output directory if it does not exist.
    os.makedirs(output_dir, exist_ok=True)
    output_path = os.path.join(output_dir, "index.html")
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(rendered_html)
    
    print(f"Homepage generated at: {output_path}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Generate homepage (index.html) using 20 jobs from the job directory and include search functionality with URL parameters."
    )
    parser.add_argument("--jobs_dir", required=True, help="Path to the job directory (should contain jobs_index.json)")
    parser.add_argument("--output_dir", required=True, help="Output directory for the generated index.html")
    args = parser.parse_args()
    main(args.jobs_dir, args.output_dir)
