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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
// Global variables
let currentTab = 1;
const charts = {};

// Initialize the app
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    feather.replace();
    showTab(currentTab);
});

// Tab switching functionality
function switchTab(tabNumber) {
    currentTab = tabNumber;
    showTab(tabNumber);
    updateNavigation(tabNumber);
}

function showTab(tabNumber) {
    // Hide all tabs
    const allTabs = document.querySelectorAll('.tab-content');
    allTabs.forEach(tab => tab.classList.add('hidden'));
    
    // Show selected tab
    const selectedTab = document.getElementById(`tab${tabNumber}`);
    if (selectedTab) {
        selectedTab.classList.remove('hidden');
    }
}

function updateNavigation(activeTab) {
    const navButtons = document.querySelectorAll('.nav-btn');
    navButtons.forEach(btn => {
        if (parseInt(btn.dataset.tab) === activeTab) {
            btn.classList.add('text-green-600');
            btn.classList.remove('text-gray-600');
        } else {
            btn.classList.remove('text-green-600');
            btn.classList.add('text-gray-600');
        }
    });
}

// Initialize charts
function initializeCharts() {
    // Yield Chart (Bar Chart)
    const yieldCanvas = document.getElementById('yieldChart');
    if (yieldCanvas) {
        const ctx = yieldCanvas.getContext('2d');
        drawBarChart(ctx, yieldCanvas, {
            labels: ['ปีที่ 1', 'ปีที่ 2', 'ปีที่ 3'],
            datasets: [
                {
                    label: 'ก่อนใช้ใจเกษตร',
                    data: [3.2, 3.3, 3.1],
                    color: '#ef4444'
                },
                {
                    label: 'หลังใช้ใจเกษตร',
                    data: [4.2, 4.5, 4.6],
                    color: '#22c55e'
                }
            ]
        });
    }

    // Cost Chart (Pie Chart)
    const costCanvas = document.getElementById('costChart');
    if (costCanvas) {
        const ctx = costCanvas.getContext('2d');
        drawPieChart(ctx, costCanvas, {
            labels: ['ปุ๋ยเคมีเดิม', 'ใจเกษตร', 'อื่นๆ'],
            data: [60, 25, 15],
            colors: ['#ef4444', '#22c55e', '#e5e7eb']
        });
    }

    // Price Chart (Line Chart)
    const priceCanvas = document.getElementById('priceChart');
    if (priceCanvas) {
        const ctx = priceCanvas.getContext('2d');
        drawLineChart(ctx, priceCanvas, {
            labels: Array.from({length: 30}, (_, i) => `วันที่ ${i+1}`),
            data: [14.2, 14.3, 14.5, 14.4, 14.6, 14.5, 14.7, 14.8, 14.9, 14.8, 
                   14.9, 15.0, 15.1, 15.0, 14.9, 14.8, 14.7, 14.9, 15.0, 15.1,
                   15.2, 15.3, 15.2, 15.1, 15.0, 14.9, 15.0, 15.1, 15.2, 15.0],
            color: '#16a34a'
        });
    }
}

// Simple bar chart drawing
function drawBarChart(ctx, canvas, data) {
    const width = canvas.width;
    const height = canvas.height;
    const padding = 40;
    const barWidth = (width - padding * 2) / (data.labels.length * 3);
    const maxValue = 5;

    ctx.clearRect(0, 0, width, height);

    // Draw axes
    ctx.strokeStyle = '#e5e7eb';
    ctx.beginPath();
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, height - padding);
    ctx.lineTo(width - padding, height - padding);
    ctx.stroke();

    // Draw bars
    data.labels.forEach((label, i) => {
        const x = padding + i * barWidth * 3 + barWidth / 2;
        
        // Draw bars for each dataset
        data.datasets.forEach((dataset, j) => {
            const value = dataset.data[i];
            const barHeight = (value / maxValue) * (height - padding * 2);
            const barX = x + j * barWidth;
            const barY = height - padding - barHeight;
            
            ctx.fillStyle = dataset.color;
            ctx.fillRect(barX, barY, barWidth - 5, barHeight);
        });

        // Draw labels
        ctx.fillStyle = '#374151';
        ctx.font = '12px Prompt';
        ctx.textAlign = 'center';
        ctx.fillText(label, x + barWidth, height - padding + 20);
    });

    // Draw legend
    ctx.font = '12px Prompt';
    let legendY = 20;
    data.datasets.forEach((dataset) => {
        ctx.fillStyle = dataset.color;
        ctx.fillRect(width - 150, legendY - 10, 15, 15);
        ctx.fillStyle = '#374151';
        ctx.textAlign = 'left';
        ctx.fillText(dataset.label, width - 130, legendY);
        legendY += 25;
    });
}

// Simple pie chart drawing
function drawPieChart(ctx, canvas, data) {
    const width = canvas.width;
    const height = canvas.height;
    const centerX = width / 2;
    const centerY = height / 2;
    const radius = Math.min(width, height) / 2 - 40;
    const total = data.data.reduce((a, b) => a + b, 0);
    let currentAngle = -Math.PI / 2;

    ctx.clearRect(0, 0, width, height);

    // Draw pie slices
    data.data.forEach((value, i) => {
        const sliceAngle = (value / total) * 2 * Math.PI;
        
        ctx.beginPath();
        ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
        ctx.lineTo(centerX, centerY);
        ctx.fillStyle = data.colors[i];
        ctx.fill();
        
        // Draw percentage
        const percentage = ((value / total) * 100).toFixed(1) + '%';
        const textAngle = currentAngle + sliceAngle / 2;
        const textX = centerX + Math.cos(textAngle) * (radius / 2);
        const textY = centerY + Math.sin(textAngle) * (radius / 2);
        
        ctx.fillStyle = 'white';
        ctx.font = 'bold 14px Prompt';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(percentage, textX, textY);
        
        currentAngle += sliceAngle;
    });

    // Draw legend
    ctx.font = '12px Prompt';
    let legendY = 20;
    data.labels.forEach((label, i) => {
        ctx.fillStyle = data.colors[i];
        ctx.fillRect(10, legendY - 10, 15, 15);
        ctx.fillStyle = '#374151';
        ctx.textAlign = 'left';
        ctx.fillText(`${label}: ${data.data[i]}%`, 30, legendY);
        legendY += 25;
    });
}

// Simple line chart drawing
function drawLineChart(ctx, canvas, data) {
    const width = canvas.width;
    const height = canvas.height;
    const padding = 40;
    const pointSpacing = (width - padding * 2) / (data.labels.length - 1);
    const maxValue = Math.max(...data.data);
    const minValue = Math.min(...data.data);
    const valueRange = maxValue - minValue;

    ctx.clearRect(0, 0, width, height);

    // Draw axes
    ctx.strokeStyle = '#e5e7eb';
    ctx.beginPath();
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, height - padding);
    ctx.lineTo(width - padding, height - padding);
    ctx.stroke();

    // Draw line
    ctx.strokeStyle = data.color;
    ctx.lineWidth = 2;
    ctx.beginPath();

    data.data.forEach((value, i) => {
        const x = padding + i * pointSpacing;
        const y = height - padding - ((value - minValue) / valueRange) * (height - padding * 2);
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    });
    
    ctx.stroke();

    // Draw points
    data.data.forEach((value, i) => {
        const x = padding + i * pointSpacing;
        const y = height - padding - ((value - minValue) / valueRange) * (height - padding * 2);
        
        ctx.beginPath();
        ctx.arc(x, y, 3, 0, Math.PI * 2);
        ctx.fillStyle = data.color;
        ctx.fill();
    });

    // Draw Y-axis labels
    ctx.fillStyle = '#6b7280';
    ctx.font = '10px Prompt';
    ctx.textAlign = 'right';
    for (let i = 0; i <= 5; i++) {
        const value = minValue + (valueRange * i / 5);
        const y = height - padding - (i / 5) * (height - padding * 2);
        ctx.fillText(value.toFixed(1) + 'k', padding - 10, y + 3);
    }

    // Draw X-axis label
    ctx.fillStyle = '#6b7280';
    ctx.font = '10px Prompt';
    ctx.textAlign = 'center';
    ctx.fillText('30 วันย้อนหลัง', width / 2, height - 10);
}

// Modal functions
function showNotifications() {
    const modal = document.getElementById('notificationModal');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function closeNotifications() {
    const modal = document.getElementById('notificationModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}

function showProfile() {
    switchTab(8);
}

// Action functions
function calculateYield() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center';
    modal.innerHTML = `
        <div class="bg-white rounded-lg p-6 m-4 max-w-sm w-full">
            <h3 class="text-lg font-bold mb-4">คำนวณผลผลิตใหม่</h3>
            <div class="space-y-3">
                <input type="number" placeholder="พื้นที่ (ไร่)" class="w-full p-3 border rounded-lg">
                <input type="number" placeholder="ผลผลิตปีที่แล้ว (ตัน)" class="w-full p-3 border rounded-lg">
                <select class="w-full p-3 border rounded-lg">
                    <option>ข้าวโพดหวาน</option>
                    <option>ข้าวหอมมะลิ</option>
                    <option>มะละกอ</option>
                    <option>มะเขือเทศ</option>
                </select>
            </div>
            <div class="flex space-x-2 mt-4">
                <button onclick="this.closest('.fixed').remove()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg">
                    ยกเลิก
                </button>
                <button onclick="calculateNewYield(this)" class="flex-1 bg-green-600 text-white py-2 rounded-lg">
                    คำนวณ
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

function calculateNewYield(button) {
    button.innerHTML = '<div class="spinner inline-block w-4 h-4"></div>';
    setTimeout(() => {
        button.closest('.fixed').remove();
        showSuccessToast('คำนวณผลผลิตสำเร็จ! คาดว่าผลผลิตเพิ่มขึ้น 35%');
    }, 1000);
}

function viewNationalPrices() {
    showSuccessToast('กำลังโหลดข้อมูลราคาทั่วประเทศ...');
}

function downloadPDF() {
    showSuccessToast('กำลังดาวน์โหลด Crop Cycle เป็น PDF...');
}

function addProduct() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center';
    modal.innerHTML = `
        <div class="bg-white rounded-lg p-6 m-4 max-w-sm w-full">
            <h3 class="text-lg font-bold mb-4">เพิ่มผลผลิตใหม่</h3>
            <div class="space-y-3">
                <input type="text" placeholder="ชื่อผลผลิต" class="w-full p-3 border rounded-lg">
                <input type="number" placeholder="ปริมาณ (กก.)" class="w-full p-3 border rounded-lg">
                <input type="number" placeholder="ราคาขายที่เสนอ (บาท/กก.)" class="w-full p-3 border rounded-lg">
                <input type="date" class="w-full p-3 border rounded-lg">
            </div>
            <div class="flex space-x-2 mt-4">
                <button onclick="this.closest('.fixed').remove()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg">
                    ยกเลิก
                </button>
                <button onclick="submitProduct(this)" class="flex-1 bg-green-600 text-white py-2 rounded-lg">
                    บันทึก
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

function submitProduct(button) {
    button.innerHTML = '<div class="spinner inline-block w-4 h-4"></div>';
    setTimeout(() => {
        button.closest('.fixed').remove();
        showSuccessToast('เพิ่มผลผลิตสำเร็จ! กำลังจับคู่ผู้ซื้อ...');
    }, 1000);
}

function becomeCoach() {
    showSuccessToast('กำลังดำเนินการสมัคร... ทีมงานจะติดต่อกลับโดยเร็ว!');
}

// Toast notification
function showSuccessToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed top-20 left-4 right-4 bg-green-600 text-white p-4 rounded-lg shadow-lg z-50 success-animation';
    toast.innerHTML = `
        <div class="flex items-center space-x-2">
            <i data-feather="check-circle" class="w-5 h-5"></i>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    feather.replace();
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// Simulate real-time price updates
setInterval(() => {
    const priceElements = document.querySelectorAll('.text-green-600, .text-red-600');
    priceElements.forEach(el => {
        if (el.textContent.includes('↑') || el.textContent.includes('↓')) {
            // Simulate price change animation
            el.style.transform = 'scale(1.1)';
            setTimeout(() => {
                el.style.transform = 'scale(1)';
            }, 200);
        }
    });
}, 5000);

// Pull to refresh functionality
let startY = 0;
let isPulling = false;

document.addEventListener('touchstart', (e) => {
    if (window.scrollY === 0) {
        startY = e.touches[0].pageY;
        isPulling = true;
    }
});

document.addEventListener('touchmove', (e) => {
    if (!isPulling) return;
    
    const currentY = e.touches[0].pageY;
    const pullDistance = currentY - startY;
    
    if (pullDistance > 100 && window.scrollY === 0) {
        // Show refresh indicator
        showRefreshIndicator();
    }
});

document.addEventListener('touchend', () => {
    if (isPulling) {
        isPulling = false;
        hideRefreshIndicator();
    }
});

function showRefreshIndicator() {
    const indicator = document.createElement('div');
    indicator.id = 'refreshIndicator';
    indicator.className = 'fixed top-16 left-0 right-0 bg-green-600 text-white text-center py-2 z-40';
    indicator.textContent = 'กำลังรีเฟรชข้อมูล...';
    document.body.appendChild(indicator);
}

function hideRefreshIndicator() {
    const indicator = document.getElementById('refreshIndicator');
    if (indicator) {
        indicator.remove();
    }
}