<?php
/**
 * FantasyXXX.ai - Anonymous Landing Page
 * Straight copy of members/dashboard.php adapted for anonymous users
 */

if (!defined('SECURE_ACCESS')) {
    define('SECURE_ACCESS', true);
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config.php';

// Initialize anonymous session (sets anon_username, anon_email, anon_tokens_remaining, anon_key)
require_once 'includes/anonymous_session.php';

// Capture affiliate ref code from URL and store in session
$ref_code = isset($_GET['ref']) ? preg_replace('/[^A-Za-z0-9]/', '', $_GET['ref']) : '';
if ($ref_code) {
    $_SESSION['affiliate_ref'] = $ref_code;

    // Determine environment-appropriate cookie domain and affiliate API URL
    $current_host = $_SERVER['HTTP_HOST'] ?? '';
    $cookie_domain = '.fantasyxxx.ai';
    $affiliate_api_url = 'https://affiliates.fantasyxxx.ai/api/events/funnel.php';
    
    if (strpos($current_host, 'devfantasyxxxai.detodoenlaweb.com') !== false) {
        $cookie_domain = '.detodoenlaweb.com';
        $affiliate_api_url = 'https://affiliatesdevfantasyxxxai.detodoenlaweb.com/api/events/funnel.php';
    }

    $visitor_id = isset($_COOKIE['aff_visitor_id']) ? $_COOKIE['aff_visitor_id'] : bin2hex(random_bytes(16));
    if (!isset($_COOKIE['aff_visitor_id'])) {
        setcookie('aff_visitor_id', $visitor_id, time() + (86400 * 30), '/', $cookie_domain, true, true);
    }
    setcookie('aff_ref', $ref_code, time() + (86400 * 30), '/', $cookie_domain, true, true);

    $tracking_data = [
        'ref'          => $ref_code,
        'event_type'   => 'page_view',
        'event_name'   => 'landing_page',
        'visitor_id'   => $visitor_id,
        'page_url'     => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
        'referrer_url' => $_SERVER['HTTP_REFERER'] ?? null,
        'ip'           => $_SERVER['REMOTE_ADDR'] ?? null,
        'user_agent'   => $_SERVER['HTTP_USER_AGENT'] ?? null,
    ];

    $ch = curl_init($affiliate_api_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($tracking_data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    @curl_exec($ch);
    curl_close($ch);
}

// Build ref param for all JOIN_URL links
$ref_param = '';
if (isset($_SESSION['affiliate_ref']) && !empty($_SESSION['affiliate_ref'])) {
    $ref_param = '?ref=' . urlencode($_SESSION['affiliate_ref']);
}
$join_url_with_ref = rtrim(JOIN_URL, '/') . '/pp1/' . $ref_param;

// Helper function (same as dashboard.php)
function clean_model_name($name) {
    return trim(preg_replace('/\s+/', ' ', $name));
}

// Generate SEO-friendly chat URL slug from model name
function get_chat_url($model_name, $base_url = '') {
    // Convert model name to slug: "Sofia" -> "sofia_ai"
    $slug = strtolower(str_replace(' ', '_', trim($model_name))) . '_ai';
    return ($base_url ?: BASE_URL) . 'chat/' . $slug;
}

function render_communication_content($content) {
    $content = preg_replace('/^# (.*?)$/m', '<h1 style="margin: 1rem 0 0.5rem 0; font-size: 1.5rem; font-weight: bold;">$1</h1>', $content);
    $content = preg_replace('/^## (.*?)$/m', '<h2 style="margin: 1rem 0 0.5rem 0; font-size: 1.25rem; font-weight: bold;">$1</h2>', $content);
    $content = preg_replace('/^### (.*?)$/m', '<h3 style="margin: 1rem 0 0.5rem 0; font-size: 1.1rem; font-weight: bold;">$1</h3>', $content);
    $content = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $content);
    $content = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $content);
    $content = preg_replace('/\[(.*?)\]\((.*?)\)/', '<a href="$2" style="color: var(--primary); text-decoration: underline;">$1</a>', $content);

    return nl2br($content);
}

$cms_images = [];
$communication = null;

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch active communication (same source as members dashboard)
    $communication_stmt = $pdo->prepare("
        SELECT communication_id, title, content
        FROM communications
        WHERE is_active = 1
        ORDER BY display_order ASC
        LIMIT 1
    ");
    $communication_stmt->execute();
    $communication = $communication_stmt->fetch(PDO::FETCH_ASSOC);

    // Get CMS images and videos for SEO landing page
    $cms_stmt = $pdo->query("
        SELECT DISTINCT ci.id, ci.model_name, ci.filename, ci.content_type, ci.image_url, ci.thumbnail_url, ci.video_url, ci.created_at, 
               (SELECT m.model_id FROM models m WHERE BINARY m.name = BINARY ci.model_name LIMIT 1) as model_id
        FROM index_cms_images ci
        WHERE ci.is_active = 1
        ORDER BY ci.sort_order ASC, ci.created_at DESC
    ");
    $cms_images = $cms_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get CMS content for About section
    $content_stmt = $pdo->prepare("SELECT content_html FROM cms_content WHERE content_key = 'about_fantasyxxx' AND is_active = 1");
    $content_stmt->execute();
    $content_data = $content_stmt->fetch(PDO::FETCH_ASSOC);
    $about_content = $content_data ? $content_data['content_html'] : '';

} catch (PDOException $e) {
    // Silently fail - use defaults
    $about_content = '';
}

require_once 'includes/layout_helper_anonymous.php';

start_content();
?>

<!-- Age Gate Modal (preserved from original index.php) -->
<div id="fx-agegate" role="dialog" aria-modal="true" aria-labelledby="fx-age-title" aria-hidden="false">
    <div class="fx-card" role="document" tabindex="-1">
        <div class="fx-brand">
            <span class="fx-wordmark" style="display:flex;align-items:center;gap:0.5rem;">
                <img src="<?php echo BASE_URL; ?>images/fantasy_heart_icon-2.png" alt="FantasyXXX.ai"
                     style="width:1.4em;height:1.4em;object-fit:contain;mix-blend-mode:screen;filter:contrast(1.5);vertical-align:-0.35em;margin-right:0.1em;" />
                Fantasy<span class="pink">XXX</span>.ai
            </span>
        </div>
        <h1 id="fx-age-title">Adults Only (18+)</h1>
        <p class="fx-sub">
            This site contains sexually explicit content intended only for adults. By clicking <strong>Enter</strong>,
            you confirm that you are at least 18 years old (or the age of majority in your jurisdiction) and agree to our
            <a href="/terms" rel="nofollow">Terms</a> and <a href="/privacy" rel="nofollow">Privacy Policy</a>.
        </p>
        <label class="fx-row">
            <input id="fx-remember" class="fx-check" type="checkbox" checked>
            Remember my choice for 30 days
        </label>
        <div class="fx-actions">
            <button id="fx-enter" class="fx-btn fx-btn-primary" type="button">Enter — I am 18+</button>
            <button id="fx-leave" class="fx-btn fx-btn-secondary" type="button">Leave</button>
        </div>
        <p class="fx-row" style="margin-top:14px;">
            If you are under 18 or it is illegal to view adult material in your area, do not enter.
        </p>
    </div>
</div>

<style>
#fx-agegate[aria-hidden="true"] { display: none; }
#fx-agegate {
    position: fixed; inset: 0; z-index: 99999;
    display: grid; place-items: center;
    background: rgba(0,0,0,0.85);
    backdrop-filter: blur(4px);
}
.fx-card {
    width: min(92vw, 500px);
    background: linear-gradient(180deg, #151633 0%, #0f1020 100%);
    color: #fff; border-radius: 18px;
    box-shadow: 0 10px 40px rgba(0,0,0,.6), inset 0 0 0 1px rgba(255,255,255,.06);
    padding: 28px; border: 1px solid #334155;
}
.fx-brand  { display:flex; align-items:center; justify-content:center; margin-bottom:16px; }
.fx-wordmark { font-size:28px; font-weight:800; color:#fff; letter-spacing:-0.5px; }
.pink { color: #ec4899; }
#fx-age-title { font-size:24px; font-weight:700; margin:0 0 12px; text-align:center; }
.fx-sub  { font-size:14px; line-height:1.6; color:#cbd5e1; margin-bottom:16px; text-align:center; }
.fx-sub a { color:#93c5fd; text-decoration:none; border-bottom:1px solid #93c5fd; }
.fx-actions { display:flex; gap:12px; margin-top:20px; }
.fx-btn { flex:1; padding:12px 20px; border-radius:8px; font-weight:600; cursor:pointer; transition:all 0.2s; border:none; font-size:15px; }
.fx-btn-primary { background-color:#3b82f6; color:white; }
.fx-btn-primary:hover { background-color:#2563eb; transform:translateY(-1px); }
.fx-btn-secondary { background:#1e293b; color:#e2e8f0; border:1px solid #334155; }
.fx-btn-secondary:hover { background:#334155; }
.fx-row { display:flex; align-items:center; gap:10px; margin-top:10px; font-size:13px; color:#94a3b8; }
.fx-check { accent-color:#3b82f6; }
body.fx-lock { overflow:hidden; }
/* iPhone 14+ and mobile responsive fixes - prevent horizontal scroll */
html, body {
    overflow-x: hidden !important;
    max-width: 100vw;
}

/* Prevent any element from causing horizontal scroll */
.main, .layout, .card, .models-grid {
    max-width: 100%;
    box-sizing: border-box;
}

/* Models grid - constrained to main column, responsive_global.css handles breakpoints */
.models-grid {
    display: grid;
    gap: 16px;
    width: 100%;
    box-sizing: border-box;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}


.model-card > div[style*="aspect-ratio:1"] img {
    width: 100% !important;
    height: 100% !important;
}

/* Tablet and smaller screens */
@media (max-width: 768px) {
    .models-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 12px;
    }
}

/* Mobile portrait - large phones (iPhone 14 Pro Max, Samsung S24+) */
@media (max-width: 480px) {
    .models-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
    }
    
    .model-card {
        padding: 10px !important;
        min-width: 0;
    }
    
        
    /* Prevent text overflow in activity cards */
    .model-card div[style*="font-weight:600"] {
        word-break: break-word;
        overflow-wrap: break-word;
        hyphens: auto;
    }
    
    /* Make inline chat button wrap better */
    .model-card a[href*="chat"] {
        display: inline-flex !important;
        margin-left: 0 !important;
        margin-top: 4px;
        font-size: 10px !important;
        padding: 3px 6px !important;
    }
}

/* Small mobile - iPhone SE, Samsung A27, A15 (360px-390px) */
@media (max-width: 390px) {
    .models-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 8px;
    }
    
    .model-card {
        padding: 12px !important;
        max-width: 100%;
    }
    
    .model-card div[style*="font-weight:600"] {
        font-size: 14px !important;
    }
    
    /* Stack buttons vertically using the model-actions class */
    .model-actions {
        flex-direction: column !important;
        gap: 8px !important;
    }
    
    .model-actions a {
        width: 100% !important;
        box-sizing: border-box !important;
        flex: none !important;
        font-size: 14px !important;
        padding: 10px 12px !important;
    }
}

/* Extra small mobile - very narrow screens (below 360px) */
@media (max-width: 359px) {
    .models-grid {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    
    .model-card {
        padding: 10px !important;
    }
}

/* Stack buttons vertically at very small widths to prevent overflow */
@media (max-width: 400px) {
    .model-card > div[style*="display:flex"] {
        flex-direction: column !important;
        gap: 6px !important;
    }
    
    .model-card > div[style*="display:flex"] a {
        width: 100% !important;
        box-sizing: border-box !important;
    }
}

/* Pagination mobile optimization */
@media (max-width: 480px) {
    div[style*="justify-content:center"][style*="flex-wrap:wrap"] {
        gap: 4px !important;
    }
    
    div[style*="justify-content:center"][style*="flex-wrap:wrap"] a,
    div[style*="justify-content:center"][style*="flex-wrap:wrap"] span {
        padding: 6px 10px !important;
        font-size: 12px !important;
        min-width: 32px;
        text-align: center;
    }
}

/* Age gate mobile optimization for iPhone */
@media (max-width: 480px) {
    #fx-agegate .fx-card {
        width: min(95vw, 500px);
        padding: 20px 16px;
        margin: 10px;
    }
    
    #fx-agegate .fx-wordmark {
        font-size: 22px;
    }
    
    #fx-agegate .fx-actions {
        flex-direction: column;
    }
    
    #fx-agegate .fx-btn {
        width: 100%;
    }
}

/* Welcome card mobile fixes */
@media (max-width: 480px) {
    .card > div[style*="display:flex"] {
        gap: 12px !important;
    }
    
    .card > div[style*="display:flex"] > div:first-child {
        flex-shrink: 0;
    }
    
    .card > div[style*="display:flex"] > div:first-child > div {
        width: 60px !important;
        height: 60px !important;
        font-size: 24px !important;
    }
    
    .card .card-title {
        font-size: 18px;
    }
    
    .card a[href*="pp1"] {
        padding: 10px 16px !important;
        font-size: 14px;
    }
}

/* Lightbox mobile optimization */
@media (max-width: 480px) {
    #lightbox {
        padding: 10px !important;
    }
    
    #lightboxInfo {
        padding: 12px !important;
        margin-top: 10px !important;
    }
    
    #lightboxImage {
        max-height: calc(100vh - 200px) !important;
    }
    
    #closeLightbox {
        top: 10px !important;
        right: 10px !important;
        width: 40px !important;
        height: 40px !important;
        font-size: 24px !important;
    }
    
    #prevImage, #nextImage {
        width: 40px !important;
        height: 40px !important;
        font-size: 24px !important;
    }
}

/* Safe area support for iPhone notch/dynamic island */
@supports (padding-top: env(safe-area-inset-top)) {
    #fx-agegate {
        padding-top: env(safe-area-inset-top);
        padding-bottom: env(safe-area-inset-bottom);
    }
    
    #lightbox {
        padding-top: env(safe-area-inset-top);
        padding-bottom: env(safe-area-inset-bottom);
    }
}

/* Ensure images don't overflow */
.model-card img, .gallery-image {
    max-width: 100%;
    height: auto;
}

/* Token depletion modal mobile fix */
@media (max-width: 480px) {
    #tokenDepletedModal > div {
        margin: 10px;
        padding: 24px 16px !important;
    }
    
    #tokenDepletedModal h2 {
        font-size: 20px;
    }
}

/* About FantasyXXX section - mobile text fix */
.card[style*="max-width: 1000px"],
.card[style*="max-width:1000px"] {
    max-width: 100% !important;
    margin: 1rem 0 !important;
    padding: 1rem !important;
    box-sizing: border-box;
    word-break: break-word;
    overflow-wrap: break-word;
}

.card[style*="max-width: 1000px"] *,
.card[style*="max-width:1000px"] * {
    max-width: 100%;
    box-sizing: border-box;
}

@media (max-width: 768px) {
    .card[style*="max-width: 1000px"] h1,
    .card[style*="max-width:1000px"] h1 { font-size: 1.4rem !important; }
    .card[style*="max-width: 1000px"] h2,
    .card[style*="max-width:1000px"] h2 { font-size: 1.2rem !important; }
    .card[style*="max-width: 1000px"] h3,
    .card[style*="max-width:1000px"] h3 { font-size: 1rem !important; }
    .card[style*="max-width: 1000px"] p,
    .card[style*="max-width:1000px"] p,
    .card[style*="max-width: 1000px"] li,
    .card[style*="max-width:1000px"] li { font-size: 0.9rem !important; line-height: 1.6; }
    .categories-title { font-size: 1.2rem !important; margin-bottom: 1rem !important; }
}

</style>

<!-- Welcome / CTA Card (replaces member Welcome Back card) -->
<div class="card">
    <div style="display:flex; gap:20px; align-items:center; flex-wrap:wrap;">
        <div>
            <div style="width:80px; height:80px; border-radius:50%; background:linear-gradient(135deg,#8a2be2,#ff2fb3); display:flex; align-items:center; justify-content:center; font-size:32px;">
                👋
            </div>
        </div>
        <div style="flex:1;">
            <div class="card-title" style="margin-bottom:8px;">Welcome to FantasyXXX.ai!</div>
            <p style="margin:4px 0;">Click <strong>💬 Chat</strong> on any model below to start.</p>
        </div>
        <div>
            <a href="<?php echo $join_url_with_ref; ?>" id="ctaJoinBtn"
               style="display:inline-block; padding:12px 24px; background:linear-gradient(90deg,#8a2be2,#ff2fb3); color:white; border-radius:10px; text-decoration:none; font-weight:700; font-size:16px;">
                🚀 Sign Up Free
            </a>
        </div>
    </div>
</div>

<?php if ($communication): ?>
<div class="card">
    <div class="card-title"><?php echo htmlspecialchars($communication['title']); ?></div>
    <div style="color: var(--text-light); line-height: 1.6;">
        <?php echo render_communication_content($communication['content']); ?>
    </div>
</div>
<?php endif; ?>

<!-- Featured Models (CMS-managed SEO images) -->
<div class="card">
    <div class="card-title">🌟 Featured AI Models</div>
    <?php if (!empty($cms_images)): ?>
        <div class="models-grid" style="margin-top:16px;">
            <?php foreach ($cms_images as $index => $cms_image): ?>
                <?php $isVideo = ($cms_image['content_type'] ?? 'image') === 'video'; ?>
                <div class="model-card" style="padding:12px; background:#1a1a2e; border-radius:12px; border:1px solid #262646;">
                    <!-- Model Media -->
                    <div class="<?php echo $isVideo ? 'video-hover-container' : ''; ?>" 
                         style="border-radius:8px; overflow:hidden; position:relative; aspect-ratio:1; margin-bottom:10px; background:#0a0a1a;"
                         <?php if ($isVideo): ?>data-video-src="<?php echo htmlspecialchars($cms_image['video_url']); ?>"<?php endif; ?>>
                        
                        <!-- Thumbnail (shown for both images and videos) - Use thumbnail_url for grid, full-size for lightbox -->
                        <img src="<?php echo htmlspecialchars($cms_image['thumbnail_url'] ?? $cms_image['image_url']); ?>"
                             alt="<?php echo htmlspecialchars($cms_image['model_name']); ?>"
                             class="<?php echo $isVideo ? 'video-thumb' : 'gallery-image'; ?>"
                             decoding="async"
                             width="300"
                             height="300"
                             <?php if ($index < 6): ?>fetchpriority="high"<?php else: ?>loading="lazy"<?php endif; ?>
                             <?php if (!$isVideo): ?>
                             data-image-url="<?php echo htmlspecialchars($cms_image['image_url']); ?>"
                             data-prompt=""
                             data-seed=""
                             data-date="<?php echo date('M d, Y', strtotime($cms_image['created_at'])); ?>"
                             data-model="<?php echo htmlspecialchars($cms_image['model_name']); ?>"
                             data-creator="FantasyXXX.ai"
                             <?php else: ?>
                             data-media-type="video"
                             data-video-url="<?php echo htmlspecialchars($cms_image['video_url']); ?>"
                             data-image-url="<?php echo htmlspecialchars($cms_image['image_url']); ?>"
                             data-date="<?php echo date('M d, Y', strtotime($cms_image['created_at'])); ?>"
                             data-model="<?php echo htmlspecialchars($cms_image['model_name']); ?>"
                             data-creator="FantasyXXX.ai"
                             <?php endif; ?>
                             style="width:100%; height:100%; object-fit:contain; border-radius:8px; cursor:pointer; display:block;">
                        
                        <?php if ($isVideo): ?>
                        <!-- Play overlay -->
                        <div class="video-play-overlay" style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:rgba(0,0,0,0.6); border-radius:50%; width:56px; height:56px; display:flex; align-items:center; justify-content:center; pointer-events:none; transition:opacity 0.2s;">
                            <span style="font-size:28px; margin-left:4px; color:white;">▶</span>
                        </div>
                        <!-- Hidden video element (loaded on hover) -->
                        <video class="hover-video" muted loop playsinline preload="none"
                               style="position:absolute; top:0; left:0; width:100%; height:100%; object-fit:contain; border-radius:8px; display:none;">
                        </video>
                        <?php endif; ?>
                    </div>

                    <!-- Model Name -->
                    <div style="font-weight:600; font-size:15px; color:#ff2fb3; margin-bottom:8px; text-align:center;">
                        <?php echo htmlspecialchars($cms_image['model_name']); ?>
                    </div>

                    <!-- Action Buttons -->
                    <div class="model-actions" style="display:flex; gap:8px;">
                        <?php if ($cms_image['model_id']): ?>
                        <a href="<?php echo get_chat_url($cms_image['model_name']); ?><?php echo $ref_param; ?>" 
                           class="btn btn-sm" 
                           style="flex:1; text-align:center; padding:8px 12px; font-size:12px;">
                            💬 Chat
                        </a>
                        <?php else: ?>
                        <a href="<?php echo BASE_URL; ?>model.php?model=<?php echo urlencode($cms_image['model_name']); ?>&img=<?php echo urlencode($cms_image['image_url']); ?><?php echo $ref_param ? '&' . substr($ref_param, 1) : ''; ?>" 
                           class="btn btn-sm" 
                           style="flex:1; text-align:center; padding:8px 12px; font-size:12px;">
                            👁 View Model
                        </a>
                        <?php endif; ?>
                        <a href="<?php echo $join_url_with_ref; ?>" 
                           class="btn btn-sm btn-secondary" 
                           style="flex:1; text-align:center; padding:8px 12px; font-size:12px;">
                            🚀 Sign Up
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <p class="muted" style="margin-top:12px;">Featured models coming soon! <a href="<?php echo $join_url_with_ref; ?>" style="color:#ff2fb3;">Sign up free</a> to create your own AI companion.</p>
    <?php endif; ?>
</div>

<!-- Token Depletion Modal -->
<div id="tokenDepletedModal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.9); z-index:10001; align-items:center; justify-content:center; padding:20px;">
    <div style="background:#1a1a2e; border-radius:16px; max-width:500px; width:100%; border:1px solid #262646; box-shadow:0 10px 40px rgba(0,0,0,0.5); text-align:center; padding:40px;">
        <div style="font-size:64px; margin-bottom:20px;">🔒</div>
        <h2 style="margin:0 0 12px; color:#f2f2f7;">You've Used Your Free Messages!</h2>
        <p style="color:#a1a1b5; line-height:1.6; margin-bottom:24px;">
            Sign up for unlimited chat with all models, image generation, video creation, and more.
        </p>
        <a href="<?php echo $join_url_with_ref; ?>" id="tokenModalJoinBtn"
           style="display:block; padding:16px 32px; background:linear-gradient(90deg,#8a2be2,#ff2fb3); color:white; border-radius:10px; text-decoration:none; font-weight:700; font-size:18px; margin-bottom:12px;">
            🚀 Sign Up Free — Unlimited Chat
        </a>
        <button onclick="document.getElementById('tokenDepletedModal').style.display='none'"
                style="background:none; border:none; color:#a1a1b5; cursor:pointer; font-size:14px;">
            Maybe later
        </button>
    </div>
</div>

<!-- Lightbox Modal (same as dashboard.php) -->
<div id="lightbox" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.95); z-index:9999; padding:20px;">
    <button id="closeLightbox" style="position:absolute; top:20px; right:20px; background:rgba(255,255,255,0.1); border:none; color:white; font-size:32px; cursor:pointer; width:50px; height:50px; border-radius:50%; transition:background 0.2s;" onmouseover="this.style.background='rgba(255,47,179,0.5)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">×</button>
    <button id="prevImage" style="position:absolute; left:20px; top:50%; transform:translateY(-50%); background:rgba(255,255,255,0.1); border:none; color:white; font-size:32px; cursor:pointer; width:50px; height:50px; border-radius:50%; transition:background 0.2s;" onmouseover="this.style.background='rgba(255,47,179,0.5)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">‹</button>
    <button id="nextImage" style="position:absolute; right:20px; top:50%; transform:translateY(-50%); background:rgba(255,255,255,0.1); border:none; color:white; font-size:32px; cursor:pointer; width:50px; height:50px; border-radius:50%; transition:background 0.2s;" onmouseover="this.style.background='rgba(255,47,179,0.5)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">›</button>
    <div style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%; max-width:1400px; margin:0 auto;">
        <img id="lightboxImage" src="" alt="Full size image" style="max-width:100%; max-height:calc(100vh - 250px); object-fit:contain; border-radius:8px; box-shadow:0 10px 40px rgba(0,0,0,0.5);">
        <video id="lightboxVideo" controls playsinline style="display:none; max-width:100%; max-height:calc(100vh - 250px); object-fit:contain; border-radius:8px; box-shadow:0 10px 40px rgba(0,0,0,0.5);">
            <source src="" type="video/mp4">
        </video>
        <div id="lightboxInfo" style="background:rgba(20,20,35,0.9); padding:20px; border-radius:12px; margin-top:20px; max-width:800px; width:100%; backdrop-filter:blur(10px);">
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
                <span id="lightboxModel" style="color:#ff2fb3; font-weight:600; font-size:16px;"></span>
                <span style="color:#666;">by</span>
                <span id="lightboxCreator" style="color:#a1a1b5; font-size:14px;"></span>
            </div>
            <div id="lightboxPrompt" style="color:#f2f2f7; font-size:16px; margin-bottom:12px; line-height:1.6;"></div>
            <div style="display:flex; gap:20px; flex-wrap:wrap; font-size:14px; color:#a1a1b5;">
                <span id="lightboxDate"></span>
                <span id="lightboxSeed"></span>
                <span id="lightboxCounter" style="margin-left:auto; color:#ff2fb3; font-weight:600;"></span>
            </div>
        </div>
    </div>
</div>

<!-- Token Depletion Modal -->
<div id="tokenDepletedModal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.9); z-index:10001; align-items:center; justify-content:center; padding:20px;">
    <div style="background:#1a1a2e; border-radius:16px; max-width:500px; width:100%; border:1px solid #262646; box-shadow:0 10px 40px rgba(0,0,0,0.5); text-align:center; padding:40px;">
        <div style="font-size:64px; margin-bottom:20px;">🔒</div>
        <h2 style="margin:0 0 12px; color:#f2f2f7;">You've Used Your Free Messages!</h2>
        <p style="color:#a1a1b5; line-height:1.6; margin-bottom:24px;">
            Sign up for unlimited chat with all models, image generation, video creation, and more.
        </p>
        <a href="<?php echo $join_url_with_ref; ?>" id="tokenModalJoinBtn"
           style="display:block; padding:16px 32px; background:linear-gradient(90deg,#8a2be2,#ff2fb3); color:white; border-radius:10px; text-decoration:none; font-weight:700; font-size:18px; margin-bottom:12px;">
            🚀 Sign Up Free — Unlimited Chat
        </a>
        <button onclick="document.getElementById('tokenDepletedModal').style.display='none'"
                style="background:none; border:none; color:#a1a1b5; cursor:pointer; font-size:14px;">
            Maybe later
        </button>
    </div>
</div>

<script src="/includes/js/bookmarks.js" defer></script>

<script>
// Age Gate Logic (preserved from original index.php)
(function() {
    const STORAGE_KEY = 'fx_age_verified_until';
    const DAYS = 30;
    const gate     = document.getElementById('fx-agegate');
    const enterBtn = document.getElementById('fx-enter');
    const leaveBtn = document.getElementById('fx-leave');
    const rememberCheckbox = document.getElementById('fx-remember');

    function checkAgeVerification() {
        const stored = localStorage.getItem(STORAGE_KEY);
        if (stored) {
            const expiryTime = parseInt(stored, 10);
            if (Date.now() < expiryTime) {
                gate.setAttribute('aria-hidden', 'true');
                document.body.classList.remove('fx-lock');
                return true;
            }
        }
        document.body.classList.add('fx-lock');
        return false;
    }

    enterBtn.addEventListener('click', function() {
        if (rememberCheckbox.checked) {
            const expiryTime = Date.now() + (DAYS * 24 * 60 * 60 * 1000);
            localStorage.setItem(STORAGE_KEY, expiryTime.toString());
        }
        gate.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('fx-lock');
    });

    leaveBtn.addEventListener('click', function() {
        window.location.href = 'https://www.google.com';
    });

    checkAgeVerification();
})();

// Lightbox Gallery (supports images + videos)
const lightbox       = document.getElementById('lightbox');
const lightboxImage  = document.getElementById('lightboxImage');
const lightboxVideo  = document.getElementById('lightboxVideo');
const lightboxPrompt = document.getElementById('lightboxPrompt');
const lightboxDate   = document.getElementById('lightboxDate');
const lightboxSeed   = document.getElementById('lightboxSeed');
const lightboxModel  = document.getElementById('lightboxModel');
const lightboxCreator  = document.getElementById('lightboxCreator');
const lightboxCounter  = document.getElementById('lightboxCounter');
const closeLightboxBtn = document.getElementById('closeLightbox');
const prevImage = document.getElementById('prevImage');
const nextImage = document.getElementById('nextImage');

let currentImageIndex = 0;
let galleryImages = [];

// Collect images into gallery
document.querySelectorAll('.gallery-image').forEach((img) => {
    const idx = galleryImages.length;
    galleryImages.push({
        type:    'image',
        url:     img.getAttribute('data-image-url'),
        prompt:  img.getAttribute('data-prompt'),
        seed:    img.getAttribute('data-seed'),
        date:    img.getAttribute('data-date'),
        model:   img.getAttribute('data-model'),
        creator: img.getAttribute('data-creator')
    });
    img.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        openLightbox(idx);
    });
});

// Collect video thumbnails into gallery
document.querySelectorAll('.video-thumb').forEach((img) => {
    const idx = galleryImages.length;
    galleryImages.push({
        type:     'video',
        url:      img.getAttribute('data-image-url'),
        videoUrl: img.getAttribute('data-video-url'),
        date:     img.getAttribute('data-date'),
        model:    img.getAttribute('data-model'),
        creator:  img.getAttribute('data-creator'),
        prompt:   '',
        seed:     ''
    });
    img.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        openLightbox(idx);
    });
});

function openLightbox(index) {
    currentImageIndex = index;
    updateLightbox();
    // Batch style changes to reduce reflows
    requestAnimationFrame(() => {
        lightbox.style.display = 'block';
        document.body.style.overflow = 'hidden';
    });
}

function closeLightboxFunc() {
    // Pause any playing video first
    lightboxVideo.pause();
    lightboxVideo.querySelector('source').src = '';
    // Batch style changes to reduce reflows
    requestAnimationFrame(() => {
        lightbox.style.display = 'none';
        document.body.style.overflow = 'auto';
        lightboxVideo.style.display = 'none';
        lightboxImage.style.display = '';
    });
}

function updateLightbox() {
    const item = galleryImages[currentImageIndex];
    if (item.type === 'video' && item.videoUrl) {
        lightboxImage.style.display = 'none';
        lightboxVideo.style.display = 'block';
        lightboxVideo.querySelector('source').src = item.videoUrl;
        lightboxVideo.load();
    } else {
        lightboxVideo.pause();
        lightboxVideo.style.display = 'none';
        lightboxImage.style.display = '';
        lightboxImage.src = item.url;
    }
    lightboxPrompt.textContent = item.prompt ? `"${item.prompt}"` : '';
    lightboxDate.textContent   = `📅 ${item.date}`;
    lightboxSeed.textContent   = item.seed ? `🌱 Seed: ${item.seed}` : '';
    lightboxModel.textContent  = item.model || 'Unknown Model';
    lightboxCreator.textContent = `@${item.creator}` || 'Unknown';
    lightboxCounter.textContent = `${currentImageIndex + 1} / ${galleryImages.length}`;
    prevImage.style.display = currentImageIndex > 0 ? 'block' : 'none';
    nextImage.style.display = currentImageIndex < galleryImages.length - 1 ? 'block' : 'none';
}

function showPrevImage() { if (currentImageIndex > 0) { currentImageIndex--; updateLightbox(); } }
function showNextImage() { if (currentImageIndex < galleryImages.length - 1) { currentImageIndex++; updateLightbox(); } }

closeLightboxBtn.addEventListener('click', closeLightboxFunc);
prevImage.addEventListener('click', showPrevImage);
nextImage.addEventListener('click', showNextImage);

lightbox.addEventListener('click', function(e) { if (e.target === lightbox) closeLightboxFunc(); });

document.addEventListener('keydown', function(e) {
    if (lightbox.style.display === 'block') {
        if (e.key === 'Escape')      closeLightboxFunc();
        if (e.key === 'ArrowLeft')   showPrevImage();
        if (e.key === 'ArrowRight')  showNextImage();
    }
});

// Video Hover Playback — load and play video on mouseenter, pause/reset on mouseleave
document.querySelectorAll('.video-hover-container').forEach(container => {
    const videoSrc = container.getAttribute('data-video-src');
    const thumb    = container.querySelector('.video-thumb');
    const overlay  = container.querySelector('.video-play-overlay');
    const video    = container.querySelector('.hover-video');
    if (!videoSrc || !video) return;

    let videoLoaded = false;

    container.addEventListener('mouseenter', function() {
        if (!videoLoaded) {
            const source = document.createElement('source');
            source.src = videoSrc;
            source.type = 'video/mp4';
            video.appendChild(source);
            video.load();
            videoLoaded = true;
        }
        // Batch style changes to reduce reflows
        requestAnimationFrame(() => {
            video.style.display = 'block';
            if (thumb) thumb.style.opacity = '0';
            if (overlay) overlay.style.opacity = '0';
        });
        video.play().catch(() => {});
    });

    container.addEventListener('mouseleave', function() {
        video.pause();
        video.currentTime = 0;
        // Batch style changes to reduce reflows
        requestAnimationFrame(() => {
            video.style.display = 'none';
            if (thumb) thumb.style.opacity = '1';
            if (overlay) overlay.style.opacity = '1';
        });
    });

    // On mobile: tap to toggle play
    container.addEventListener('touchstart', function(e) {
        if (video.paused) {
            if (!videoLoaded) {
                const source = document.createElement('source');
                source.src = videoSrc;
                source.type = 'video/mp4';
                video.appendChild(source);
                video.load();
                videoLoaded = true;
            }
            video.style.display = 'block';
            if (thumb) thumb.style.opacity = '0';
            if (overlay) overlay.style.opacity = '0';
            video.play().catch(() => {});
        } else {
            video.pause();
            video.currentTime = 0;
            video.style.display = 'none';
            if (thumb) thumb.style.opacity = '1';
            if (overlay) overlay.style.opacity = '1';
        }
    }, { passive: true });
});

// Lazy Loading for Videos (same as dashboard.php)
const videoContainers = document.querySelectorAll('.lazy-video-container');
const videoObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const container  = entry.target;
            const videoUrl   = container.getAttribute('data-video-url');
            const videoElement = container.querySelector('.lazy-video');
            const placeholder  = container.querySelector('.video-placeholder');
            if (videoElement && videoUrl) {
                const source = videoElement.querySelector('source');
                source.src = videoUrl;
                videoElement.load();
                videoElement.addEventListener('canplay', function() {
                    placeholder.style.display = 'none';
                    videoElement.style.display = 'block';
                }, { once: true });
                videoElement.addEventListener('error', function() {
                    placeholder.innerHTML = '<div style="text-align:center;color:#ff2fb3;"><div style="font-size:32px;margin-bottom:8px;">⚠️</div><div style="font-size:12px;">Failed to load video</div></div>';
                }, { once: true });
                videoObserver.unobserve(container);
            }
        }
    });
}, { rootMargin: '50px' });

videoContainers.forEach(container => videoObserver.observe(container));

// Token Management for Anonymous Users (same as index3.php)
<?php if (isset($anon_tokens_remaining) && $anon_tokens_remaining !== null): ?>
const anonTokensRemaining = <?php echo $anon_tokens_remaining; ?>;
const tokenModal = document.getElementById('tokenDepletedModal');

// Check tokens on page load
if (anonTokensRemaining <= 0) {
    tokenModal.style.display = 'flex';
}

// Handle chat links - check tokens before allowing
document.addEventListener('click', function(e) {
    const chatLink = e.target.closest('a[href*="chat/?model_id"]');
    if (chatLink && anonTokensRemaining <= 0) {
        e.preventDefault();
        tokenModal.style.display = 'flex';
    }
});
<?php endif; ?>
</script>

<!-- About FantasyXXX.ai Section (CMS-managed) -->
<?php if ($about_content): ?>
    <div class="card" style="max-width: 1000px; margin: 2rem auto; padding: 2rem;">
        <?php echo $about_content; ?>
    </div>
<?php else: ?>
    <!-- Fallback About section if CMS content not available -->
    <div class="card" style="max-width: 1000px; margin: 2rem auto; padding: 2rem;">
        <h2 class="categories-title" style="text-align: center; margin-bottom: 2rem;">About FantasyXXX.ai</h2>
        <p style="color: var(--text-light); font-size: 1rem; margin-bottom: 1.5rem;">
            FantasyXXX.ai is an immersive AI girlfriend and NSFW AI chat platform where users create their own digital fantasy from the ground up.
        </p>
    </div>
<?php endif; ?>

<?php
end_content('HOME');
?>
