---
/**
 * Preview Site Route
 * Shows all pages for a site in preview mode
 */

import { getDirectusClient, readItems } from '@/lib/directus/client';

const { siteId } = Astro.params;

if (!siteId) {
    return Astro.redirect('/admin/sites');
}

interface Site {
    id: string;
    name: string;
    domain: string;
    status: string;
    date_created: string;
}

interface Page {
    id: string;
    title: string;
    status: string;
    permalink: string;
    slug: string;
    seo_description: string;
}

let site: Site | null = null;
let pages: Page[] = [];
let error: string | null = null;

try {
    const client = getDirectusClient();
    
    // Fetch site
    const siteResult = await client.request(readItems('sites', {
        filter: { id: { _eq: siteId } },
        limit: 1
    }));
    site = siteResult[0] as Site;
    
    // Fetch pages for this site
    // Note: directus-shim buildWhere supports _eq
    const pagesResult = await client.request(readItems('pages', {
        filter: { site: { _eq: siteId } },
        limit: -1
    }));
    pages = pagesResult as Page[];
    
} catch (err) {
    error = err instanceof Error ? err.message : 'Failed to load site';
    console.error('Preview error:', err);
}

if (!site && !error) {
    return Astro.redirect('/admin/sites');
}
---

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preview: {site?.name || 'Site'}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #0a0a0a;
            color: #fff;
        }
        
        .preview-banner {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
        }
        
        .banner-left {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .badge {
            background: rgba(255,255,255,0.2);
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            font-weight: 500;
            transition: background 0.2s;
        }
        
        .btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        
        .site-header {
            background: #111;
            border-radius: 0.5rem;
            padding: 2rem;
            margin-bottom: 2rem;
            border: 1px solid #222;
        }
        
        .site-header h1 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }
        
        .site-meta {
            color: #888;
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }
        
        .pages-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        
        .page-card {
            background: #111;
            border: 1px solid #222;
            border-radius: 0.5rem;
            padding: 1.5rem;
            transition: all 0.2s;
            cursor: pointer;
        }
        
        .page-card:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
        }
        
        .page-card h3 {
            font-size: 1.25rem;
            margin-bottom: 0.5rem;
            color: #fff;
        }
        
        .page-card p {
            color: #888;
            font-size: 0.875rem;
            margin-bottom: 1rem;
        }
        
        .page-status {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-published {
            background: #10b981;
            color: white;
        }
        
        .status-draft {
            background: #6b7280;
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            color: #666;
        }
        
        .empty-state svg {
            width: 4rem;
            height: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }
    </style>
</head>
<body>
    <!-- Preview Banner -->
    <div class="preview-banner">
        <div class="banner-left">
            <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
            </svg>
            <span style="font-weight: 600;">SITE PREVIEW</span>
            {site && <span class="badge">{site.status || 'Active'}</span>}
        </div>
        <button class="btn" onclick="window.close()">Close Preview</button>
    </div>

    <!-- Site Content -->
    <div class="container">
        {error ? (
            <div style="background: #fee; border: 1px solid #fcc; color: #c00; padding: 20px; border-radius: 8px;">
                <h2>Error Loading Site</h2>
                <p>{error}</p>
            </div>
        ) : site ? (
            <>
                <div class="site-header">
                    <h1>{site.name}</h1>
                    <div class="site-meta">
                        <span>🌐 {site.domain}</span>
                        <span>📄 {pages.length} pages</span>
                        {site.date_created && (
                            <span>📅 Created {new Date(site.date_created).toLocaleDateString()}</span>
                        )}
                    </div>
                </div>

                <h2 style="margin-bottom: 1.5rem; font-size: 1.5rem;">Pages</h2>

                {pages.length > 0 ? (
                    <div class="pages-grid">
                        {pages.map((page) => (
                            <div class="page-card" onclick={`window.open('/preview/page/${page.id}', '_blank')`}>
                                <h3>{page.title}</h3>
                                <p>{page.seo_description || 'No description'}</p>
                                <div style="display: flex; justify-between; align-items: center;">
                                    <span class={`page-status ${page.status === 'published' ? 'status-published' : 'status-draft'}`}>
                                        {page.status || 'draft'}
                                    </span>
                                    <span style="color: #666; font-size: 0.75rem;">
                                        /{page.permalink || page.slug}
                                    </span>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div class="empty-state">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        <p>No pages created yet for this site.</p>
                        <p style="margin-top: 0.5rem; font-size: 0.875rem;">
                            <a href={`/admin/sites/${site.id}`} style="color: #667eea;">Create your first page →</a>
                        </p>
                    </div>
                )}
            </>
        ) : null}
    </div>
</body>
</html>
