<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chicago Past</title>
    <link rel="stylesheet" href="/styles.css?t=1741966948">
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="icon" href="/favicon.ico" sizes="any">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body>
    <div class="header">
        <h1><a href="/" style="text-decoration: none; color: inherit;">Chicago Past</a></h1>
        <div class="nav-menu">
            <a href="/">home</a>
            <a href="/info">info</a>
            <a href="/archive">archive</a>
        </div>
    </div>
    
    <div id="app">
        <!-- Content will be loaded here by JavaScript -->
        <div style="text-align: center; padding: 50px;">
            Loading...
        </div>
    </div>

    <script>
        // Configuration
        const POSTS_PER_PAGE = 15;
        const DATA_URL = '/data/posts.json';
        
        // State
        let allPosts = [];
        let currentPage = 1;
        let currentTag = null;
        let currentPost = null;
        
        // Helper functions
        function formatDate(dateString) {
            const options = { year: 'numeric', month: 'long', day: 'numeric' };
            return new Date(dateString).toLocaleDateString(undefined, options);
        }
        
        function getPageCount(postsArray) {
            return Math.ceil(postsArray.length / POSTS_PER_PAGE);
        }
        
        function getPaginatedPosts(postsArray, page) {
            const startIndex = (page - 1) * POSTS_PER_PAGE;
            return postsArray.slice(startIndex, startIndex + POSTS_PER_PAGE);
        }
        
        function getPostsWithTag(tag) {
            // Decode the URL-encoded tag (e.g., "Lake%20Shore%20Drive" to "Lake Shore Drive")
            const decodedTag = decodeURIComponent(tag);
            return allPosts.filter(post => post.tags && post.tags.includes(decodedTag));
        }
        
        function getPostById(id) {
            return allPosts.find(post => post.postid === id);
        }
        
        // Rendering functions
        function renderPosts(posts) {
            return `
                <div class="posts">
                    ${posts.map(post => `
                        <div class="post">
                            ${post.image ? `
                            ${post.source ? `
                                <a href="${post.source}" class="external-link" target="_blank">
                            ` : ''}
                            <img src="/media/${post.image}.jpg" alt="${post.image}" class="post-image">
                            ${post.source ? `
                                </a>
                            ` : ''}
                            ` : ''}
                            <div class="post-content">
                                <!--<div class="post-date">${formatDate(post.date)}</div>-->
                                ${post.description ? `
                                <div class="post-description">${post.description.substring(0, 1000)}</div>
                                ` : ''}
                                <div class="post-tags">
                                    ${post.tags.map(tag => `
                                        <a href="/tagged/${encodeURIComponent(tag)}" class="tag">#${tag}</a>
                                    `).join('')}
                                </div>
                                <p class="post-title">
                                    <a href="/post/${post.postid}" style="text-decoration: none; color: inherit;">
                                        &infin;
                                    </a>
                                </p>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        }
        
        function renderPagination(currentPage, totalPages, baseUrl) {
            let pagination = '<div class="pagination">';
            
            // Previous button
            if (currentPage > 1) {
                pagination += `<a href="${baseUrl}/${currentPage - 1}">&laquo; Previous</a>`;
            }
            
            // Determine which page numbers to show
            const pageBuffer = 5; // Show 5 pages before and after current page
            let startPage = Math.max(1, currentPage - pageBuffer);
            let endPage = Math.min(totalPages, currentPage + pageBuffer);
            
            // Add first page and ellipsis if needed
            if (startPage > 1) {
                pagination += `<a href="${baseUrl}/1">1</a>`;
                if (startPage > 2) {
                    pagination += `<span style="margin: 0 5px;">...</span>`;
                }
            }
            
            // Page numbers
            for (let i = startPage; i <= endPage; i++) {
                if (i === currentPage) {
                    pagination += `<a class="active" href="${baseUrl}/${i}">${i}</a>`;
                } else {
                    pagination += `<a href="${baseUrl}/${i}">${i}</a>`;
                }
            }
            
            // Add last page and ellipsis if needed
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    pagination += `<span style="margin: 0 5px;">...</span>`;
                }
                pagination += `<a href="${baseUrl}/${totalPages}">${totalPages}</a>`;
            }
            
            // Next button
            if (currentPage < totalPages) {
                pagination += `<a href="${baseUrl}/${currentPage + 1}">Next &raquo;</a>`;
            }
            
            pagination += '</div>';
            return pagination;
        }
        
        function renderHomePage(page = 1) {
            currentPage = parseInt(page);
            const pageCount = getPageCount(allPosts);
            const posts = getPaginatedPosts(allPosts, currentPage);
            
            return `
                ${renderPosts(posts)}
                ${renderPagination(currentPage, pageCount, '/page')}
            `;
        }
        
        function renderTagPage(tag, page = 1) {
            currentTag = tag;
            currentPage = parseInt(page);
            
            const postsWithTag = getPostsWithTag(tag);
            const pageCount = getPageCount(postsWithTag);
            const posts = getPaginatedPosts(postsWithTag, currentPage);
            
            // Display the decoded tag name
            const decodedTag = decodeURIComponent(tag);
            
            return `
                <div class="tag-header">
                    <!--<a href="/" class="back-link">← Back to all posts</a>-->
                    <h2>Tagged: ${decodedTag}</h2>
                </div>
                ${renderPosts(posts)}
                ${renderPagination(currentPage, pageCount, `/tagged/${tag}`)}
            `;
        }
        
        function renderSinglePost(postId) {
            const post = getPostById(postId);
            
            if (!post) {
                return `
                    <div style="text-align: center; padding: 50px;">
                        <h2>Post not found</h2>
                        <a href="/" class="back-link">← Back to all posts</a>
                    </div>
                `;
            }
            
            return `
                <div class="post">
                    <!--<a href="/" class="back-link">← Back to all posts</a>-->
                    <!--<h1>${post.postid}</h1>-->
                    <!--<div class="post-date">${formatDate(post.date)}</div>-->
                    ${post.image ? `
                    ${post.source ? `
                        <a href="${post.source}" class="external-link" target="_blank">
                    ` : ''}
                    <img src="/media/${post.image}.jpg" alt="${post.image}" class="post-image">
                    ${post.source ? `
                        </a>
                    ` : ''}
                    ` : ''}
                    <div class="post-content">
                    <div class="post-description">
                        ${post.description}
                    </div>
                    <!--${post.source ? `
                        <a href="${post.source}" class="external-link" target="_blank">
                            View source →
                        </a>
                    ` : ''}-->
                    <div class="post-tags">
                        ${post.tags.map(tag => `
                            <a href="/tagged/${encodeURIComponent(tag)}" class="tag">#${tag}</a>
                        `).join('')}
                    </div>
                    </div>
                </div>
            `;
        }

        // New function to render the info page
        function renderInfoPage() {
            return `
                <div class="info-container">
                    <div class="info-section">
                        <p>
                            Chicago Past collects large photos of historic Chicago.
                        </p>
                        <p>
                            <a href="https://schroeder.me" target="_blank">John</a> is the person behind it.
                        </p>
                    </div>

                    <div class="info-section">
                        <p>
                            Other sites you may enjoy<br/>
                            <a href="http://chicagoscreenshots.com/">Chicago Screenshots</a><br/>
                            <a href="http://nycpast.tumblr.com/">NYC Past</a><br/>
                            <a href="http://calumet412.com/">Calumet 412</a><br/>
                            <a href="http://themanonfive.com/">The Man On Five</a><br/>
                        </p>
                    </div>
                </div>
            `;
        }

        // New function to render the archive page
        function renderArchivePage() {
            return `
                <div class="archive-container">
                    <!--<h2>Image Archive</h2>-->
                    <div id="archive-grid" class="archive-grid">
                        <!-- Content will be loaded here -->
                        <div style="text-align: center; padding: 50px;">
                            Loading images...
                        </div>
                    </div>
                </div>
            `;
        }

        // Modified function to load archive content
        function loadArchiveContent() {
            const archiveGrid = document.getElementById('archive-grid');
            if (!archiveGrid) return;

            try {
                // Filter posts that have an image and sort by date (newest first)
                const postsWithImages = allPosts
                    .filter(post => post.image)
                    .sort((a, b) => new Date(b.date) - new Date(a.date));
                
                if (postsWithImages.length === 0) {
                    archiveGrid.innerHTML = `
                        <div style="text-align: center; padding: 50px;">
                            <p>No images found in the archive.</p>
                        </div>
                    `;
                    return;
                }
                
                let gridHTML = '';
                
                postsWithImages.forEach(post => {
                    // For each post with an image, create a grid item
                    gridHTML += `
                        <a href="/post/${post.postid}" class="archive-item">
                            <img src="/media/${post.image}-m.jpg" alt="${post.image || 'Chicago Past Archive Image'}">
                            <div class="archive-item-overlay">
                                <div>${formatDate(post.date)}</div>
                                ${post.tags ? `<div>${post.tags[0]}</div>` : ''}
                            </div>
                        </a>
                    `;
                });
                
                archiveGrid.innerHTML = gridHTML;
            } catch (error) {
                console.error('Error loading archive content:', error);
                archiveGrid.innerHTML = `
                    <div style="text-align: center; padding: 50px;">
                        <h2>Error loading content</h2>
                        <p>Please try again later.</p>
                    </div>
                `;
            }
        }
        
        // Router
        function parseUrl() {
            const path = window.location.pathname;
            
            if (path === '/' || path === '/index.html') {
                return { type: 'home', page: 1 };
            }
            
            const pageMatch = path.match(/^\/page\/(\d+)$/);
            if (pageMatch) {
                return { type: 'home', page: parseInt(pageMatch[1]) };
            }
            
            const postMatch = path.match(/^\/post\/([^\/]+)$/);
            if (postMatch) {
                return { type: 'post', id: postMatch[1] };
            }
            
            const tagMatch = path.match(/^\/tagged\/([^\/]+)$/);
            if (tagMatch) {
                return { type: 'tag', tag: tagMatch[1], page: 1 };
            }
            
            const tagPageMatch = path.match(/^\/tagged\/([^\/]+)\/(\d+)$/);
            if (tagPageMatch) {
                return { 
                    type: 'tag', 
                    tag: tagPageMatch[1], 
                    page: parseInt(tagPageMatch[2]) 
                };
            }

            // Added routes for info and archive pages
            if (path === '/info' || path === '/info/') {
                return { type: 'info' };
            }

            if (path === '/archive' || path === '/archive/') {
                return { type: 'archive' };
            }
            
            return { type: '404' };
        }
        
        function renderPage() {
            const route = parseUrl();
            const app = document.getElementById('app');
            
            switch (route.type) {
                case 'home':
                    app.innerHTML = renderHomePage(route.page);
                    break;
                case 'post':
                    app.innerHTML = renderSinglePost(route.id);
                    break;
                case 'tag':
                    app.innerHTML = renderTagPage(route.tag, route.page);
                    break;
                case 'info':
                    app.innerHTML = renderInfoPage();
                    break;
                case 'archive':
                    app.innerHTML = renderArchivePage();
                    // Load archive content after rendering the page
                    setTimeout(loadArchiveContent, 0);
                    break;
                case '404':
                    app.innerHTML = `
                        <div style="text-align: center; padding: 50px;">
                            <h2>Page not found</h2>
                            <a href="/" class="back-link">← Back to home</a>
                        </div>
                    `;
                    break;
            }
        }
        
        // Main initialization
        async function init() {
            try {
                const response = await fetch(DATA_URL);
                const data = await response.json();
                
                // Sort posts by date (newest first)
                allPosts = data.sort((a, b) => new Date(b.date) - new Date(a.date));
                
                // Render the page based on the URL
                renderPage();
                
                // Handle navigation without page reload
                window.addEventListener('popstate', renderPage);
                
                // Intercept link clicks to use History API
                document.addEventListener('click', function(e) {
                    if (e.target.tagName === 'A') {
                        const href = e.target.getAttribute('href');
                        
                        // Only handle internal links
                        if (href && href.startsWith('/') && !e.target.getAttribute('target')) {
                            e.preventDefault();
                            history.pushState(null, null, href);
                            renderPage();
                        }
                    }
                });
                
            } catch (error) {
                console.error('Error loading posts:', error);
                document.getElementById('app').innerHTML = `
                    <div style="text-align: center; padding: 50px;">
                        <h2>Error loading content</h2>
                        <p>Please try again later.</p>
                    </div>
                `;
            }
        }
        
        // Start the app
        init();
    </script>

<!-- Default Statcounter code for Chicagopast
    http://chicagopast.com -->
    <script type="text/javascript">
    var sc_project=7627026; 
    var sc_invisible=1; 
    var sc_security="ad2a535b"; 
    </script>
    <script type="text/javascript"
    src="https://www.statcounter.com/counter/counter.js"
    async></script>
    <!-- End of Statcounter Code -->

</body>
</html>
