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12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// SketchVerse - Main Application Logic

// Data: Gallery Items
const galleryData = [
    {
        id: 1,
        title: "Ethereal Gaze",
        category: "portrait",
        image: "http://static.photos/people/640x800/1",
        description: "Hyper-realistic portrait exploring human emotion"
    },
    {
        id: 2,
        title: "Mountain Solitude",
        category: "landscape",
        image: "http://static.photos/nature/640x480/2",
        description: "Dramatic mountain landscape in graphite"
    },
    {
        id: 3,
        title: "Timeless Wisdom",
        category: "portrait",
        image: "http://static.photos/people/640x800/3",
        description: "Elder portrait capturing years of stories"
    },
    {
        id: 4,
        title: "Urban Dreams",
        category: "conceptual",
        image: "http://static.photos/cityscape/640x480/4",
        description: "Surreal cityscape blending reality and imagination"
    },
    {
        id: 5,
        title: "Silent Observer",
        category: "portrait",
        image: "http://static.photos/people/640x800/5",
        description: "Contemplative portrait study"
    },
    {
        id: 6,
        title: "Forest Whispers",
        category: "landscape",
        image: "http://static.photos/nature/640x800/6",
        description: "Detailed forest scene with dramatic lighting"
    },
    {
        id: 7,
        title: "The Musician",
        category: "portrait",
        image: "http://static.photos/people/640x800/7",
        description: "Portrait of a classical guitarist"
    },
    {
        id: 8,
        title: "Abstract Thoughts",
        category: "conceptual",
        image: "http://static.photos/abstract/640x640/8",
        description: "Conceptual piece exploring consciousness"
    },
    {
        id: 9,
        title: "Coastal Serenity",
        category: "landscape",
        image: "http://static.photos/nature/640x480/9",
        description: "Seascape capturing the calm of the ocean"
    }
];

// State Management
const state = {
    currentFilter: 'all',
    modalOpen: false,
    currentImageIndex: 0,
    zoomLevel: 1,
    darkMode: false,
    displayedItems: 6
};

// DOM Elements
const elements = {
    galleryGrid: document.getElementById('gallery-grid'),
    filterButtons: document.querySelectorAll('.filter-btn'),
    modal: document.getElementById('image-modal'),
    modalImage: document.getElementById('modal-image'),
    modalTitle: document.getElementById('modal-title'),
    modalCategory: document.getElementById('modal-category'),
    modalClose: document.getElementById('modal-close'),
    modalBackdrop: document.getElementById('modal-backdrop'),
    modalZoomIn: document.getElementById('modal-zoom-in'),
    modalZoomOut: document.getElementById('modal-zoom-out'),
    modalShare: document.getElementById('modal-share'),
    loadMoreBtn: document.getElementById('load-more'),
    themeToggle: document.getElementById('theme-toggle'),
    contactForm: document.getElementById('contact-form'),
    toast: document.getElementById('toast'),
    toastMessage: document.getElementById('toast-message'),
    installBtn: document.getElementById('install-btn'),
    header: document.getElementById('main-header')
};

// Initialize App
document.addEventListener('DOMContentLoaded', () => {
    initGallery();
    initEventListeners();
    initTheme();
    initScrollEffects();
    initLazyLoading();
});

// Gallery Functions
function initGallery() {
    renderGallery();
}

function renderGallery() {
    const filtered = state.currentFilter === 'all' 
        ? galleryData 
        : galleryData.filter(item => item.category === state.currentFilter);
    
    const toShow = filtered.slice(0, state.displayedItems);
    
    elements.galleryGrid.innerHTML = toShow.map((item, index) => `
        <article class="gallery-item group relative bg-white dark:bg-primary-800 rounded-2xl overflow-hidden shadow-md hover:shadow-2xl transition-all duration-500 animate-fade-in stagger-${(index % 6) + 1}" data-category="${item.category}">
            <div class="aspect-w-4 aspect-h-5 md:aspect-w-3 md:aspect-h-4 overflow-hidden bg-primary-200 dark:bg-primary-700">
                <img 
                    src="${item.image}" 
                    alt="${item.title}" 
                    class="w-full h-full object-cover transform group-hover:scale-105 transition-transform duration-700"
                    loading="lazy"
                >
                <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
            </div>
            <div class="absolute bottom-0 left-0 right-0 p-6 transform translate-y-full group-hover:translate-y-0 transition-transform duration-300">
                <h3 class="text-white font-serif text-xl font-bold mb-1">${item.title}</h3>
                <p class="text-white/80 text-sm capitalize">${item.category}</p>
            </div>
            <button class="absolute top-4 right-4 w-10 h-10 bg-white/90 dark:bg-primary-900/90 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 hover:scale-110 focus:outline-none focus:ring-2 focus:ring-secondary-500" onclick="openModal(${item.id})" aria-label="View ${item.title}">
                <i data-feather="maximize-2" class="w-5 h-5 text-primary-900 dark:text-primary-100"></i>
            </button>
        </article>
    `).join('');
    
    // Update load more button visibility
    if (state.displayedItems >= filtered.length) {
        elements.loadMoreBtn.style.display = 'none';
    } else {
        elements.loadMoreBtn.style.display = 'inline-block';
    }
    
    // Re-initialize feather icons for new content
    if (typeof feather !== 'undefined') {
        feather.replace();
    }
}

// Filter Functionality
function initEventListeners() {
    // Filter buttons
    elements.filterButtons.forEach(btn => {
        btn.addEventListener('click', (e) => {
            // Update active state
            elements.filterButtons.forEach(b => {
                b.classList.remove('active', 'bg-primary-900', 'dark:bg-primary-100', 'text-primary-50', 'dark:text-primary-900');
                b.classList.add('bg-white', 'dark:bg-primary-800', 'text-primary-600', 'dark:text-primary-300');
                b.setAttribute('aria-selected', 'false');
            });
            
            e.target.classList.remove('bg-white', 'dark:bg-primary-800', 'text-primary-600', 'dark:text-primary-300');
            e.target.classList.add('active', 'bg-primary-900', 'dark:bg-primary-100', 'text-primary-50', 'dark:text-primary-900');
            e.target.setAttribute('aria-selected', 'true');
            
            // Update state and render
            state.currentFilter = e.target.dataset.filter;
            state.displayedItems = 6;
            renderGallery();
        });
    });
    
    // Load more
    elements.loadMoreBtn.addEventListener('click', () => {
        state.displayedItems += 3;
        renderGallery();
    });
    
    // Modal controls
    elements.modalClose.addEventListener('click', closeModal);
    elements.modalBackdrop.addEventListener('click', closeModal);
    elements.modalZoomIn.addEventListener('click', () => adjustZoom(0.25));
    elements.modalZoomOut.addEventListener('click', () => adjustZoom(-0.25));
    elements.modalShare.addEventListener('click', shareImage);
    
    // Keyboard navigation
    document.addEventListener('keydown', (e) => {
        if (!state.modalOpen) return;
        
        if (e.key === 'Escape') closeModal();
        if (e.key === 'ArrowLeft') navigateModal(-1);
        if (e.key === 'ArrowRight') navigateModal(1);
    });
    
    // Touch gestures for modal
    let touchStartX = 0;
    let touchEndX = 0;
    
    elements.modal.addEventListener('touchstart', (e) => {
        touchStartX = e.changedTouches[0].screenX;
    }, {passive: true});
    
    elements.modal.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].screenX;
        handleSwipe();
    }, {passive: true});
    
    function handleSwipe() {
        const diff = touchStartX - touchEndX;
        if (Math.abs(diff) > 50) {
            if (diff > 0) navigateModal(1);
            else navigateModal(-1);
        }
    }
    
    // Theme toggle
    elements.themeToggle.addEventListener('click', toggleTheme);
    
    // Contact form
    elements.contactForm.addEventListener('submit', handleFormSubmit);
    
    // Install button
    let deferredPrompt;
    window.addEventListener('beforeinstallprompt', (e) => {
        e.preventDefault();
        deferredPrompt = e;
        elements.installBtn.classList.remove('hidden');
        elements.installBtn.classList.add('flex');
    });
    
    elements.installBtn.addEventListener('click', async () => {
        if (!deferredPrompt) return;
        deferredPrompt.prompt();
        const { outcome } = await deferredPrompt.userChoice;
        if (outcome === 'accepted') {
            showToast('App installed successfully!');
        }
        deferredPrompt = null;
        elements.installBtn.classList.add('hidden');
        elements.installBtn.classList.remove('flex');
    });
    
    // Mobile nav active state
    const mobileNavLinks = document.querySelectorAll('nav[aria-label="Mobile navigation"] a');
    const sections = document.querySelectorAll('section[id]');
    
    window.addEventListener('scroll', () => {
        let current = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;
            if (scrollY >= sectionTop - 200) {
                current = section.getAttribute('id');
            }
        });
        
        mobileNavLinks.forEach(link => {
            link.classList.remove('text-secondary-600', 'dark:text-secondary-400');
            link.classList.add('text-primary-400', 'dark:text-primary-500');
            if (link.getAttribute('href') === `#${current}`) {
                link.classList.remove('text-primary-400', 'dark:text-primary-500');
                link.classList.add('text-secondary-600', 'dark:text-secondary-400');
            }
        });
    });
}

// Modal Functions
function openModal(id) {
    const item = galleryData.find(i => i.id === id);
    if (!item) return;
    
    state.currentImageIndex = galleryData.indexOf(item);
    state.zoomLevel = 1;
    
    elements.modalImage.src = item.image;
    elements.modalImage.style.transform = `scale(${state.zoomLevel})`;
    elements.modalTitle.textContent = item.title;
    elements.modalCategory.textContent = item.category.charAt(0).toUpperCase() + item.category.slice(1);
    
    elements.modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    state.modalOpen = true;
    
    // Preload adjacent images
    preloadAdjacentImages();
}

function closeModal() {
    elements.modal.classList.add('hidden');
    document.body.style.overflow = '';
    state.modalOpen = false;
    state.zoomLevel = 1;
}

function adjustZoom(delta) {
    state.zoomLevel = Math.max(0.5, Math.min(3, state.zoomLevel + delta));
    elements.modalImage.style.transform = `scale(${state.zoomLevel})`;
}

function navigateModal(direction) {
    let newIndex = state.currentImageIndex + direction;
    
    // Filter logic for navigation
    const filtered = state.currentFilter === 'all' 
        ? galleryData 
        : galleryData.filter(item => item.category === state.currentFilter);
    
    if (newIndex < 0) newIndex = filtered.length - 1;
    if (newIndex >= filtered.length) newIndex = 0;
    
    const item = filtered[newIndex];
    state.currentImageIndex = galleryData.indexOf(item);
    
    // Animate transition
    elements.modalImage.style.opacity = '0';
    setTimeout(() => {
        elements.modalImage.src = item.image;
        elements.modalTitle.textContent = item.title;
        elements.modalCategory.textContent = item.category.charAt(0).toUpperCase() + item.category.slice(1);
        state.zoomLevel = 1;
        elements.modalImage.style.transform = `scale(${state.zoomLevel})`;
        elements.modalImage.style.opacity = '1';
    }, 200);
}

function preloadAdjacentImages() {
    const filtered = state.currentFilter === 'all' 
        ? galleryData 
        : galleryData.filter(item => item.category === state.currentFilter);
    
    [-1, 1].forEach(offset => {
        let index = state.currentImageIndex + offset;
        if (index < 0) index = filtered.length - 1;
        if (index >= filtered.length) index = 0;
        
        const img = new Image();
        img.src = filtered[index].image;
    });
}

async function shareImage() {
    const item = galleryData[state.currentImageIndex];
    
    if (navigator.share) {
        try {
            await navigator.share({
                title: item.title,
                text: `Check out this amazing pencil sketch: ${item.title}`,
                url: window.location.href
            });
        } catch (err) {
            console.log('Share cancelled');
        }
    } else {
        // Fallback: copy to clipboard
        navigator.clipboard.writeText(window.location.href);
        showToast('Link copied to clipboard!');
    }
}

// Theme Functions
function initTheme() {
    const savedTheme = localStorage.getItem('theme');
    const systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    
    if (savedTheme === 'dark' || (!savedTheme && systemDark)) {
        document.documentElement.classList.add('dark');
        state.darkMode = true;
    }
}

function toggleTheme() {
    state.darkMode = !state.darkMode;
    document.documentElement.classList.toggle('dark');
    localStorage.setItem('theme', state.darkMode ? 'dark' : 'light');
    
    // Update icon
    setTimeout(() => {
        if (typeof feather !== 'undefined') {
            feather.replace();
        }
    }, 100);
}

// Form Handling
function handleFormSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData);
    
    // Simulate API call
    const submitBtn = e.target.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i data-feather="loader" class="w-5 h-5 animate-spin mx-auto"></i>';
    feather.replace();
    
    setTimeout(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
        e.target.reset();
        showToast('Message sent successfully! I\'ll get back to you soon.');
    }, 1500);
}

function showToast(message) {
    elements.toastMessage.textContent = message;
    elements.toast.classList.remove('translate-y-20', 'opacity-0');
    
    setTimeout(() => {
        elements.toast.classList.add('translate-y-20', 'opacity-0');
    }, 3000);
}

// Scroll Effects
function initScrollEffects() {
    let lastScroll = 0;
    
    window.addEventListener('scroll', () => {
        const currentScroll = window.pageYOffset;
        
        // Header hide/show on mobile
        if (window.innerWidth < 768) {
            if (currentScroll > lastScroll && currentScroll > 100) {
                elements.header.style.transform = 'translateY(-100%)';
            } else {
                elements.header.style.transform = 'translateY(0)';
            }
        }
        
        lastScroll = currentScroll;
    });
    
    // Intersection Observer for animations
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-slide-up');
                entry.target.style.opacity = '1';
            }
        });
    }, observerOptions);
    
    document.querySelectorAll('section h2, section p').forEach(el => {
        el.style.opacity = '0';
        observer.observe(el);
    });
}

// Lazy Loading
function initLazyLoading() {
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src || img.src;
                img.classList.remove('img-skeleton');
                observer.unobserve(img);
            }
        });
    });
    
    document.querySelectorAll('img[loading="lazy"]').forEach(img => {
        imageObserver.observe(img);
    });
}

// Performance: Debounce resize
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        // Recalculate layout if needed
        if (state.modalOpen) {
            closeModal();
        }
    }, 250);
});