-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
662 lines (642 loc) Β· 35.4 KB
/
Copy pathscript.js
File metadata and controls
662 lines (642 loc) Β· 35.4 KB
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
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
const state = {
screen: 'landing',
params: {},
currentRole: null,
farmerProfile: null,
customerProfile: null,
cart: [],
farmers: [
{id:'f1', name:'Ramesh Yadav', village:'Barwani', district:'Madhya Pradesh', years:12, rating:4.7, deals:63, avatar:'π¨\u200dπΎ', bio:'Third-generation farmer growing tomatoes on 3.5 acres using natural pest control passed down from my father.'},
{id:'f2', name:'Sunita Devi', village:'Nashik', district:'Maharashtra', years:8, rating:4.9, deals:41, avatar:'π©\u200dπΎ', bio:'I switched to organic onion farming five years ago β better soil, better sleep, and buyers who actually know my name.'},
{id:'f3', name:'Arjun Patel', village:'Anand', district:'Gujarat', years:15, rating:4.6, deals:97, avatar:'π¨\u200dπΎ', bio:'We grow wheat the way my grandfather did β rain-fed, traditional seed, no shortcuts.'}
],
products: [
{id:'p1', farmerId:'f1', crop:'Tomato', emoji:'π
', quantity:180, unit:'kg', price:34, harvestDate:'2026-08-18', practices:['Natural Farming','No Pesticides'], story:'Picked ripe at dawn so they reach you within 24 hours of harvest.'},
{id:'p2', farmerId:'f2', crop:'Onion', emoji:'π§
', quantity:420, unit:'kg', price:26, harvestDate:'2026-08-10', practices:['Organic','Traditional Seeds'], story:'Sun-cured for a week the traditional way β no chemical drying, better shelf life.'},
{id:'p3', farmerId:'f3', crop:'Wheat', emoji:'πΎ', quantity:900, unit:'kg', price:24, harvestDate:'2026-08-05', practices:['Rain-fed','Traditional Seeds'], story:'Stone-ground quality wheat from rain-fed fields β no borewell, no shortcuts.'},
{id:'p4', farmerId:'f2', crop:'Mango (Kesar)', emoji:'π₯', quantity:75, unit:'kg', price:110, harvestDate:'2026-08-20', practices:['Organic'], story:'Tree-ripened Kesar mangoes, hand-picked in small batches to protect the skin.'}
],
orders: []
};
const STATUSES = ['Confirmed','Packed','Out for Delivery','Delivered'];
function inr(n){ return 'βΉ' + Number(n).toLocaleString('en-IN'); }
function farmerOf(id){ return state.farmers.find(f=>f.id===id); }
function productOf(id){ return state.products.find(p=>p.id===id); }
function genTrace(){ return 'KS-' + Math.random().toString(36).slice(2,6).toUpperCase() + '-' + Math.random().toString(36).slice(2,6).toUpperCase(); }
function toast(msg){
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(window._toastTimer);
window._toastTimer = setTimeout(()=>t.classList.remove('show'), 2400);
}
function navigate(screen, params={}){
state.screen = screen;
state.params = params;
window.scrollTo({top:0, behavior:'smooth'});
render();
}
function fairSplit(subtotal){
const platformFee = Math.round(subtotal*0.08);
const farmerReceives = subtotal - platformFee;
const mandiEstimate = Math.round(subtotal*0.62);
return {platformFee, farmerReceives, mandiEstimate};
}
function renderHeader(){
const cartCount = state.cart.reduce((s,c)=>s+c.qty,0);
let roleToggle = '';
if(state.farmerProfile || state.customerProfile){
roleToggle = `<div class="role-pill">
${state.farmerProfile ? `<button class="${state.currentRole==='farmer'?'active':''}" onclick="switchRole('farmer')">π¨\u200dπΎ Farmer</button>` : ''}
${state.customerProfile ? `<button class="${state.currentRole==='customer'?'active':''}" onclick="switchRole('customer')">π§Ί Customer</button>` : ''}
</div>`;
}
let cartBtn = '';
if(state.currentRole==='customer'){
cartBtn = `<button class="cart-btn" onclick="navigate('cart')">π Cart ${cartCount>0?`<span class="cart-badge">${cartCount}</span>`:''}</button>`;
}
document.getElementById('headRight').innerHTML = roleToggle + cartBtn;
}
function switchRole(role){
state.currentRole = role;
navigate(role==='farmer' ? 'farmerDashboard' : 'marketplace');
}
function renderLanding(){
return `
<section class="hero">
<div class="wrap hero-inner">
<span class="eyebrow">Farm to Fork, No Middlemen</span>
<h1>Sell direct. <span>Earn fair.</span><br>Know your farmer.</h1>
<p class="sub">KisanSetu connects farmers straight to the people who eat what they grow β transparent pricing, real traceability, and a fair cut for the person who actually grew your food.</p>
<div class="hero-cta">
<button class="btn btn-primary" onclick="navigate('farmerOnboard')">π¨βπΎ I'm a Farmer</button>
<button class="btn btn-dark" onclick="navigate('customerOnboard')">π§Ί I'm a Customer</button>
</div>
<div class="hero-tagline">"Kheti se Bazaar Tak, Seedha aur Samajhdaar" β from field to market, straight and smart.</div>
</div>
</section>
<section class="route wrap">
<h2>How it works</h2>
<p class="route-sub">One straight line from soil to your kitchen β every stop tracked, nothing hidden.</p>
<div class="route-path">
<div class="stop"><div class="stop-dot">π¨βπΎ</div><h4>Farmer registers</h4><p>Simple sign-up with farm & village details</p></div>
<div class="stop"><div class="stop-dot">π¦</div><h4>Lists produce</h4><p>Crop, quantity, harvest date & fair price</p></div>
<div class="stop"><div class="stop-dot">π</div><h4>Customer discovers</h4><p>Browses by crop, practice & farmer story</p></div>
<div class="stop"><div class="stop-dot">π§Ύ</div><h4>Orders</h4><p>Transparent price split shown before checkout</p></div>
<div class="stop"><div class="stop-dot">π</div><h4>Farmer fulfils</h4><p>Packed and shipped straight from the farm</p></div>
<div class="stop"><div class="stop-dot">π </div><h4>Customer receives</h4><p>Fresh produce, full traceability included</p></div>
</div>
</section>
<section class="impact">
<div class="wrap impact-grid">
<div class="impact-col">
<h3>πΎ For Farmers</h3>
<ul class="impact-list">
<li><span class="ic">π°</span><span><strong>Better earning potential</strong> β keep ~92% of the sale price instead of ~60% through traditional mandi chains.</span></li>
<li><span class="ic">π</span><span><strong>Direct market access</strong> β list produce in minutes, reach customers beyond your local mandi.</span></li>
<li><span class="ic">π₯</span><span><strong>Direct customer relationship</strong> β build a reputation and repeat buyers through your own farm profile.</span></li>
</ul>
</div>
<div class="impact-col">
<h3>π§Ί For Customers</h3>
<ul class="impact-list">
<li><span class="ic">π±</span><span><strong>Fresh products</strong> β harvested days, not weeks, before it reaches you.</span></li>
<li><span class="ic">π</span><span><strong>Transparent source</strong> β every order carries a traceable farm passport and trace ID.</span></li>
<li><span class="ic">π€</span><span><strong>Know your farmer</strong> β see exactly who grew your food and how.</span></li>
<li><span class="ic">π΅</span><span><strong>Fair pricing</strong> β see the exact split between what you pay and what the farmer earns.</span></li>
</ul>
</div>
</div>
</section>
<section class="footer-cta">
<h2>Ready to cut out the middlemen?</h2>
<div class="hero-cta" style="margin-top:22px;">
<button class="btn btn-primary" onclick="navigate('farmerOnboard')">Start Selling</button>
<button class="btn btn-outline" onclick="navigate('customerOnboard')">Start Buying</button>
</div>
</section>
<footer>KisanSetu β SIH Prototype Β· Market data, prices and reviews shown are simulated for demonstration.</footer>
`;
}
function renderFarmerOnboard(){
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('landing')">β Back</button>
<h2>π¨βπΎ Register as a Farmer</h2>
<p>Takes under a minute. Basic details only β verification is simplified for this prototype.</p>
</div>
<div class="wrap" style="padding-bottom:70px;">
<div class="card form-card">
<div class="field"><label>Full name</label><input type="text" id="fName" placeholder="e.g. Ramesh Yadav" value="Ramesh Yadav"></div>
<div class="row-2">
<div class="field"><label>Village</label><input type="text" id="fVillage" placeholder="e.g. Barwani" value="Barwani"></div>
<div class="field"><label>District / State</label><input type="text" id="fDistrict" placeholder="e.g. Madhya Pradesh" value="Madhya Pradesh"></div>
</div>
<div class="row-2">
<div class="field"><label>Mobile number</label><input type="text" id="fPhone" placeholder="10-digit number" value="98765 43210"></div>
<div class="field"><label>Farm size (acres)</label><input type="number" id="fSize" placeholder="e.g. 3.5" value="3.5"></div>
</div>
<div class="field"><label>Main crop grown</label><input type="text" id="fCrop" placeholder="e.g. Tomato" value="Tomato"></div>
<div class="field hint">π We'll send a one-time OTP to verify this number (simulated in this prototype).</div>
<button class="btn btn-leaf btn-block" onclick="submitFarmerOnboard()">Create Farmer Account</button>
</div>
</div>
`;
}
function submitFarmerOnboard(){
const name = document.getElementById('fName').value.trim() || 'Raghav';
const village = document.getElementById('fVillage').value.trim() || 'chindipur';
const district = document.getElementById('fDistrict').value.trim() || 'Uttar Pradesh Pradesh';
const crop = document.getElementById('fCrop').value.trim() || 'Tomato';
state.farmerProfile = {id:'you', name, village, district, avatar:'π¨\u200dπΎ', years:1, rating:5.0, deals:0, bio:`New to KisanSetu, growing ${crop} in ${village}.`};
if(!farmerOf('you')) state.farmers.push(state.farmerProfile);
state.currentRole = 'farmer';
toast(`Welcome, ${name}! Farmer account created.`);
navigate('farmerDashboard');
}
function renderFarmerDashboard(){
const fp = state.farmerProfile;
const myListings = state.products.filter(p=>p.farmerId==='you');
const myOrders = state.orders.filter(o=>o.farmerId==='you');
const earnings = myOrders.reduce((s,o)=>{
const sub = o.items.reduce((a,it)=>a+it.qty*it.price,0);
return s + fairSplit(sub).farmerReceives;
},0);
return `
<div class="wrap screen-head">
<h2>Good day, ${fp.name.split(' ')[0]} π</h2>
<p>${fp.village}, ${fp.district} Β· ${myListings.length} active listing${myListings.length===1?'':'s'}</p>
</div>
<div class="wrap">
<div class="grid-3" style="margin-bottom:26px;">
<div class="card stat-card"><div class="num">${myListings.length}</div><div class="lbl">Active Listings</div></div>
<div class="card stat-card"><div class="num">${myOrders.length}</div><div class="lbl">Total Orders</div></div>
<div class="card stat-card"><div class="num mono">${inr(earnings)}</div><div class="lbl">Earnings so far</div></div>
</div>
<div class="grid-2">
<div class="card action-card" onclick="navigate('farmerListForm')">
<div class="ic">π¦</div><h4>List New Produce</h4><p>Post a crop for sale with harvest details & fair price.</p>
</div>
<div class="card action-card" onclick="navigate('farmerListings')">
<div class="ic">ποΈ</div><h4>My Listings</h4><p>View and manage everything you currently have for sale.</p>
</div>
<div class="card action-card" onclick="navigate('farmerOrders')">
<div class="ic">π</div><h4>Incoming Orders</h4><p>${myOrders.length} order${myOrders.length===1?'':'s'} to pack & fulfil.</p>
</div>
<div class="card action-card" onclick="navigate('marketplace')">
<div class="ic">π</div><h4>Preview Marketplace</h4><p>See exactly what customers see when they find your farm.</p>
</div>
</div>
</div>
`;
}
const CROP_EMOJIS = [['Tomato','π
'],['Onion','π§
'],['Wheat','πΎ'],['Mango','π₯'],['Potato','π₯'],['Carrot','π₯'],['Rice','π'],['Chili','πΆοΈ'],['Banana','π'],['Spinach','π₯¬']];
let pickedEmoji = 'π
';
function renderFarmerListForm(){
pickedEmoji = 'π
';
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('farmerDashboard')">β Back to dashboard</button>
<h2>π¦ List Your Produce</h2>
<p>The more detail you add, the more trust customers place in your listing.</p>
</div>
<div class="wrap" style="padding-bottom:70px;">
<div class="card form-card">
<div class="field">
<label>Crop</label>
<div class="emoji-pick" id="emojiPick"></div>
<input type="text" id="pCrop" placeholder="e.g. Tomato" style="margin-top:10px;" value="Tomato">
</div>
<div class="row-2">
<div class="field"><label>Quantity</label><input type="number" id="pQty" value="180"></div>
<div class="field"><label>Unit</label>
<select id="pUnit"><option>kg</option><option>quintal</option><option>dozen</option><option>crate</option></select>
</div>
</div>
<div class="row-2">
<div class="field"><label>Price you want to receive (per unit)</label><input type="number" id="pPrice" value="34"></div>
<div class="field"><label>Harvest date</label><input type="date" id="pDate" value="2026-08-20"></div>
</div>
<div class="field">
<label>Farming practice</label>
<div class="tag-check" id="practiceTags"></div>
</div>
<div class="field"><label>Your farm's story (shown to customers)</label>
<textarea id="pStory" placeholder="e.g. Picked ripe at dawn, no pesticides used.">Grown with care on our family farm β picked fresh and shipped within a day of harvest.</textarea>
</div>
<div id="feePreview" style="margin-bottom:18px;"></div>
<button class="btn btn-leaf btn-block" onclick="submitListing()">Post Produce</button>
</div>
</div>
`;
}
function paintListFormExtras(){
const ep = document.getElementById('emojiPick');
if(ep){
ep.innerHTML = CROP_EMOJIS.map(([name,em])=>`<button type="button" class="${em===pickedEmoji?'sel':''}" onclick="pickEmoji('${em}','${name}')">${em}</button>`).join('');
}
const tags = document.getElementById('practiceTags');
if(tags){
const options = ['Organic','Natural Farming','No Pesticides','Traditional Seeds','Rain-fed'];
tags.innerHTML = options.map((o,i)=>`<label><input type="checkbox" class="practiceCk" value="${o}" ${i<2?'checked':''}><span>${o}</span></label>`).join('');
}
updateFeePreview();
}
function pickEmoji(em,name){
pickedEmoji = em;
document.getElementById('pCrop').value = name;
paintListFormExtras();
}
function updateFeePreview(){
const priceEl = document.getElementById('pPrice');
const qtyEl = document.getElementById('pQty');
const box = document.getElementById('feePreview');
if(!priceEl || !box) return;
const price = Number(priceEl.value)||0;
const qty = Number(qtyEl.value)||0;
const subtotal = price*qty;
const {platformFee, farmerReceives, mandiEstimate} = fairSplit(subtotal || 1);
const unit = document.getElementById('pUnit') ? document.getElementById('pUnit').value : 'kg';
box.innerHTML = `
<div class="ledger">
<h4>Estimated payout for this listing</h4>
<div class="ledger-row"><span>If sold in full (${qty} ${unit} Γ ${inr(price)})</span><span>${inr(subtotal)}</span></div>
<div class="ledger-row"><span>KisanSetu platform fee (8%)</span><span>β ${inr(platformFee)}</span></div>
<div class="ledger-row total"><span>You receive</span><span>${inr(farmerReceives)}</span></div>
<div class="split-bars">
<div>
<div class="split-label"><span>Typical mandi chain</span><span>~${inr(mandiEstimate)}</span></div>
<div class="split-track"><div class="split-fill sindoor" style="width:${subtotal?Math.round(mandiEstimate/subtotal*100):0}%"></div></div>
</div>
<div>
<div class="split-label"><span>On KisanSetu</span><span>${inr(farmerReceives)}</span></div>
<div class="split-track"><div class="split-fill leaf" style="width:${subtotal?Math.round(farmerReceives/subtotal*100):0}%"></div></div>
</div>
</div>
</div>`;
}
function submitListing(){
const crop = document.getElementById('pCrop').value.trim() || 'Produce';
const qty = Number(document.getElementById('pQty').value)||1;
const unit = document.getElementById('pUnit').value;
const price = Number(document.getElementById('pPrice').value)||1;
const date = document.getElementById('pDate').value || '2026-08-20';
const story = document.getElementById('pStory').value.trim() || 'Fresh from our farm.';
const practices = Array.from(document.querySelectorAll('.practiceCk:checked')).map(c=>c.value);
const id = 'p' + (state.products.length + 1) + Math.floor(Math.random()*99);
state.products.unshift({id, farmerId:'you', crop, emoji:pickedEmoji, quantity:qty, unit, price, harvestDate:date, practices, story});
toast(`${crop} listed! It's now live in the marketplace.`);
navigate('farmerListings');
}
function renderFarmerListings(){
const mine = state.products.filter(p=>p.farmerId==='you');
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('farmerDashboard')">β Back to dashboard</button>
<h2>ποΈ My Listings</h2>
<p>${mine.length} item${mine.length===1?'':'s'} currently visible to customers.</p>
</div>
<div class="wrap" style="padding-bottom:70px;">
${mine.length===0 ? `
<div class="card empty"><div class="ic">π¦</div><p>You haven't listed anything yet.</p>
<button class="btn btn-leaf" style="margin-top:14px;" onclick="navigate('farmerListForm')">List Your First Produce</button></div>
` : `<div class="grid-3">${mine.map(p=>productCard(p)).join('')}</div>`}
<div style="margin-top:24px;"><button class="btn btn-outline" onclick="navigate('farmerListForm')">+ List Another Item</button></div>
</div>`;
}
function renderFarmerOrders(){
const mine = state.orders.filter(o=>o.farmerId==='you').slice().reverse();
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('farmerDashboard')">β Back to dashboard</button>
<h2>π Incoming Orders</h2>
<p>Update status as you pack and dispatch β customers see this update live.</p>
</div>
<div class="wrap" style="padding-bottom:70px;">
${mine.length===0 ? `<div class="card empty"><div class="ic">π§Ί</div><p>No orders yet. Once a customer buys your produce, it'll show up here.</p></div>` :
mine.map(o=>farmerOrderTicket(o)).join('')}
</div>`;
}
function farmerOrderTicket(o){
const subtotal = o.items.reduce((a,it)=>a+it.qty*it.price,0);
const {farmerReceives} = fairSplit(subtotal);
const idx = STATUSES.indexOf(o.status);
const next = STATUSES[idx+1];
return `
<div class="order-ticket">
<div class="oh">
<div>
<div class="trace">TRACE ${o.traceId}</div>
<h4 style="margin-top:4px;">Order for ${o.customerName}</h4>
</div>
<span class="status-pill">${o.status}</span>
</div>
<div class="muted" style="font-size:13.5px;margin-bottom:10px;">${o.items.map(it=>`${productOf(it.productId)?productOf(it.productId).emoji:'π¦'} ${it.qty}${productOf(it.productId)?productOf(it.productId).unit:''} ${productOf(it.productId)?productOf(it.productId).crop:''}`).join(', ')}</div>
<div class="muted" style="font-size:13px;">Deliver to: ${o.address}</div>
<div class="muted" style="font-size:13px;">You receive: <strong class="mono">${inr(farmerReceives)}</strong></div>
${renderStepper(o.status)}
${next ? `<button class="btn btn-leaf btn-sm" style="margin-top:14px;" onclick="advanceOrder('${o.id}')">Mark as "${next}"</button>` : `<div style="margin-top:14px;color:var(--leaf-deep);font-weight:700;font-size:13.5px;">β
Delivered β cycle complete</div>`}
</div>`;
}
function advanceOrder(orderId){
const o = state.orders.find(x=>x.id===orderId);
if(!o) return;
const idx = STATUSES.indexOf(o.status);
if(idx < STATUSES.length-1){
o.status = STATUSES[idx+1];
toast(`Order marked "${o.status}"`);
}
render();
}
function renderCustomerOnboard(){
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('landing')">β Back</button>
<h2>π§Ί Welcome, Customer</h2>
<p>Just your name and delivery city β start browsing right away.</p>
</div>
<div class="wrap" style="padding-bottom:70px;">
<div class="card form-card">
<div class="field"><label>Your name</label><input type="text" id="cName" value="Priya Sharma"></div>
<div class="field"><label>Delivery city</label><input type="text" id="cCity" value="Indore"></div>
<button class="btn btn-dark btn-block" onclick="submitCustomerOnboard()">Browse the Marketplace</button>
</div>
</div>`;
}
function submitCustomerOnboard(){
const name = document.getElementById('cName').value.trim() || 'Priya Sharma';
const city = document.getElementById('cCity').value.trim() || 'Indore';
state.customerProfile = {name, city};
state.currentRole = 'customer';
toast(`Welcome, ${name.split(' ')[0]}!`);
navigate('marketplace');
}
let activeFilter = 'All';
let searchTerm = '';
function renderMarketplace(){
const crops = ['All', ...new Set(state.products.map(p=>p.crop))];
const filtered = state.products.filter(p=>{
const matchCrop = activeFilter==='All' || p.crop===activeFilter;
const matchSearch = !searchTerm || p.crop.toLowerCase().includes(searchTerm.toLowerCase()) || farmerOf(p.farmerId).village.toLowerCase().includes(searchTerm.toLowerCase());
return matchCrop && matchSearch;
});
return `
<div class="wrap screen-head">
<h2>π Fresh from the Farm</h2>
<p>Every listing here is traceable straight back to the farmer who grew it.</p>
</div>
<div class="wrap">
<div class="filter-row">
<div class="search-box"><input type="text" placeholder="Search crop or village..." value="${searchTerm}" oninput="setSearch(this.value)"></div>
${crops.map(c=>`<button class="chip-filter ${c===activeFilter?'active':''}" onclick="setFilter('${c}')">${c}</button>`).join('')}
</div>
${filtered.length===0 ? `<div class="card empty"><div class="ic">π±</div><p>No produce matches that search.</p></div>` :
`<div class="grid-3" style="padding-bottom:60px;">${filtered.map(p=>productCard(p)).join('')}</div>`}
</div>`;
}
function setFilter(c){ activeFilter=c; render(); }
function setSearch(v){ searchTerm=v; render(); }
function productCard(p){
const f = farmerOf(p.farmerId);
return `
<div class="card product-card" onclick="navigate('productDetail',{id:'${p.id}'})">
<div class="product-photo">${p.emoji}<span class="verified-badge">β Verified</span></div>
<div class="product-body">
<h4>${p.crop}</h4>
<div class="product-meta">π ${f.village}, ${f.district} Β· <span class="rating">β
${f.rating}</span></div>
<div class="practice-tags">${p.practices.slice(0,2).map(t=>`<span>${t}</span>`).join('')}</div>
<div class="price-row">
<div><span class="price">${inr(p.price)}</span> <span class="unit">/ ${p.unit}</span></div>
<div class="muted" style="font-size:12px;">${p.quantity}${p.unit} avail.</div>
</div>
</div>
</div>`;
}
function renderProductDetail(){
const p = productOf(state.params.id);
if(!p) return `<div class="wrap"><p>Product not found.</p></div>`;
const f = farmerOf(p.farmerId);
const subtotal = p.price;
const {platformFee, farmerReceives, mandiEstimate} = fairSplit(subtotal);
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('marketplace')">β Back to marketplace</button>
</div>
<div class="wrap" style="padding-bottom:70px;">
<div class="passport" style="margin-bottom:24px;">
<div class="passport-top">
<div class="passport-avatar">${f.avatar}</div>
<div>
<h3>${f.name}</h3>
<div class="vloc">π ${f.village}, ${f.district} Β· ${f.years} yrs farming Β· β
${f.rating} (${f.deals} deals)</div>
</div>
<div class="stamp">VERIFIED<br>FARMER<br>β</div>
</div>
<div class="passport-body">
<div class="story">"${f.bio}"</div>
<div class="pp-grid">
<div class="pp-item"><div class="k">Crop</div><div class="v">${p.emoji} ${p.crop}</div></div>
<div class="pp-item"><div class="k">Harvest date</div><div class="v">${p.harvestDate}</div></div>
<div class="pp-item"><div class="k">Available</div><div class="v">${p.quantity} ${p.unit}</div></div>
<div class="pp-item"><div class="k">Practice</div><div class="v">${p.practices.join(', ')||'β'}</div></div>
<div class="pp-item"><div class="k">Farm size</div><div class="v">3.5 acres</div></div>
<div class="pp-item"><div class="k">Trace status</div><div class="v">Full farm-to-door</div></div>
</div>
<div class="story" style="border-color:var(--leaf);">${p.story}</div>
</div>
</div>
<div class="grid-2">
<div class="ledger">
<h4>Fair price breakdown (per ${p.unit})</h4>
<div class="ledger-row"><span>You pay</span><span>${inr(subtotal)}</span></div>
<div class="ledger-row"><span>Platform fee (8%)</span><span>β ${inr(platformFee)}</span></div>
<div class="ledger-row total"><span>Farmer receives</span><span>${inr(farmerReceives)}</span></div>
<div class="split-bars">
<div><div class="split-label"><span>Typical mandi chain gives farmer</span><span>~${Math.round(mandiEstimate/subtotal*100)}%</span></div>
<div class="split-track"><div class="split-fill sindoor" style="width:${Math.round(mandiEstimate/subtotal*100)}%"></div></div></div>
<div><div class="split-label"><span>KisanSetu gives farmer</span><span>${Math.round(farmerReceives/subtotal*100)}%</span></div>
<div class="split-track"><div class="split-fill leaf" style="width:${Math.round(farmerReceives/subtotal*100)}%"></div></div></div>
</div>
</div>
<div class="card" style="padding:22px;display:flex;flex-direction:column;gap:14px;">
<h4>Add to your basket</h4>
<div class="field" style="margin-bottom:0;">
<label>Quantity (${p.unit})</label>
<input type="number" id="buyQty" value="2" min="1" max="${p.quantity}">
</div>
<div class="muted" style="font-size:13px;">Free delivery on orders above βΉ300 Β· flat βΉ30 fee otherwise.</div>
<button class="btn btn-primary btn-block" onclick="addToCartFromDetail('${p.id}')">Add to Cart</button>
<button class="btn btn-outline btn-block" onclick="navigate('marketplace')">Keep Browsing</button>
</div>
</div>
</div>`;
}
function addToCartFromDetail(pid){
if(!state.customerProfile){ navigate('customerOnboard'); return; }
const qty = Number(document.getElementById('buyQty').value)||1;
addToCart(pid, qty);
}
function addToCart(pid, qty=1){
const existing = state.cart.find(c=>c.productId===pid);
if(existing) existing.qty += qty;
else state.cart.push({productId:pid, qty});
toast('Added to cart π');
renderHeader();
}
/* ============================= CART ============================= */
function renderCart(){
if(state.cart.length===0){
return `<div class="wrap screen-head"><h2>π Your Cart</h2></div>
<div class="wrap" style="padding-bottom:70px;"><div class="card empty"><div class="ic">π§Ί</div><p>Your cart is empty.</p>
<button class="btn btn-primary" style="margin-top:14px;" onclick="navigate('marketplace')">Browse Marketplace</button></div></div>`;
}
const subtotal = state.cart.reduce((s,c)=>s + c.qty*productOf(c.productId).price, 0);
const delivery = subtotal >= 300 ? 0 : 30;
const total = subtotal + delivery;
return `
<div class="wrap screen-head"><h2>π Your Cart</h2><p>Review before checkout β prices are exactly what the farmer set.</p></div>
<div class="wrap" style="padding-bottom:70px;">
<div class="card" style="padding:8px 24px;margin-bottom:20px;">
${state.cart.map(c=>{
const p = productOf(c.productId); const f = farmerOf(p.farmerId);
return `<div class="cart-row">
<div class="cart-emoji">${p.emoji}</div>
<div class="cart-info"><h5>${p.crop}</h5><div class="from">from ${f.name}, ${f.village} Β· ${inr(p.price)}/${p.unit}</div></div>
<div class="qty-ctrl">
<button onclick="changeQty('${p.id}',-1)">β</button><span>${c.qty}</span><button onclick="changeQty('${p.id}',1)">+</button>
</div>
<div class="cart-price">${inr(p.price*c.qty)}</div>
<button class="remove-x" onclick="removeFromCart('${p.id}')">β</button>
</div>`;
}).join('')}
</div>
<div class="ledger" style="max-width:380px;margin-left:auto;">
<div class="ledger-row"><span>Subtotal</span><span>${inr(subtotal)}</span></div>
<div class="ledger-row"><span>Delivery</span><span>${delivery===0?'Free':inr(delivery)}</span></div>
<div class="ledger-row total"><span>Total</span><span>${inr(total)}</span></div>
</div>
<div style="max-width:380px;margin-left:auto;margin-top:16px;display:flex;flex-direction:column;gap:10px;">
<button class="btn btn-primary btn-block" onclick="navigate('checkout')">Proceed to Checkout</button>
<button class="btn btn-outline btn-block" onclick="navigate('marketplace')">+ Add More Produce</button>
</div>
</div>`;
}
function changeQty(pid, delta){
const item = state.cart.find(c=>c.productId===pid);
if(!item) return;
item.qty += delta;
if(item.qty<=0) state.cart = state.cart.filter(c=>c.productId!==pid);
render();
}
function removeFromCart(pid){
state.cart = state.cart.filter(c=>c.productId!==pid);
toast('Removed from cart');
render();
}
function renderCheckout(){
if(state.cart.length===0){ navigate('cart'); return ''; }
const subtotal = state.cart.reduce((s,c)=>s + c.qty*productOf(c.productId).price, 0);
const delivery = subtotal >= 300 ? 0 : 30;
return `
<div class="wrap screen-head">
<button class="back-link" onclick="navigate('cart')">β Back to cart</button>
<h2>π§Ύ Checkout</h2>
</div>
<div class="wrap" style="padding-bottom:70px;">
<div class="card form-card">
<div class="field"><label>Delivery address</label>
<textarea id="addr">${state.customerProfile.name}, ${state.customerProfile.city}</textarea>
</div>
<div class="ledger" style="margin-bottom:20px;">
<div class="ledger-row"><span>Subtotal</span><span>${inr(subtotal)}</span></div>
<div class="ledger-row"><span>Delivery</span><span>${delivery===0?'Free':inr(delivery)}</span></div>
<div class="ledger-row total"><span>Total (escrow-secured)</span><span>${inr(subtotal+delivery)}</span></div>
</div>
<div class="field hint" style="margin-bottom:20px;">π Payment is held securely and released to the farmer only once delivery is confirmed.</div>
<button class="btn btn-primary btn-block" onclick="placeOrder()">Place Order & Pay ${inr(subtotal+delivery)}</button>
</div>
</div>`;
}
function placeOrder(){
const address = document.getElementById('addr').value.trim() || state.customerProfile.city;
const byFarmer = {};
state.cart.forEach(c=>{
const p = productOf(c.productId);
if(!byFarmer[p.farmerId]) byFarmer[p.farmerId] = [];
byFarmer[p.farmerId].push({productId:c.productId, qty:c.qty, price:p.price});
});
Object.keys(byFarmer).forEach(farmerId=>{
state.orders.push({
id:'ord' + (state.orders.length+1) + Math.floor(Math.random()*999),
farmerId, customerName: state.customerProfile.name,
items: byFarmer[farmerId], status:'Confirmed', address,
traceId: genTrace(), placedAt: new Date().toISOString()
});
});
state.cart = [];
toast('Order placed! Payment secured in escrow. π');
navigate('orderTracking');
}
function renderStepper(status){
const idx = STATUSES.indexOf(status);
return `<div class="stepper">
${STATUSES.map((s,i)=>`<div class="step ${i<idx?'done':''} ${i===idx?'current':''}">
<div class="sdot">${i<idx?'β':i+1}</div><div class="slabel">${s}</div>
</div>`).join('')}
</div>`;
}
function renderOrderTracking(){
const mine = state.orders.filter(o=>o.customerName===state.customerProfile.name).slice().reverse();
return `
<div class="wrap screen-head">
<h2>π¦ Your Orders</h2>
<p>Live status, straight from the farmer's dispatch.</p>
</div>
<div class="wrap" style="padding-bottom:70px;">
${mine.length===0 ? `<div class="card empty"><div class="ic">π</div><p>No orders yet.</p>
<button class="btn btn-primary" style="margin-top:14px;" onclick="navigate('marketplace')">Browse Marketplace</button></div>` :
mine.map(o=>{
const f = farmerOf(o.farmerId);
const subtotal = o.items.reduce((a,it)=>a+it.qty*it.price,0);
return `<div class="order-ticket">
<div class="oh">
<div><div class="trace">TRACE ${o.traceId}</div>
<h4 style="margin-top:4px;">${o.items.map(it=>`${productOf(it.productId).emoji} ${it.qty}${productOf(it.productId).unit} ${productOf(it.productId).crop}`).join(', ')}</h4>
</div>
<span class="status-pill">${o.status}</span>
</div>
<div class="muted" style="font-size:13.5px;">From ${f.avatar} <strong>${f.name}</strong>, ${f.village} Β· <button class="link-btn" onclick="navigate('productDetail',{id:'${o.items[0].productId}'})">View farm passport</button></div>
<div class="muted" style="font-size:13px;margin-top:2px;">Delivering to: ${o.address}</div>
<div class="muted" style="font-size:13px;">Total paid: <strong class="mono">${inr(subtotal)}</strong> (escrow-secured)</div>
${renderStepper(o.status)}
</div>`;
}).join('')}
<button class="btn btn-outline" onclick="navigate('marketplace')">β Continue Shopping</button>
</div>`;
}
function render(){
renderHeader();
const app = document.getElementById('app');
switch(state.screen){
case 'landing': app.innerHTML = renderLanding(); break;
case 'farmerOnboard': app.innerHTML = renderFarmerOnboard(); break;
case 'farmerDashboard': app.innerHTML = renderFarmerDashboard(); break;
case 'farmerListForm': app.innerHTML = renderFarmerListForm(); paintListFormExtras(); attachFeeListeners(); break;
case 'farmerListings': app.innerHTML = renderFarmerListings(); break;
case 'farmerOrders': app.innerHTML = renderFarmerOrders(); break;
case 'customerOnboard': app.innerHTML = renderCustomerOnboard(); break;
case 'marketplace': app.innerHTML = renderMarketplace(); break;
case 'productDetail': app.innerHTML = renderProductDetail(); break;
case 'cart': app.innerHTML = renderCart(); break;
case 'checkout': app.innerHTML = renderCheckout(); break;
case 'orderTracking': app.innerHTML = renderOrderTracking(); break;
default: app.innerHTML = renderLanding();
}
}
function attachFeeListeners(){
['pPrice','pQty','pUnit'].forEach(id=>{
const el = document.getElementById(id);
if(el){ el.addEventListener('input', updateFeePreview); el.addEventListener('change', updateFeePreview); }
});
}
render();