File size: 9,958 Bytes
56de4b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
// AgroPulverize Pro - Main JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // Initialize Feather Icons
    if (typeof feather !== 'undefined') {
        feather.replace();
    }

    // Load News from RSS
    loadNews();

    // Initialize Forms
    initForms();

    // Initialize Scroll Effects
    initScrollEffects();

    // Initialize Mobile Menu
    initMobileMenu();
});

// News Loading Function
async function loadNews() {
    const newsContainer = document.getElementById('news-container');
    if (!newsContainer) return;

    // Using a CORS proxy to fetch RSS feed
    const rssUrls = [
        'https://www.noticiasagricolas.com.br/rss/ultimas-noticias.xml',
        'https://g1.globo.com/rss/g1/agronegocios/'
    ];

    try {
        // Fallback to mock news if RSS fails
        const mockNews = [
            {
                title: 'Drones agrícolas aumentam produtividade em 40% no Mato Grosso',
                description: 'Estudo mostra que pulverização aérea com drones reduziu custos e aumentou eficiência na aplicação de defensivos.',
                image: 'http://static.photos/agriculture/640x360/101',
                date: '15 Jan 2025',
                category: 'Tecnologia'
            },
            {
                title: 'Governo libera novos créditos para modernização do campo',
                description: 'Produtores rurais terão acesso a financiamentos com taxas reduzidas para aquisição de equipamentos de precisão.',
                image: 'http://static.photos/finance/640x360/202',
                date: '14 Jan 2025',
                category: 'Política'
            },
            {
                title: 'Sustentabilidade: práticas agrícolas de baixo carbono crescem no Brasil',
                description: 'Movimento por agricultura regenerativa ganha força entre grandes produtores do Centro-Oeste.',
                image: 'http://static.photos/nature/640x360/303',
                date: '13 Jan 2025',
                category: 'Sustentabilidade'
            }
        ];

        // Try to fetch real news, fallback to mock
        let news = mockNews;
        
        try {
            const response = await fetch('https://api.rss2json.com/v1/api.json?rss_url=' + encodeURIComponent(rssUrls[0]));
            const data = await response.json();
            
            if (data.items && data.items.length > 0) {
                news = data.items.slice(0, 3).map((item, index) => ({
                    title: item.title,
                    description: item.description ? item.description.replace(/<[^>]*>/g, '').substring(0, 120) + '...' : 'Leia mais sobre esta notícia...',
                    image: `http://static.photos/agriculture/640x360/${400 + index}`,
                    date: new Date(item.pubDate).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' }),
                    category: 'Agronegócio',
                    link: item.link
                }));
            }
        } catch (e) {
            console.log('Using mock news data');
        }

        renderNews(news);
    } catch (error) {
        console.error('Error loading news:', error);
        newsContainer.innerHTML = '<p class="text-secondary-500 text-center col-span-3">Não foi possível carregar as notícias.</p>';
    }
}

function renderNews(news) {
    const newsContainer = document.getElementById('news-container');
    
    newsContainer.innerHTML = news.map((item, index) => `
        <article class="news-card bg-secondary-50 rounded-2xl overflow-hidden group cursor-pointer" onclick="window.open('${item.link || '#'}', '_blank')">
            <div class="relative h-48 overflow-hidden">
                <img src="${item.image}" alt="${item.title}" class="news-image w-full h-full object-cover">
                <div class="absolute top-4 left-4">
                    <span class="bg-primary-500 text-white text-xs font-semibold px-3 py-1 rounded-full">${item.category}</span>
                </div>
            </div>
            <div class="p-6">
                <div class="flex items-center gap-2 text-secondary-400 text-sm mb-3">
                    <i data-feather="calendar" class="w-4 h-4"></i>
                    <span>${item.date}</span>
                </div>
                <h3 class="font-bold text-secondary-900 mb-2 line-clamp-2 group-hover:text-primary-600 transition-colors">${item.title}</h3>
                <p class="text-secondary-600 text-sm line-clamp-2">${item.description}</p>
                <div class="mt-4 flex items-center gap-2 text-primary-600 font-medium text-sm group-hover:gap-3 transition-all">
                    Ler mais
                    <i data-feather="arrow-right" class="w-4 h-4"></i>
                </div>
            </div>
        </article>
    `).join('');

    // Re-initialize Feather Icons for new content
    if (typeof feather !== 'undefined') {
        feather.replace();
    }
}

// Form Initialization
function initForms() {
    // Contact Form
    const contactForm = document.getElementById('contact-form');
    if (contactForm) {
        contactForm.addEventListener('submit', handleContactSubmit);
    }

    // Login Form
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLoginSubmit);
    }
}

function handleContactSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData);
    
    // Show success message
    showToast('Mensagem enviada com sucesso! Entraremos em contato em breve.', 'success');
    
    // Reset form
    e.target.reset();
    
    // Here you would typically send to a server
    console.log('Contact form data:', data);
}

function handleLoginSubmit(e) {
    e.preventDefault();
    
    // Simulate login
    showToast('Área do cliente em desenvolvimento. Entre em contato pelo WhatsApp!', 'error');
    
    e.target.reset();
}

// Toast Notification
function showToast(message, type = 'success') {
    // Remove existing toasts
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
        existingToast.remove();
    }

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 ${type === 'success' ? 'bg-green-100' : 'bg-red-100'} rounded-full flex items-center justify-center">
                <i data-feather="${type === 'success' ? 'check' : 'alert-circle'}" class="w-5 h-5 ${type === 'success' ? 'text-green-600' : 'text-red-600'}"></i>
            </div>
            <div>
                <div class="font-semibold text-secondary-900">${type === 'success' ? 'Sucesso!' : 'Atenção'}</div>
                <div class="text-secondary-600 text-sm">${message}</div>
            </div>
        </div>
    `;

    document.body.appendChild(toast);

    // Initialize feather icons in toast
    if (typeof feather !== 'undefined') {
        feather.replace();
    }

    // Show toast
    requestAnimationFrame(() => {
        toast.classList.add('show');
    });

    // Hide after 4 seconds
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}

// Scroll Effects
function initScrollEffects() {
    const navbar = document.querySelector('agro-navbar');
    if (!navbar) return;

    const shadowRoot = navbar.shadowRoot;
    if (!shadowRoot) return;

    const nav = shadowRoot.querySelector('nav');
    if (!nav) return;

    let lastScroll = 0;

    window.addEventListener('scroll', () => {
        const currentScroll = window.pageYOffset;
        
        if (currentScroll > 100) {
            nav.classList.add('bg-white/95', 'backdrop-blur-md', 'shadow-lg');
            nav.classList.remove('bg-transparent');
        } else {
            nav.classList.remove('bg-white/95', 'backdrop-blur-md', 'shadow-lg');
            nav.classList.add('bg-transparent');
        }

        lastScroll = currentScroll;
    }, { passive: true });

    // Smooth scroll for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href === '#') return;
            
            const target = document.querySelector(href);
            if (target) {
                e.preventDefault();
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
}

// Mobile Menu
function initMobileMenu() {
    // Mobile menu functionality is handled in the navbar component
}

// Utility: Format Phone Number
function formatPhone(value) {
    return value
        .replace(/\D/g, '')
        .replace(/(\d{2})(\d)/, '($1) $2')
        .replace(/(\d{5})(\d)/, '$1-$2')
        .replace(/(-\d{4})\d+?$/, '$1');
}

// Utility: Format CPF/CNPJ
function formatDocument(value) {
    const cleaned = value.replace(/\D/g, '');
    
    if (cleaned.length <= 11) {
        // CPF
        return cleaned
            .replace(/(\d{3})(\d)/, '$1.$2')
            .replace(/(\d{3})(\d)/, '$1.$2')
            .replace(/(\d{3})(\d{1,2})$/, '$1-$2');
    } else {
        // CNPJ
        return cleaned
            .replace(/(\d{2})(\d)/, '$1.$2')
            .replace(/(\d{3})(\d)/, '$1.$2')
            .replace(/(\d{3})(\d)/, '$1/$2')
            .replace(/(\d{4})(\d{1,2})$/, '$1-$2');
    }
}

// Auto-format inputs
document.addEventListener('input', function(e) {
    if (e.target.matches('input[type="tel"]')) {
        e.target.value = formatPhone(e.target.value);
    }
    if (e.target.matches('input[placeholder*="CPF/CNPJ"]')) {
        e.target.value = formatDocument(e.target.value);
    }
});