/* Me2You - Main App: routing, header, footer, state management */
/* global React, ReactDOM, Icon, PageTransition, SearchBar, Price,
 MarketplaceHero, CategoryRail, ProductGrid, ProductDetail, CartView, CheckoutView, OrderSuccess, OrdersList, DisputeForm,
 SwapOfferFlow, OTPCollectionConfirm,
 SellerDashboard, CreateListing, AdminPanel, DriverApp,
 AuthLogin, AuthRegister, AuthForgot, SellerOTPVerify, ProfilePage, PrivacyPolicy, AdminPayoutRun,
 ToastProvider, useToast, OrderTracking, MobileBottomNav,
 NotificationBell, SearchSuggestions, BrowseFilters,
 WishlistPage, SellerStorefront, ChatList, ChatThread, FeedScreen, CommunityScreen,
 PayFastRedirect, OnboardingTour, EarningsChart, AdminAuditLog, PWAInstallBanner,
 PRODUCTS, CATEGORIES, SAMPLE_ORDERS,
 btnPrimary, btnGhost, panelStyle,
 TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakToggle, TweakSlider, TweakSelect, TweakColor, TweakButton */

const { useState, useEffect, useMemo, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
 "surface": "marketplace",
 "theme": "light",
 "animationLevel": "lively",
 "trustBadges": true,
 "heroVariant": "seller",
 "cardDensity": "comfortable",
 "navStyle": "top"
}/*EDITMODE-END*/;

/* --- App Header --- */
function AppHeader({ surface, onSurface, cartCount, onNav, search, onSearch, onSelectProduct }) {
 return (
 <header style={{
 position:'sticky',top:0,zIndex:20,
 background:'rgba(255,255,255,0.92)',backdropFilter:'blur(12px)',
 borderBottom:'1px solid var(--ink-200)',height:'var(--header-h)',
 display:'flex',alignItems:'center'
 }}>
 <div style={{maxWidth:'var(--content-max)',margin:'0 auto',padding:'0 24px',
 display:'flex',alignItems:'center',gap:16,width:'100%'}}>
 <a href="#" onClick={e => { e.preventDefault(); onNav('home'); }} style={{display:'inline-flex',alignItems:'center',gap:8,borderBottom:0}}>
 <img src="assets/logo-peace-orange.png" alt="" style={{height:32,width:'auto'}}/>
 <span style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:20,color:'var(--brand-orange)',letterSpacing:'-0.01em'}}>Me2You</span>
 </a>

 {/* Surface tabs */}
 <div className="surface-tabs" style={{display:'flex',gap:2,marginLeft:8}}>
 {[
 {key:'marketplace',label:'Items'},
 {key:'property',label:'Property'},
 {key:'vehicles',label:'Vehicles'},
 {key:'seller',label:'Seller'},
 {key:'admin',label:'Admin'},
 {key:'driver',label:'Driver'},
 ].map(s => (
 <button key={s.key} onClick={() => onSurface(s.key)} style={{
 padding:'6px 14px',borderRadius:'var(--radius-pill)',border:'none',cursor:'pointer',
 fontFamily:'var(--font-body)',fontWeight:600,fontSize:13,
 background: surface===s.key ? 'var(--ink-900)' : 'transparent',
 color: surface===s.key ? 'white' : 'var(--ink-500)',
 transition:'all .15s'
 }}>{s.label}</button>
 ))}
 </div>

 {surface === 'marketplace' && (
 <div style={{flex:1,maxWidth:400,marginLeft:8}}>
 <SearchSuggestions value={search} onChange={onSearch} onSelect={p => { if (onSelectProduct) onSelectProduct(p); }}/>
 </div>
 )}

 <nav style={{display:'flex',alignItems:'center',gap:4,marginLeft:'auto'}}>
 <button onClick={() => onNav('feed')} style={headerNavBtn}>
 <Icon name="play" size={18}/><span className="hide-mobile">Feed</span>
 </button>
 <button onClick={() => onNav('community')} style={headerNavBtn}>
 <Icon name="users" size={18}/><span className="hide-mobile">Community</span>
 </button>
 <NotificationBell/>
 <button onClick={() => onNav('saved')} style={headerNavBtn}>
 <Icon name="heart" size={18}/><span className="hide-mobile">Saved</span>
 </button>
 <button onClick={() => onNav('messages')} style={headerNavBtn}>
 <Icon name="message-circle" size={18}/><span className="hide-mobile">Messages</span>
 </button>
 <button onClick={() => onNav('orders')} style={headerNavBtn}>
 <Icon name="receipt" size={18}/><span className="hide-mobile">Orders</span>
 </button>
 <button onClick={() => onNav('cart')} style={{...headerNavBtn,position:'relative'}}>
 <Icon name="shopping-bag" size={18}/><span className="hide-mobile">Cart</span>
 {cartCount > 0 && (
 <span style={{position:'absolute',top:2,right:2,background:'var(--brand-orange)',
 color:'white',fontSize:10,fontWeight:800,borderRadius:999,
 width:18,height:18,display:'flex',alignItems:'center',justifyContent:'center'}}>{cartCount}</span>
 )}
 </button>
 <button onClick={() => onNav('login')} style={headerNavBtn}>
 <Icon name="user-round" size={18}/><span className="hide-mobile">Sign in</span>
 </button>
 <button onClick={() => onSurface('seller')} style={{
 ...btnPrimary,padding:'10px 16px',fontSize:13,boxShadow:'var(--shadow-pop)'
 }}>Sell</button>
 </nav>
 </div>
 </header>
 );
}

const headerNavBtn = {
 display:'inline-flex',alignItems:'center',gap:8,
 padding:'10px 14px',borderRadius:'var(--radius-md)',
 background:'transparent',border:'none',cursor:'pointer',
 fontFamily:'var(--font-body)',fontWeight:600,fontSize:14,color:'var(--ink-700)',
};

/* --- App Footer --- */
function AppFooter() {
 return (
 <footer style={{borderTop:'1px solid var(--ink-200)',background:'var(--paper)',marginTop:64,padding:'32px 24px 24px'}}>
 <div style={{maxWidth:'var(--content-max)',margin:'0 auto',
 display:'grid',gridTemplateColumns:'2fr 1fr 1fr 1fr',gap:32}}>
 <div>
 <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:12}}>
 <img src="assets/logo-peace-orange.png" alt="" style={{height:32,width:'auto'}}/>
 <span style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:18,color:'var(--brand-orange)'}}>Me2You</span>
 </div>
 <p style={{fontFamily:'var(--font-body)',fontSize:13,color:'var(--ink-500)',maxWidth:320,margin:0,lineHeight:1.5}}>
 A C2C marketplace built for South Africa's informal economy. Locally hosted, POPIA-compliant, and designed to work on any phone.
 </p>
 </div>
 {[
 {h:'Buy', items:['Browse listings','Categories','How it works']},
 {h:'Sell', items:['Start selling','Seller fees','Shareable links']},
 {h:'Trust', items:['Privacy Policy','POPIA','Report a listing']},
 ].map(col => (
 <div key={col.h}>
 <h4 style={{fontFamily:'var(--font-mono)',fontSize:11,color:'var(--ink-500)',textTransform:'uppercase',
 letterSpacing:'.08em',fontWeight:600,margin:'0 0 12px'}}>{col.h}</h4>
 <ul style={{listStyle:'none',padding:0,margin:0,display:'flex',flexDirection:'column',gap:8}}>
 {col.items.map(i => (
 <li key={i}><a href="#" style={{fontFamily:'var(--font-body)',fontSize:13,color:'var(--ink-700)',borderBottom:0}}>{i}</a></li>
 ))}
 </ul>
 </div>
 ))}
 </div>
 <div style={{maxWidth:'var(--content-max)',margin:'24px auto 0',paddingTop:16,
 borderTop:'1px solid var(--ink-100)',display:'flex',justifyContent:'space-between',
 fontFamily:'var(--font-body)',fontSize:12,color:'var(--ink-500)'}}>
 <span>(c) 2026 Me2You - Made in South Africa</span>
 <span>Payments by PayFast - Pickup partners across SA</span>
 </div>
 </footer>
 );
}

/* --- Main App --- */
function App() {
 const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
 const [surface, setSurface] = useState(tweaks.surface);
 const [route, setRoute] = useState('home');
 const [cart, setCart] = useState([]);
 const [search, setSearch] = useState('');
 const [activeCat, setActiveCat] = useState('all');
 const [selected, setSelected] = useState(null);
 const [saved, setSaved] = useState([]);
 const [watched, setWatched] = useState([]);
 const [deliveryMethod, setDeliveryMethod] = useState('pickup');
 const [chatThread, setChatThread] = useState(null);
 const [showOnboarding, setShowOnboarding] = useState(true);
 const [showPWA, setShowPWA] = useState(false);
 const [browseView, setBrowseView] = useState('grid');
 const toast = useToast();

 useEffect(() => {
 const t = setTimeout(() => setShowPWA(true), 8000);
 return () => clearTimeout(t);
 }, []);

 const toggleSave = useCallback((id) => {
 setSaved(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
 if (toast) toast(saved.includes(id) ? 'Removed from saved' : 'Saved for later');
 }, [toast, saved]);

 const toggleWatch = useCallback((id) => {
 setWatched(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
 if (toast) toast(watched.includes(id) ? 'Stopped watching' : 'Watching for price drops');
 }, [toast, watched]);

 const cartCount = cart.reduce((n,i) => n + i.qty, 0);

 const addToCart = useCallback((p) => {
 setCart(prev => {
 const ex = prev.find(i => i.product.id === p.id);
 if (ex) return prev.map(i => i.product.id === p.id ? {...i, qty:i.qty+1} : i);
 return [...prev, {product:p, qty:1}];
 });
 if (toast) toast(`${p.title} added to cart`);
 setRoute('cart');
 }, [toast]);

 const updateQty = useCallback((id, delta) => {
 setCart(prev => prev.map(i => i.product.id === id ? {...i, qty: Math.max(1, i.qty + delta)} : i));
 }, []);

 const removeFromCart = useCallback((id) => {
 setCart(prev => prev.filter(i => i.product.id !== id));
 }, []);

 const filteredProducts = useMemo(() => {
 let list = PRODUCTS;
 if (activeCat !== 'all') list = list.filter(p => p.cat === activeCat);
 if (search) list = list.filter(p => p.title.toLowerCase().includes(search.toLowerCase()) || p.location.toLowerCase().includes(search.toLowerCase()));
 return list;
 }, [activeCat, search]);

 const handleSurface = (s) => {
 setSurface(s);
 setRoute('home');
 setTweak('surface', s);
 };

 const isDark = tweaks.theme === 'dark';

 return (
 <div style={{
 background: isDark ? '#1a1612' : 'var(--ink-50)',
 minHeight:'100vh',
 color: isDark ? '#e8e0d6' : 'var(--ink-900)',
 transition:'background .3s, color .3s',
 '--paper': isDark ? '#252019' : '#FFFFFF',
 '--ink-50': isDark ? '#1a1612' : '#FAF6EF',
 '--ink-100': isDark ? '#2a2420' : '#F4EEE5',
 '--ink-200': isDark ? '#3a332e' : '#E7DFD5',
 }}>
 <AppHeader surface={surface} onSurface={handleSurface} cartCount={cartCount}
 onNav={r => { setSurface('marketplace'); setRoute(r); }}
 search={search} onSearch={setSearch}
 onSelectProduct={p => { setSurface('marketplace'); setSelected(p); setRoute('product'); }}/>

 {surface === 'admin' ? (
 <AdminPanel/>
 ) : surface === 'driver' ? (
 <DriverApp/>
 ) : surface === 'property' ? (
 <main style={{maxWidth:'var(--content-max)',margin:'0 auto',padding:'32px 24px'}}>
 <PageTransition routeKey={surface + route + (selected?.id || '')}>
 {route === 'property-detail' && selected ? (
 <PropertyDetail property={selected} onBack={() => { setSelected(null); setRoute('home'); }}
 onMessage={() => { setSurface('marketplace'); setRoute('messages'); }}/>
 ) : (
 <PropertyBrowse onSelect={p => { setSelected(p); setRoute('property-detail'); }}/>
 )}
 </PageTransition>
 </main>
 ) : surface === 'vehicles' ? (
 <main style={{maxWidth:'var(--content-max)',margin:'0 auto',padding:'32px 24px'}}>
 <PageTransition routeKey={surface + route + (selected?.id || '')}>
 {route === 'vehicle-detail' && selected ? (
 <VehicleDetail vehicle={selected} onBack={() => { setSelected(null); setRoute('home'); }}
 onMessage={() => { setSurface('marketplace'); setRoute('messages'); }}/>
 ) : (
 <VehicleBrowse onSelect={v => { setSelected(v); setRoute('vehicle-detail'); }}/>
 )}
 </PageTransition>
 </main>
 ) : (
 <main style={{maxWidth:'var(--content-max)',margin:'0 auto',padding:'32px 24px'}}>
 <PageTransition routeKey={surface + route}>
 {surface === 'marketplace' && route === 'home' && (
 <>
 <MarketplaceHero onBrowse={() => setRoute('home')} onSell={() => handleSurface('seller')}/>
 {tweaks.trustBadges && (
 <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,margin:'24px 0'}}>
 {[
 {icon:'shield-check', title:'Escrow protected', desc:'Payment held until delivery confirmed'},
 {icon:'truck', title:'Three delivery flows', desc:'Door-to-door, pickup locker, or self-collect OTP'},
 {icon:'star', title:'Built for trust', desc:'Ratings, disputes, POPIA-compliant'},
 ].map(t => (
 <div key={t.title} style={{...panelStyle,padding:16,marginBottom:0,display:'flex',gap:12,alignItems:'start'}}>
 <div style={{width:40,height:40,borderRadius:10,background:'var(--brand-orange-50)',flexShrink:0,
 display:'flex',alignItems:'center',justifyContent:'center',color:'var(--brand-orange-700)'}}>
 <Icon name={t.icon} size={20}/>
 </div>
 <div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:14}}>{t.title}</div>
 <div style={{fontSize:12,color:'var(--ink-500)',marginTop:2}}>{t.desc}</div>
 </div>
 </div>
 ))}
 </div>
 )}
 <div style={{margin:'32px 0 16px',display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
 <h2>Browse the marketplace</h2>
 <div style={{display:'flex',gap:2,padding:4,background:'var(--ink-100)',borderRadius:999}}>
 <button onClick={() => setBrowseView('grid')} style={{padding:'6px 14px',borderRadius:999,border:'none',cursor:'pointer',fontFamily:'var(--font-body)',fontWeight:600,fontSize:12,background: browseView==='grid' ? 'var(--paper)' : 'transparent',color: browseView==='grid' ? 'var(--ink-900)' : 'var(--ink-500)',boxShadow: browseView==='grid' ? 'var(--shadow-xs)' : 'none'}}>Grid</button>
 <button onClick={() => setBrowseView('map')} style={{padding:'6px 14px',borderRadius:999,border:'none',cursor:'pointer',fontFamily:'var(--font-body)',fontWeight:600,fontSize:12,background: browseView==='map' ? 'var(--paper)' : 'transparent',color: browseView==='map' ? 'var(--ink-900)' : 'var(--ink-500)',boxShadow: browseView==='map' ? 'var(--shadow-xs)' : 'none'}}>Map</button>
 </div>
 </div>
 {browseView === 'grid' ? (
 <>
 <CategoryRail active={activeCat} onPick={setActiveCat}/>
 <div style={{marginTop:20}}>
 <ProductGrid products={filteredProducts} onSelect={p => { setSelected(p); setRoute('product'); }} onAddToCart={addToCart}/>
 </div>
 </>
 ) : (
 <MapSearch onSelect={p => { setSelected(p); setRoute('product'); }}/>
 )}
 </>
 )}
 {surface === 'marketplace' && route === 'feed' && (
 <FeedScreen
 onShop={p => { setSelected(p); setRoute('product'); }}
 onMessage={() => setRoute('messages')}/>
 )}
 {surface === 'marketplace' && route === 'community' && (
 <CommunityScreen onShop={p => { setSelected(p); setRoute('product'); }}/>
 )}
 {surface === 'marketplace' && route === 'product' && (
 <ProductDetail product={selected} onBack={() => setRoute('home')} onAddToCart={addToCart}
 onSwap={p => { setSelected(p); setRoute('swap'); }}
 onWatch={toggleWatch} watched={selected ? watched.includes(selected.id) : false}/>
 )}
 {surface === 'marketplace' && route === 'swap' && (
 <SwapOfferFlow product={selected} onBack={() => setRoute('product')}/>
 )}
 {surface === 'marketplace' && route === 'otp-collect' && (
 <OTPCollectionConfirm onBack={() => { setCart([]); setRoute('home'); }}
 onConfirmed={() => {}}/>
 )}
 {surface === 'marketplace' && route === 'cart' && (
 <CartView cart={cart} onUpdateQty={updateQty} onRemove={removeFromCart}
 onCheckout={() => setRoute('checkout')} onBrowse={() => setRoute('home')}/>
 )}
 {surface === 'marketplace' && route === 'checkout' && (
 <CheckoutView cart={cart} onSuccess={(method) => { setDeliveryMethod(method || 'pickup'); setRoute('payfast'); }}/>
 )}
 {surface === 'marketplace' && route === 'success' && (
 <OrderSuccess onContinue={() => { setCart([]); setRoute('home'); }}
 onConfirmCollect={() => setRoute('otp-collect')}/>
 )}
 {surface === 'marketplace' && route === 'orders' && (
 <OrdersList orders={SAMPLE_ORDERS} onTrack={() => setRoute('tracking')}/>
 )}
 {surface === 'marketplace' && route === 'dispute' && (
 <DisputeForm onBack={() => setRoute('orders')}/>
 )}
 {surface === 'marketplace' && route === 'login' && (
 <AuthLogin onLogin={() => setRoute('home')} onRegister={() => setRoute('register')} onForgot={() => setRoute('forgot')}/>
 )}
 {surface === 'marketplace' && route === 'register' && (
 <AuthRegister onRegister={() => setRoute('home')} onLogin={() => setRoute('login')}/>
 )}
 {surface === 'marketplace' && route === 'forgot' && (
 <AuthForgot onBack={() => setRoute('login')}/>
 )}
 {surface === 'marketplace' && route === 'profile' && (
 <ProfilePage onNav={setRoute}/>
 )}
 {surface === 'marketplace' && route === 'privacy' && (
 <PrivacyPolicy onBack={() => setRoute('home')}/>
 )}
 {surface === 'marketplace' && route === 'tracking' && (
 <OrderTracking onBack={() => setRoute('orders')} onDispute={() => setRoute('dispute')}/>
 )}
 {surface === 'marketplace' && route === 'verify' && (
 <IDVerifyWizard onComplete={() => setRoute('profile')} onBack={() => setRoute('profile')}/>
 )}
 {surface === 'marketplace' && route === 'proof' && (
 <div style={{maxWidth:600,margin:'0 auto'}}>
 <button onClick={() => setRoute('profile')} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Back to profile
 </button>
 <h1 style={{marginBottom:16}}>Proof of ownership</h1>
 <ProofOfOwnership kind="vehicle"/>
 <div style={{marginTop:16}}><ProofOfOwnership kind="property"/></div>
 </div>
 )}
 {surface === 'marketplace' && route === '2fa' && (
 <div style={{maxWidth:540,margin:'0 auto'}}>
 <button onClick={() => setRoute('profile')} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Back to profile
 </button>
 <h1 style={{marginBottom:16}}>Two-factor authentication</h1>
 <TwoFactorSetup/>
 </div>
 )}
 {surface === 'marketplace' && route === 'safe-meetup' && (
 <div style={{maxWidth:760,margin:'0 auto'}}>
 <button onClick={() => setRoute('home')} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Back
 </button>
 <h1 style={{marginBottom:16}}>Safe meet-up locations</h1>
 <SafeMeetupMap/>
 </div>
 )}
 {surface === 'marketplace' && route === 'saved' && (
 <WishlistPage saved={saved} watched={watched}
 onSelect={p => { setSelected(p); setRoute('product'); }}
 onUnsave={toggleSave} onToggleWatch={toggleWatch}/>
 )}
 {surface === 'marketplace' && route === 'messages' && !chatThread && (
 <ChatList onOpenThread={t => setChatThread(t)}/>
 )}
 {surface === 'marketplace' && route === 'messages' && chatThread && (
 <ChatThread thread={chatThread} onBack={() => setChatThread(null)}/>
 )}
 {surface === 'marketplace' && route === 'storefront' && (
 <SellerStorefront sellerName={selected?.seller} onBack={() => setRoute(selected ? 'product' : 'home')}
 onSelect={p => { setSelected(p); setRoute('product'); }}/>
 )}
 {surface === 'marketplace' && route === 'payfast' && (
 <PayFastRedirect amount={cart.reduce((s,i) => s + i.product.price * i.qty, 0) + 60}
 onComplete={() => setRoute(deliveryMethod === 'self' ? 'otp-collect' : 'success')}/>
 )}
 {surface === 'seller' && route === 'home' && (
 <SellerDashboard onCreateListing={() => setRoute('create')} onNav={setRoute}/>
 )}
 {surface === 'seller' && route === 'create' && (
 <UnifiedSellWizard onBack={() => setRoute('home')} onPublish={() => setRoute('home')}/>
 )}
 {surface === 'seller' && route === 'otp' && (
 <SellerOTPVerify onBack={() => setRoute('home')}/>
 )}
 </PageTransition>
 </main>
 )}

 {surface !== 'driver' && <AppFooter/>}

 {/* Mobile bottom nav */}
 {surface === 'marketplace' && (
 <MobileBottomNav active={route === 'home' ? 'home' : route} cartCount={cartCount}
 onNav={k => { if (k === 'sell') handleSurface('seller'); else if (k === 'browse') { setActiveCat('all'); setRoute('home'); } else setRoute(k); }}/>
 )}

 {/* Onboarding tour */}
 {showOnboarding && <OnboardingTour onComplete={() => setShowOnboarding(false)}/>}

 {/* PWA install banner */}
 {showPWA && <PWAInstallBanner onDismiss={() => setShowPWA(false)}/>}

 {/* Tweaks Panel */}
 <TweaksPanel title="Me2You Tweaks">
 <TweakSection label="Surface">
 <TweakRadio label="Active surface" value={surface}
 options={['marketplace','seller','admin','driver']}
 onChange={v => handleSurface(v)}/>
 </TweakSection>
 <TweakSection label="Theme">
 <TweakRadio label="Mode" value={tweaks.theme} options={['light','dark']}
 onChange={v => setTweak('theme', v)}/>
 </TweakSection>
 <TweakSection label="Layout">
 <TweakToggle label="Trust badges" value={tweaks.trustBadges}
 onChange={v => setTweak('trustBadges', v)}/>
 <TweakRadio label="Card density" value={tweaks.cardDensity}
 options={['compact','comfortable','showcase']}
 onChange={v => setTweak('cardDensity', v)}/>
 </TweakSection>
 <TweakSection label="Animation">
 <TweakRadio label="Level" value={tweaks.animationLevel}
 options={['none','subtle','lively']}
 onChange={v => setTweak('animationLevel', v)}/>
 </TweakSection>
 </TweaksPanel>
 </div>
 );
}

const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<ToastProvider><App/></ToastProvider>);
