/* Me2You - Order Tracking, Toast Notifications, Mobile Bottom Nav */
/* global React, Icon, StatusTag, OrderStepper, Price, panelStyle, btnPrimary, btnGhost, btnSmall, btnDanger */

const { useState, useEffect, useRef, createContext, useContext } = React;

/* --- Toast System --- */
const ToastContext = createContext(null);

function ToastProvider({ children }) {
 const [toasts, setToasts] = useState([]);
 const addToast = (msg, type='success') => {
 const id = Date.now();
 setToasts(prev => [...prev, { id, msg, type, out: false }]);
 setTimeout(() => setToasts(prev => prev.map(t => t.id === id ? {...t, out: true} : t)), 2500);
 setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
 };
 return (
 <ToastContext.Provider value={addToast}>
 {children}
 <div style={{position:'fixed',top:88,right:24,zIndex:100,display:'flex',flexDirection:'column',gap:8}}>
 {toasts.map(t => (
 <div key={t.id} className={`toast ${t.out ? 'out' : ''}`}>
 <div style={{width:24,height:24,borderRadius:999,flexShrink:0,
 background: t.type === 'success' ? 'var(--success-100)' : t.type === 'error' ? 'var(--danger-100)' : 'var(--info-100)',
 color: t.type === 'success' ? 'var(--success)' : t.type === 'error' ? 'var(--danger)' : 'var(--info)',
 display:'flex',alignItems:'center',justifyContent:'center'}}>
 <Icon name={t.type === 'success' ? 'check' : t.type === 'error' ? 'x' : 'truck'} size={14} stroke={2.5}/>
 </div>
 {t.msg}
 </div>
 ))}
 </div>
 </ToastContext.Provider>
 );
}

function useToast() { return useContext(ToastContext); }

/* --- Order Tracking Page --- */
function OrderTracking({ order, onBack, onDispute }) {
 const o = order || {
 id: 'M2Y-2026-00248',
 status: 'dispatched',
 product: { title: 'Hisense 32" Smart TV', emoji: '', bg: 'linear-gradient(135deg,#FFE7C8,#FFF6E9)', price: 1850 },
 seller: 'Sipho M.',
 buyer: 'Nomsa M.',
 total: 1910,
 delivery: 60,
 method: 'Courier to door',
 address: '42 Vilakazi St, Orlando West, Soweto, 1804',
 placed: '28 Apr 2026, 10:23',
 paid: '28 Apr 2026, 10:24',
 dispatched: '29 Apr 2026, 14:15',
 eta: '1 May 2026',
 driver: 'Bongani K.',
 driverPhone: '072 345 6789',
 trackingRef: 'DRV-0041',
 };

 const [liveStep, setLiveStep] = useState(2); // 0-4

 return (
 <div style={{maxWidth:720,margin:'0 auto'}}>
 <button onClick={onBack} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Back to orders
 </button>
 
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'start',marginBottom:20}}>
 <div>
 <h1 style={{margin:'0 0 4px',fontSize:28}}>Track your order</h1>
 <div style={{fontFamily:'var(--font-mono)',fontSize:13,color:'var(--ink-500)'}}>{o.id}</div>
 </div>
 <StatusTag status={o.status}/>
 </div>

 {/* Status stepper */}
 <div style={{...panelStyle,padding:24}}>
 <OrderStepper current={o.status.charAt(0).toUpperCase() + o.status.slice(1)}/>
 </div>

 {/* Live delivery card */}
 {(o.status === 'dispatched' || o.status === 'paid') && (
 <div style={{...panelStyle,background:'var(--brand-orange-50)',borderColor:'var(--brand-orange)',padding:20}}>
 <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:12}}>
 <div style={{width:44,height:44,borderRadius:12,background:'var(--brand-orange)',
 display:'flex',alignItems:'center',justifyContent:'center',color:'white'}}>
 <Icon name="truck" size={22}/>
 </div>
 <div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16}}>
 {o.status === 'dispatched' ? 'On the way!' : 'Awaiting dispatch'}
 </div>
 <div style={{fontSize:13,color:'var(--ink-700)'}}>
 {o.status === 'dispatched' ? `Estimated arrival: ${o.eta}` : 'Seller has 3 days to dispatch'}
 </div>
 </div>
 </div>

 {o.status === 'dispatched' && (
 <>
 <div style={{height:240,borderRadius:'var(--radius-md)',marginBottom:12,overflow:'hidden'}}>
 <DriverLiveMap pickup={[-26.2041,28.0473]} dropoff={[-26.2678,27.8585]} driver={o.driver} height={240}/>
 </div>

 <div style={{display:'flex',gap:12}}>
 <div style={{flex:1,...panelStyle,margin:0,padding:12,background:'var(--paper)'}}>
 <div style={{fontSize:11,color:'var(--ink-500)',fontWeight:600,textTransform:'uppercase',letterSpacing:'.06em'}}>Driver</div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:14,marginTop:2}}>{o.driver}</div>
 <div style={{fontSize:12,color:'var(--ink-500)',marginTop:2}}> 4.8 - Scooter</div>
 </div>
 <div style={{flex:1,...panelStyle,margin:0,padding:12,background:'var(--paper)'}}>
 <div style={{fontSize:11,color:'var(--ink-500)',fontWeight:600,textTransform:'uppercase',letterSpacing:'.06em'}}>Tracking</div>
 <div style={{fontFamily:'var(--font-mono)',fontWeight:600,fontSize:14,marginTop:2}}>{o.trackingRef}</div>
 <div style={{fontSize:12,color:'var(--ink-500)',marginTop:2}}>ETA ~25 min</div>
 </div>
 </div>

 <div style={{display:'flex',gap:8,marginTop:12}}>
 <button style={{...btnGhost,flex:1,justifyContent:'center',padding:'10px',fontSize:13,background:'var(--paper)'}}>
 <Icon name="phone" size={16}/> Call driver
 </button>
 <button style={{...btnGhost,flex:1,justifyContent:'center',padding:'10px',fontSize:13,background:'var(--paper)'}}>
 <Icon name="message-circle" size={16}/> Message
 </button>
 </div>
 </>
 )}
 </div>
 )}

 {/* Order details */}
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 12px'}}>Order details</h3>
 <div style={{display:'flex',gap:16,alignItems:'center',paddingBottom:12,borderBottom:'1px solid var(--ink-100)',marginBottom:12}}>
 <div style={{width:64,height:64,borderRadius:12,backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center',flexShrink:0}}/>
 <div style={{flex:1}}>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:15}}>{o.product.title}</div>
 <div style={{fontSize:13,color:'var(--ink-500)',marginTop:2}}>Sold by {o.seller}</div>
 </div>
 <Price amount={o.product.price}/>
 </div>
 <div style={{display:'flex',flexDirection:'column',gap:8}}>
 <DetailRow label="Delivery" value={`R ${o.delivery}`}/>
 <DetailRow label="Total" value={`R ${o.total.toLocaleString('en-ZA')}`} bold/>
 </div>
 </div>

 {/* Delivery info */}
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 12px'}}>Delivery information</h3>
 <div style={{display:'flex',flexDirection:'column',gap:8}}>
 <DetailRow label="Method" value={o.method} icon="truck"/>
 <DetailRow label="Address" value={o.address} icon="map-pin"/>
 {o.driver && <DetailRow label="Driver" value={`${o.driver} - ${o.driverPhone}`} icon="user-round"/>}
 </div>
 </div>

 {/* Timeline */}
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 12px'}}>Timeline</h3>
 <div style={{display:'flex',flexDirection:'column',gap:0}}>
 {[
 { time: o.placed, label: 'Order placed', icon: 'receipt', done: true },
 { time: o.paid, label: 'Payment confirmed', icon: 'shield-check', done: true },
 { time: o.dispatched, label: 'Dispatched', icon: 'truck', done: o.status !== 'paid' },
 { time: o.status === 'received' || o.status === 'completed' ? '2 May 2026, 09:30' : null, label: 'Received', icon: 'check-circle', done: o.status === 'received' || o.status === 'completed' },
 { time: o.status === 'completed' ? '2 May 2026, 09:30' : null, label: 'Completed', icon: 'star', done: o.status === 'completed' },
 ].map((step, i) => (
 <div key={i} style={{display:'flex',gap:12,position:'relative'}}>
 <div style={{display:'flex',flexDirection:'column',alignItems:'center',width:24}}>
 <div style={{width:24,height:24,borderRadius:999,flexShrink:0,
 background: step.done ? 'var(--success)' : 'var(--ink-100)',
 color: step.done ? 'white' : 'var(--ink-400)',
 display:'flex',alignItems:'center',justifyContent:'center'}}>
 <Icon name={step.icon} size={12} stroke={2.5}/>
 </div>
 {i < 4 && <div style={{width:2,height:32,background: step.done ? 'var(--success)' : 'var(--ink-200)'}}/>}
 </div>
 <div style={{paddingBottom:i < 4 ? 16 : 0}}>
 <div style={{fontFamily:'var(--font-body)',fontWeight:600,fontSize:14,
 color: step.done ? 'var(--ink-900)' : 'var(--ink-400)'}}>{step.label}</div>
 {step.time && <div style={{fontSize:12,color:'var(--ink-500)',marginTop:2}}>{step.time}</div>}
 </div>
 </div>
 ))}
 </div>
 </div>

 {/* Actions */}
 <div style={{display:'flex',gap:8}}>
 {o.status === 'dispatched' && (
 <button onClick={() => {}} style={{...btnPrimary,flex:1,justifyContent:'center'}}>
 <Icon name="check" size={18}/> Confirm received
 </button>
 )}
 {(o.status === 'paid' || o.status === 'dispatched' || o.status === 'received') && (
 <button onClick={onDispute} style={{...btnGhost,flex: o.status === 'dispatched' ? 0 : 1,justifyContent:'center',color:'var(--danger)',borderColor:'var(--danger)'}}>
 <Icon name="triangle-alert" size={18}/> Open dispute
 </button>
 )}
 </div>
 </div>
 );
}

function DetailRow({ label, value, bold, icon }) {
 return (
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',fontSize:14}}>
 <span style={{color:'var(--ink-500)',display:'flex',alignItems:'center',gap:6}}>
 {icon && <Icon name={icon} size={14}/>}
 {label}
 </span>
 <span style={{fontWeight: bold ? 700 : 400,fontFamily: bold ? 'var(--font-display)' : 'var(--font-body)'}}>{value}</span>
 </div>
 );
}

/* --- Mobile Bottom Nav --- */
function MobileBottomNav({ active, onNav, cartCount }) {
 const items = [
 { key: 'home', label: 'Home', icon: 'home' },
 { key: 'feed', label: 'Feed', icon: 'play' },
 { key: 'sell', label: 'Sell', icon: 'plus' },
 { key: 'community', label: 'Community', icon: 'users' },
 { key: 'cart', label: 'Cart', icon: 'shopping-bag', badge: cartCount },
 ];
 return (
 <nav className="mobile-bnav">
 {items.map(item => (
 <button key={item.key} onClick={() => onNav(item.key)}
 style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:2,
 background:'none',border:'none',cursor:'pointer',position:'relative',
 color: active === item.key ? 'var(--brand-orange)' : 'var(--ink-400)',
 fontFamily:'var(--font-body)',fontSize:10,fontWeight:600,transition:'color .15s'}}>
 <div style={{position:'relative'}}>
 <Icon name={item.icon} size={22} stroke={active === item.key ? 2 : 1.5}/>
 {item.badge > 0 && (
 <span style={{position:'absolute',top:-4,right:-8,background:'var(--brand-orange)',color:'white',
 fontSize:9,fontWeight:800,borderRadius:999,width:16,height:16,
 display:'flex',alignItems:'center',justifyContent:'center'}}>{item.badge}</span>
 )}
 </div>
 {item.label}
 </button>
 ))}
 </nav>
 );
}

Object.assign(window, { ToastProvider, ToastContext, useToast, OrderTracking, MobileBottomNav });
