// === AI Cartoon Generator - Complete File ===
// Utility function to show/hide elements
function toggleElement(el, show) {
if (el) el.style.display = show ? 'block' : 'none';
}
// === Image Preview Handler ===
(function imagePreviewInit() {
const form = document.querySelector('form');
if (!form) return;
const inputs = form.querySelectorAll('input[name="pet_images[]"]');
const previewContainer = document.getElementById('image-preview-container');
if (!previewContainer) return;
inputs.forEach(input => {
input.addEventListener('change', function(e) {
const files = e.target.files;
if (!files || files.length === 0) return;
previewContainer.innerHTML = '';
Array.from(files).forEach(file => {
if (!file.type.startsWith('image/')) return;
const reader = new FileReader();
reader.onload = function(e) {
const div = document.createElement('div');
div.className = 'image-preview-item';
div.innerHTML = `
${file.name}
`;
previewContainer.appendChild(div);
};
reader.readAsDataURL(file);
});
});
});
})();
// === Style Selection Handler ===
(function styleSelectionInit() {
const form = document.querySelector('form');
if (!form) return;
const styleRadios = form.querySelectorAll('input[name="style"]');
const styleCards = document.querySelectorAll('.style-card');
styleRadios.forEach(radio => {
radio.addEventListener('change', function() {
styleCards.forEach(card => {
card.classList.remove('selected');
});
const selectedCard = this.closest('.style-card');
if (selectedCard) {
selectedCard.classList.add('selected');
}
});
});
})();
// === Generate Cartoon via OpenAI (server-side) ===
(function cartoonGenerateInit() {
const generateBtn = document.getElementById('ai-generate-btn');
const preview = document.getElementById('ai-generated-preview');
const hidden = document.getElementById('ai-generated-url');
const mockupSection = document.getElementById('mockup-preview-section');
const mockupContainer = document.getElementById('mockup-preview-container');
if (!generateBtn || !preview || !hidden) return;
generateBtn.addEventListener('click', async () => {
// Find the form - adjust selector based on your HTML structure
const form = generateBtn.closest('form') || document.querySelector('form');
if (!form) {
alert('Form not found.');
return;
}
// Pick first image from pet_images[]
const inputs = form.querySelectorAll('input[name="pet_images[]"]');
let file = null;
for (const inp of inputs) {
if (inp.files && inp.files.length > 0) {
file = inp.files[0];
break;
}
}
if (!file) {
alert('Please upload a pet image first.');
return;
}
// Get selected style from radio buttons
const selectedStyle = form.querySelector('input[name="style"]:checked');
if (!selectedStyle) {
alert('Please select a cartoon style.');
return;
}
const old = generateBtn.textContent;
generateBtn.disabled = true;
generateBtn.textContent = '🎨 Generating...';
preview.innerHTML = '
This is how your design will look on our products!