<?php
// Configurações do banco de dados
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

// OTIMIZAÇÕES MÁXIMAS
ini_set('memory_limit', '256M');
set_time_limit(15);

// Cache de sessão para resultados
session_start();

// Conectar ao banco
try {
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false,
    ];
    
    $pdo = new PDO($dsn, $user, $pass, $options);
    // Otimizações MySQL
    $pdo->exec("SET SESSION sql_buffer_result = 1");
    
} catch (PDOException $e) {
    die("Database error");
}

// Parâmetros
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$mode = isset($_GET['mode']) ? $_GET['mode'] : 'fast';
$limit = 40; // Mais resultados por página
$offset = ($page - 1) * $limit;

$results = [];
$searchTime = 0;
$totalEstimate = 0;

if (!empty($q)) {
    $startTime = microtime(true);
    
    // Cache key
    $cacheKey = md5($q . $mode . $page);
    
    // Verificar cache de sessão
    if (isset($_SESSION['search_cache'][$cacheKey]) && 
        (time() - $_SESSION['search_cache'][$cacheKey]['time'] < 300)) {
        $results = $_SESSION['search_cache'][$cacheKey]['results'];
        $totalEstimate = $_SESSION['search_cache'][$cacheKey]['total'];
        $searchTime = 0.001; // Cached
    } else {
        try {
            // Limpar busca
            $term = preg_replace('/[^\p{L}\p{N}\s\-]/u', '', $q);
            $term = trim(preg_replace('/\s+/', ' ', $term));
            
            // BUSCA ULTRA OTIMIZADA
            if ($mode === 'fast') {
                // Busca em índice de título (mais rápido)
                $sql = "SELECT id, title, thumbnail, tags, link, author,
                               DATE_FORMAT(pubDate, '%d/%m') as date_short
                        FROM pinfeeds 
                        WHERE title LIKE :term
                        ORDER BY id DESC
                        LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute(['term' => '%' . $term . '%']);
                
            } elseif ($mode === 'exact') {
                // Busca exata no título
                $sql = "SELECT id, title, thumbnail, tags, link, author,
                               DATE_FORMAT(pubDate, '%d/%m') as date_short
                        FROM pinfeeds 
                        WHERE title = :term
                        ORDER BY id DESC
                        LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute(['term' => $term]);
                
            } else {
                // Busca completa (título + tags)
                $sql = "SELECT id, title, thumbnail, tags, link, author,
                               DATE_FORMAT(pubDate, '%d/%m') as date_short,
                               CASE 
                                   WHEN title LIKE :exact THEN 1
                                   WHEN title LIKE :start THEN 2
                                   WHEN title LIKE :term THEN 3
                                   ELSE 4
                               END as relevance
                        FROM pinfeeds 
                        WHERE title LIKE :term OR tags LIKE :term2
                        ORDER BY relevance, id DESC
                        LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    'exact' => $term,
                    'start' => $term . '%',
                    'term' => '%' . $term . '%',
                    'term2' => '%' . $term . '%'
                ]);
            }
            
            $results = $stmt->fetchAll();
            
            // Estimar total sem contar tudo
            if (count($results) == $limit) {
                // Verificar se há mais páginas
                $checkSql = "SELECT 1 FROM pinfeeds WHERE title LIKE :term LIMIT 1 OFFSET " . ($offset + $limit);
                $checkStmt = $pdo->prepare($checkSql);
                $checkStmt->execute(['term' => '%' . $term . '%']);
                
                if ($checkStmt->fetch()) {
                    $totalEstimate = ($page + 20) * $limit; // Estima mais 20 páginas
                } else {
                    $totalEstimate = $offset + $limit + 10; // Quase no fim
                }
            } else {
                $totalEstimate = $offset + count($results);
            }
            
            // Salvar no cache
            $_SESSION['search_cache'][$cacheKey] = [
                'results' => $results,
                'total' => $totalEstimate,
                'time' => time()
            ];
            
            // Limpar cache antigo
            if (count($_SESSION['search_cache']) > 10) {
                array_shift($_SESSION['search_cache']);
            }
            
        } catch (Exception $e) {
            $error = true;
        }
    }
    
    $searchTime = round(microtime(true) - $startTime, 3);
}

// Helper
function h($text) {
    return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
}

// Processar tags
function getTags($tagString) {
    if (empty($tagString)) return [];
    $tags = array_map('trim', explode(',', $tagString));
    return array_slice(array_filter($tags), 0, 3);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $q ? h($q) . ' - ' : ''; ?>DigUpDog</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        :root {
            --pinterest-red: #e60023;
            --pinterest-dark: #ad081b;
            --gray-50: #fafafa;
            --gray-100: #f5f5f5;
            --gray-200: #eeeeee;
            --gray-300: #e0e0e0;
            --gray-400: #bdbdbd;
            --gray-500: #9e9e9e;
            --gray-600: #757575;
            --gray-700: #616161;
            --gray-800: #424242;
            --gray-900: #212121;
            --radius: 16px;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow: 0 1px 3px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: var(--gray-50);
            color: var(--gray-900);
            line-height: 1.5;
            -webkit-font-smoothing: antialiased;
        }
        
        /* Header */
        .header {
            background: white;
            box-shadow: var(--shadow-sm);
            position: sticky;
            top: 0;
            z-index: 1000;
            padding: 12px 0;
        }
        
        .header-content {
            max-width: 1600px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        /* Logo */
        .logo {
            font-size: 24px;
            font-weight: 700;
            color: var(--pinterest-red);
            text-decoration: none;
            letter-spacing: -0.5px;
        }
        
        /* Search */
        .search-wrapper {
            flex: 1;
            max-width: 700px;
        }
        
        .search-form {
            position: relative;
            display: flex;
            align-items: center;
        }
        
        .search-input {
            width: 100%;
            padding: 12px 48px 12px 20px;
            border: none;
            border-radius: 24px;
            background: var(--gray-100);
            font-size: 16px;
            outline: none;
            transition: all 0.2s;
        }
        
        .search-input:hover {
            background: var(--gray-200);
        }
        
        .search-input:focus {
            background: white;
            box-shadow: 0 0 0 4px var(--gray-200);
        }
        
        .search-btn {
            position: absolute;
            right: 3px;
            padding: 8px 16px;
            background: var(--pinterest-red);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .search-btn:hover {
            background: var(--pinterest-dark);
        }
        
        /* Mode Pills */
        .mode-pills {
            display: flex;
            gap: 8px;
            padding: 0 20px;
            margin-top: 12px;
            justify-content: center;
        }
        
        .mode-pill {
            padding: 6px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid transparent;
            background: white;
            color: var(--gray-700);
            text-decoration: none;
        }
        
        .mode-pill:hover {
            background: var(--gray-100);
        }
        
        .mode-pill.active {
            background: var(--gray-900);
            color: white;
        }
        
        /* Results Bar */
        .results-bar {
            padding: 16px 20px;
            text-align: center;
            font-size: 14px;
            color: var(--gray-600);
            background: white;
            border-bottom: 1px solid var(--gray-200);
        }
        
        .results-bar strong {
            color: var(--gray-900);
        }
        
        .time-badge {
            display: inline-block;
            padding: 2px 8px;
            background: var(--gray-100);
            border-radius: 12px;
            font-size: 12px;
            margin-left: 8px;
        }
        
        /* Pinterest Masonry Grid */
        .pinterest-grid {
            column-count: 2;
            column-gap: 16px;
            padding: 16px;
            max-width: 1600px;
            margin: 0 auto;
        }
        
        @media (min-width: 640px) { .pinterest-grid { column-count: 3; } }
        @media (min-width: 768px) { .pinterest-grid { column-count: 4; } }
        @media (min-width: 1024px) { .pinterest-grid { column-count: 5; } }
        @media (min-width: 1280px) { .pinterest-grid { column-count: 6; } }
        @media (min-width: 1536px) { .pinterest-grid { column-count: 7; } }
        
        /* Pin Card */
        .pin {
            break-inside: avoid;
            margin-bottom: 16px;
            position: relative;
            cursor: pointer;
            transform: translateZ(0); /* Performance */
        }
        
        .pin-content {
            background: white;
            border-radius: var(--radius);
            overflow: hidden;
            box-shadow: var(--shadow);
            transition: all 0.2s;
        }
        
        .pin:hover .pin-content {
            box-shadow: var(--shadow-lg);
            transform: translateY(-2px);
        }
        
        .pin-img-wrapper {
            position: relative;
            background: var(--gray-100);
            min-height: 120px;
        }
        
        .pin-img {
            width: 100%;
            height: auto;
            display: block;
        }
        
        .no-img {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 200px;
            color: var(--gray-400);
            font-size: 14px;
            background: linear-gradient(135deg, var(--gray-100) 0%, var(--gray-200) 100%);
        }
        
        /* Pin Overlay on Hover */
        .pin-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(to bottom, transparent 0%, rgba(0,0,0,0.6) 100%);
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .pin:hover .pin-overlay {
            opacity: 1;
        }
        
        .pin-save-btn {
            position: absolute;
            top: 12px;
            right: 12px;
            padding: 8px 16px;
            background: var(--pinterest-red);
            color: white;
            border: none;
            border-radius: 24px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            opacity: 0;
            transform: translateY(-10px);
            transition: all 0.2s;
        }
        
        .pin:hover .pin-save-btn {
            opacity: 1;
            transform: translateY(0);
        }
        
        /* Pin Info */
        .pin-info {
            padding: 12px;
        }
        
        .pin-title {
            font-size: 14px;
            font-weight: 600;
            line-height: 1.4;
            margin-bottom: 4px;
            color: var(--gray-900);
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        
        .pin-desc {
            font-size: 13px;
            color: var(--gray-600);
            line-height: 1.4;
            margin-bottom: 8px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        
        .pin-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            margin-bottom: 8px;
        }
        
        .tag {
            display: inline-block;
            padding: 4px 10px;
            background: var(--gray-100);
            color: var(--gray-700);
            border-radius: 16px;
            font-size: 12px;
            font-weight: 500;
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            transition: all 0.2s;
        }
        
        .tag:hover {
            background: var(--gray-200);
        }
        
        .pin-meta {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 12px;
            color: var(--gray-500);
        }
        
        .pin-author {
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 120px;
        }
        
        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 4px;
            padding: 40px 20px;
            background: white;
            margin-top: 20px;
        }
        
        .page-link {
            padding: 8px 14px;
            border-radius: 8px;
            text-decoration: none;
            color: var(--gray-700);
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
            border: 1px solid transparent;
        }
        
        .page-link:hover {
            background: var(--gray-100);
        }
        
        .page-link.active {
            background: var(--pinterest-red);
            color: white;
        }
        
        .page-link.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .page-dots {
            padding: 0 8px;
            color: var(--gray-400);
        }
        
        /* Messages */
        .message {
            text-align: center;
            padding: 80px 20px;
            color: var(--gray-600);
        }
        
        .message h2 {
            font-size: 24px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 8px;
        }
        
        /* Loading Animation */
        @keyframes shimmer {
            0% { background-position: -1000px 0; }
            100% { background-position: 1000px 0; }
        }
        
        .skeleton {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 1000px 100%;
            animation: shimmer 2s infinite;
        }
        
        /* Performance */
        img {
            content-visibility: auto;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="header-content">
            <a href="?" class="logo">DigUpDog</a>
            
            <div class="search-wrapper">
                <form class="search-form" method="GET">
                    <input type="text" 
                           name="q" 
                           class="search-input" 
                           placeholder="Search for ideas..." 
                           value="<?php echo h($q); ?>"
                           autocomplete="off">
                    <input type="hidden" name="mode" value="<?php echo h($mode); ?>">
                    <button type="submit" class="search-btn">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="11" cy="11" r="8"></circle>
                            <path d="m21 21-4.35-4.35"></path>
                        </svg>
                    </button>
                </form>
            </div>
        </div>
        
        <?php if ($q): ?>
        <div class="mode-pills">
            <a href="?q=<?php echo urlencode($q); ?>&mode=fast" 
               class="mode-pill <?php echo $mode === 'fast' ? 'active' : ''; ?>">Fast</a>
            <a href="?q=<?php echo urlencode($q); ?>&mode=exact" 
               class="mode-pill <?php echo $mode === 'exact' ? 'active' : ''; ?>">Exact</a>
            <a href="?q=<?php echo urlencode($q); ?>&mode=full" 
               class="mode-pill <?php echo $mode === 'full' ? 'active' : ''; ?>">Full</a>
        </div>
        <?php endif; ?>
    </header>

    <?php if ($q && !isset($error)): ?>
        <div class="results-bar">
            <?php if ($totalEstimate > 10000): ?>
                <strong>10,000+</strong> pins for "<strong><?php echo h($q); ?></strong>"
            <?php else: ?>
                <strong><?php echo number_format($totalEstimate); ?></strong> pins for "<strong><?php echo h($q); ?></strong>"
            <?php endif; ?>
            
            <?php if ($searchTime < 0.01): ?>
                <span class="time-badge">⚡ Cached</span>
            <?php else: ?>
                <span class="time-badge">🚀 <?php echo $searchTime; ?>s</span>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <main>
        <?php if (!empty($results)): ?>
            <div class="pinterest-grid">
                <?php foreach ($results as $item): ?>
                    <?php
                    $tags = getTags($item['tags']);
                    $link = h($item['link'] ?? '#');
                    $hasImage = !empty($item['thumbnail']);
                    ?>
                    <article class="pin" data-link="<?php echo $link; ?>">
                        <div class="pin-content">
                            <div class="pin-img-wrapper">
                                <?php if ($hasImage): ?>
                                    <img src="<?php echo h($item['thumbnail']); ?>" 
                                         alt="" 
                                         class="pin-img"
                                         loading="lazy"
                                         decoding="async"
                                         onerror="this.style.display='none'; this.parentElement.innerHTML='<div class=\'no-img\'>No image</div>';">
                                <?php else: ?>
                                    <div class="no-img">
                                        <svg width="32" height="32" fill="currentColor" viewBox="0 0 24 24">
                                            <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
                                        </svg>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="pin-overlay"></div>
                                <button class="pin-save-btn">Save</button>
                            </div>
                            
                            <div class="pin-info">
                                <h3 class="pin-title"><?php echo h($item['title']); ?></h3>
                                
                                <?php if (!empty($tags)): ?>
                                    <div class="pin-tags">
                                        <?php foreach ($tags as $tag): ?>
                                            <span class="tag"><?php echo h($tag); ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="pin-meta">
                                    <?php if (!empty($item['author'])): ?>
                                        <span class="pin-author"><?php echo h($item['author']); ?></span>
                                    <?php else: ?>
                                        <span></span>
                                    <?php endif; ?>
                                    <span><?php echo $item['date_short'] ?? ''; ?></span>
                                </div>
                            </div>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>

            <?php 
            // Paginação ilimitada
            $totalPages = ceil($totalEstimate / $limit);
            if ($totalPages > 1): 
            ?>
                <nav class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?q=<?php echo urlencode($q); ?>&mode=<?php echo $mode; ?>&page=1" class="page-link">
                            « First
                        </a>
                        <a href="?q=<?php echo urlencode($q); ?>&mode=<?php echo $mode; ?>&page=<?php echo $page-1; ?>" class="page-link">
                            ‹ Prev
                        </a>
                    <?php endif; ?>
                    
                    <?php
                    // Mostrar páginas ao redor da atual
                    $range = 3;
                    $start = max(1, $page - $range);
                    $end = min($totalPages, $page + $range);
                    
                    // Primeira página sempre visível
                    if ($start > 1) {
                        echo '<a href="?q=' . urlencode($q) . '&mode=' . $mode . '&page=1" class="page-link">1</a>';
                        if ($start > 2) echo '<span class="page-dots">...</span>';
                    }
                    
                    // Páginas do range
                    for ($i = $start; $i <= $end; $i++):
                        if ($i == $page): ?>
                            <span class="page-link active"><?php echo $i; ?></span>
                        <?php else: ?>
                            <a href="?q=<?php echo urlencode($q); ?>&mode=<?php echo $mode; ?>&page=<?php echo $i; ?>" class="page-link">
                                <?php echo $i; ?>
                            </a>
                        <?php endif;
                    endfor;
                    
                    // Última página sempre visível
                    if ($end < $totalPages) {
                        if ($end < $totalPages - 1) echo '<span class="page-dots">...</span>';
                        echo '<a href="?q=' . urlencode($q) . '&mode=' . $mode . '&page=' . $totalPages . '" class="page-link">' . $totalPages . '</a>';
                    }
                    ?>
                    
                    <?php if ($page < $totalPages): ?>
                        <a href="?q=<?php echo urlencode($q); ?>&mode=<?php echo $mode; ?>&page=<?php echo $page+1; ?>" class="page-link">
                            Next ›
                        </a>
                        <a href="?q=<?php echo urlencode($q); ?>&mode=<?php echo $mode; ?>&page=<?php echo $totalPages; ?>" class="page-link">
                            Last »
                        </a>
                    <?php endif; ?>
                </nav>
            <?php endif; ?>
            
        <?php elseif ($q): ?>
            <div class="message">
                <h2>No pins found</h2>
                <p>Try different keywords or search mode</p>
            </div>
        <?php else: ?>
            <div class="message">
                <h2>Discover ideas</h2>
                <p>Search millions of pins</p>
            </div>
        <?php endif; ?>
    </main>

    <script>
        // Abrir links
        document.querySelectorAll('.pin').forEach(pin => {
            pin.addEventListener('click', function(e) {
                if (!e.target.classList.contains('pin-save-btn') && 
                    !e.target.classList.contains('tag')) {
                    const link = this.dataset.link;
                    if (link && link !== '#') {
                        window.open(link, '_blank');
                    }
                }
            });
        });
        
        // Save button (exemplo)
        document.querySelectorAll('.pin-save-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                this.textContent = 'Saved!';
                this.style.background = '#111';
            });
        });
        
        // Auto-focus search
        if (!document.querySelector('.search-input').value) {
            document.querySelector('.search-input').focus();
        }
        
        // Lazy loading de imagens nativas
        if ('loading' in HTMLImageElement.prototype) {
            // Browser suporta lazy loading nativo
        } else {
            // Fallback para browsers antigos
            const images = document.querySelectorAll('img[loading="lazy"]');
            const imageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        img.removeAttribute('loading');
                        imageObserver.unobserve(img);
                    }
                });
            });
            images.forEach(img => imageObserver.observe(img));
        }
    </script>
</body>
</html>