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

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

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;

    $cookie_domain = COOKIE_DOMAIN;
    $affiliate_api_url = AFFILIATES_URL . '/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,
               (SELECT m.bio FROM models m WHERE BINARY m.name = BINARY ci.model_name LIMIT 1) as model_bio
        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_sexting_username' AND is_active = 1 LIMIT 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="<?= BRAND_NAME ?>"
                     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;" />
                -->
                <?= BRAND_NAME ?>
            </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, #ffffff 0%, #eef5ff 100%);
    color: #14263f; border-radius: 18px;
    box-shadow: 0 10px 32px rgba(46,168,255,0.16), inset 0 0 0 1px rgba(211,226,245,0.8);
    padding: 28px; border: 1px solid #d3e2f5;
}
.fx-brand  { display:flex; align-items:center; justify-content:center; margin-bottom:16px; }
.fx-wordmark { font-size:28px; font-weight:800; color:#14263f; letter-spacing:-0.5px; }
.pink { color: #ff5a8a; }
#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:#5d7289; margin-bottom:16px; text-align:center; }
.fx-sub a { color:#2ea8ff; text-decoration:none; border-bottom:1px solid #2ea8ff; }
.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:#2ea8ff; color:white; }
.fx-btn-primary:hover { background-color:#1d8fe6; transform:translateY(-1px); }
.fx-btn-secondary { background:#f0f7ff; color:#14263f; border:1px solid #d3e2f5; }
.fx-btn-secondary:hover { background:#dceeff; }
.fx-row { display:flex; align-items:center; gap:10px; margin-top:10px; font-size:13px; color:#5d7289; }
.fx-check { accent-color:#2ea8ff; }
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 - iPhone 14 optimized */
.models-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
    justify-items: center;
    max-width: 1400px;
    margin: 0 auto;
}

.featured-model-card {
    width: 100%;
    padding: 12px;
    background: linear-gradient(180deg, #0d1540 0%, #0a1030 100%);
    border-radius: 14px;
    border: 1px solid rgba(255, 79, 216, 0.22);
    box-shadow: 0 12px 28px rgba(0, 0, 0, 0.32), 0 0 0 1px rgba(0, 229, 255, 0.04) inset;
    transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
    box-sizing: border-box;
}

.featured-model-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 18px 36px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255, 79, 216, 0.12);
    border-color: rgba(255, 79, 216, 0.4);
}

.featured-model-media {
    border-radius: 10px;
    overflow: hidden;
    position: relative;
    aspect-ratio: 1 / 1;
    margin-bottom: 10px;
    background: #0a0a1a;
}

.featured-model-name {
    font-weight: 700;
    font-size: 15px;
    color: #ff4fd8;
    margin-bottom: 10px;
    text-align: center;
    line-height: 1.3;
    text-shadow: 0 0 10px rgba(255, 79, 216, 0.18);
}

.featured-model-actions {
    display: flex;
    gap: 8px;
}

.featured-model-actions .btn {
    flex: 1;
    text-align: center;
    padding: 8px 12px;
    font-size: 12px;
    white-space: nowrap;
}

.featured-models-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;
    justify-content: center;
    align-items: start;
    margin-top: 16px;
    max-width: 1100px;
    margin-left: auto;
    margin-right: auto;
}

.featured-model-card .btn {
    border-radius: 10px;
}

.featured-model-card .btn-secondary {
    background: rgba(0, 229, 255, 0.1);
    border: 1px solid rgba(0, 229, 255, 0.18);
    color: #ffffff;
}

.featured-model-card .btn-secondary:hover {
    background: rgba(0, 229, 255, 0.16);
}

.lightbox-meta-row {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
    flex-wrap: wrap;
}

.lightbox-shell {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    max-width: min(1400px, 100%);
    margin: 0 auto;
    overflow: hidden;
}

.lightbox-media {
    max-width: 100%;
    max-height: min(56vh, 720px);
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.5);
}

.lightbox-info-panel {
    background: rgba(255,255,255,0.95);
    padding: 20px;
    border-radius: 12px;
    margin-top: 20px;
    max-width: 800px;
    width: min(800px, 100%);
    max-height: min(34vh, 360px);
    overflow-y: auto;
    overflow-x: hidden;
    backdrop-filter: blur(10px);
}

.lightbox-bio {
    color: #14263f;
    font-size: 15px;
    line-height: 1.65;
    margin-bottom: 12px;
    white-space: pre-wrap;
    word-break: break-word;
    overflow-wrap: anywhere;
}


.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-fit, minmax(200px, 1fr));
        gap: 14px;
    }
}

/* Mobile landscape and small tablets */
@media (max-width: 600px) {
    .models-grid {
        grid-template-columns: repeat(auto-fit, minmax(180px, 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: 12px;
    }
    
    .model-card {
        padding: 10px !important;
        min-width: 0;
    }

    .featured-model-card {
        width: 100%;
    }

    .featured-models-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 12px;
    }
    
        
    /* 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: 1fr;
        gap: 12px;
    }
    
    .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;
    }

    .featured-model-actions {
        flex-direction: column;
    }

    .featured-models-grid {
        grid-template-columns: 1fr;
    }
}

/* 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;
    }
    
    .lightbox-shell {
        justify-content: flex-start;
        padding-top: 48px;
        height: 100%;
    }

    .lightbox-info-panel {
        padding: 12px !important;
        margin-top: 10px !important;
        max-height: 52vh;
    }

    .lightbox-media {
        max-height: 30vh !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;
    }

    .lightbox-meta-row {
        gap: 8px;
        margin-bottom: 10px;
    }

    .lightbox-bio,
    #lightboxPrompt {
        font-size: 14px !important;
        line-height: 1.55 !important;
    }
}

@media (min-width: 1600px) {
    .lightbox-media {
        max-height: min(52vh, 760px);
    }

    .lightbox-info-panel {
        max-height: min(32vh, 380px);
    }
}

/* 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;
    }
}

</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,#2ea8ff,#ff5a8a); 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 <?= BRAND_NAME ?>!</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,#ff7a59,#ff5a8a); 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="featured-models-grid">
            <?php foreach ($cms_images as $index => $cms_image): ?>
                <?php $isVideo = ($cms_image['content_type'] ?? 'image') === 'video'; ?>
                <div class="model-card featured-model-card">
                    <!-- Model Media -->
                    <div class="featured-model-media <?php echo $isVideo ? 'video-hover-container' : ''; ?>"
                         <?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"
                             <?php if ($index < 6): ?>fetchpriority="high"<?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-bio="<?php echo htmlspecialchars($cms_image['model_bio'] ?? ''); ?>"
                             data-creator="<?= BRAND_NAME ?>"
                             <?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-bio="<?php echo htmlspecialchars($cms_image['model_bio'] ?? ''); ?>"
                             data-creator="<?= BRAND_NAME ?>"
                             <?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 class="featured-model-name">
                        <?php echo htmlspecialchars($cms_image['model_name']); ?>
                    </div>

                    <!-- Action Buttons -->
                    <div class="model-actions featured-model-actions">
                        <?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">
                            💬 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">
                            👁 View Model
                        </a>
                        <?php endif; ?>
                        <a href="<?php echo $join_url_with_ref; ?>" 
                           class="btn btn-sm btn-secondary">
                            🚀 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:#ff5a8a;">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:#ffffff; border-radius:16px; max-width:500px; width:100%; border:1px solid #d3e2f5; box-shadow:0 10px 32px rgba(46,168,255,0.18); text-align:center; padding:40px;">
        <div style="font-size:64px; margin-bottom:20px;">🔒</div>
        <h2 style="margin:0 0 12px; color:#14263f;">You've Used Your Free Messages!</h2>
        <p style="color:#5d7289; 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,#ff7a59,#ff5a8a); 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:#5d7289; 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 class="lightbox-shell">
        <img id="lightboxImage" class="lightbox-media" src="" alt="Full size image">
        <video id="lightboxVideo" class="lightbox-media" controls playsinline style="display:none;">
            <source src="" type="video/mp4">
        </video>
        <div id="lightboxInfo" class="lightbox-info-panel">
            <div class="lightbox-meta-row">
                <span id="lightboxModel" style="color:#ff5a8a; font-weight:600; font-size:16px;"></span>
                <span style="color:#666;">by</span>
                <span id="lightboxCreator" style="color:#5d7289; font-size:14px;"></span>
            </div>
            <div id="lightboxBio" class="lightbox-bio"></div>
            <div id="lightboxPrompt" style="color:#14263f; font-size:16px; margin-bottom:12px; line-height:1.6;"></div>
            <div style="display:flex; gap:20px; flex-wrap:wrap; font-size:14px; color:#5d7289;">
                <span id="lightboxDate"></span>
                <span id="lightboxSeed"></span>
                <span id="lightboxCounter" style="margin-left:auto; color:#2ea8ff; 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:#ffffff; border-radius:16px; max-width:500px; width:100%; border:1px solid #d3e2f5; box-shadow:0 10px 32px rgba(46,168,255,0.18); text-align:center; padding:40px;">
        <div style="font-size:64px; margin-bottom:20px;">🔒</div>
        <h2 style="margin:0 0 12px; color:#14263f;">You've Used Your Free Messages!</h2>
        <p style="color:#5d7289; 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,#ff7a59,#ff5a8a); 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:#5d7289; 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 lightboxBio    = document.getElementById('lightboxBio');
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'),
        bio:     img.getAttribute('data-bio'),
        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'),
        bio:      img.getAttribute('data-bio'),
        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;
    }
    lightboxBio.textContent      = item.bio || '';
    lightboxBio.style.display    = item.bio ? 'block' : 'none';
    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:#ff5a8a;"><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 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 <?= BRAND_NAME ?></h2>
        <p style="color: var(--text-light); font-size: 1rem; margin-bottom: 1.5rem;">
            <?= BRAND_NAME ?> 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');
?>
