import React, {useEffect,useMemo,useState} from 'react';
import {createRoot} from 'react-dom/client';
import {Search, ShoppingCart, Store, Package, User, LogOut, Plus, Menu, X, ArrowRight, ShieldCheck, Truck, Heart, LayoutDashboard, Globe, Smartphone, Laptop, Headphones, AlertCircle, CheckCircle2, Sparkles, ClipboardList, Star, Wallet, Users, Bell, LifeBuoy, Settings, TrendingUp, MessageCircle, BarChart3, Tag} from 'lucide-react';
import {createTravisClient,createTravisApi} from './travis-supabase.js';
import {createTravisCommerce} from './travis-commerce.js';
import './style.css';
import AdvancedWorkspace from './AdvancedWorkspace.jsx';

const env={url:import.meta.env.VITE_SUPABASE_URL,key:import.meta.env.VITE_SUPABASE_ANON_KEY};
let api=null,commerce=null,supabase=null,configError='';
try{if(env.url&&env.key){supabase=createTravisClient({url:env.url,publishableKey:env.key});api=createTravisApi(supabase);commerce=createTravisCommerce(supabase)}else configError='Add your Supabase URL and publishable key to the .env file, then restart the app.'}catch(e){configError=e.message}
const money=n=>new Intl.NumberFormat('en-TZ',{style:'currency',currency:'TZS',maximumFractionDigits:0}).format(Number(n||0));
const categories=[['All products',''],['Phones & Tablets','Phones'],['Computers','Computers'],['Audio & Speakers','Audio'],['Accessories','Accessories'],['Fashion','Fashion'],['Home & Living','Home']];
function App(){
 const [session,setSession]=useState(null),[profile,setProfile]=useState(null),[screen,setScreen]=useState('home'),[products,setProducts]=useState([]),[search,setSearch]=useState(''),[category,setCategory]=useState(''),[cart,setCart]=useState([]),[orders,setOrders]=useState([]),[stores,setStores]=useState([]),[myProducts,setMyProducts]=useState([]),[loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[notice,setNotice]=useState(''),[noticeType,setNoticeType]=useState('ok'),[authMode,setAuthMode]=useState('login'),[auth,setAuth]=useState({email:'',password:'',name:'',role:'buyer'}),[storeForm,setStoreForm]=useState({name:'',slug:'',description:''}),[productForm,setProductForm]=useState({title:'',description:'',category:'Phones',price_tzs:'',stock_quantity:'1'}),[activeStore,setActiveStore]=useState(''),[mobileMenu,setMobileMenu]=useState(false),[language,setLanguage]=useState('en'),[favorites,setFavorites]=useState([]),[adminData,setAdminData]=useState({stores:[],products:[],orders:[],users:[]}),[buyerAddresses,setBuyerAddresses]=useState([]),[addressForm,setAddressForm]=useState({label:'Home',recipient_name:'',phone:'',region:'Dar es Salaam',district:'',ward:'',street:'',details:''});
 const isReady=!!api;
 const say=(m,type='ok')=>{setNotice(m);setNoticeType(type);setTimeout(()=>setNotice(''),5000)};
 const loadProducts=async()=>{if(!commerce)return;try{setProducts(await commerce.marketplace.list({search,category,limit:60}))}catch(e){say(e.message,'err')}};
 const loadAccount=async(s)=>{if(!s||!api)return;try{const [p,st]=await Promise.all([api.profile.get(),api.stores.mine()]);setProfile(p);setStores(st);if(st[0]){setActiveStore(st[0].id);setMyProducts(await api.products.listMine(st[0].id))}else{setActiveStore('');setMyProducts([])};const [fav,addr]=await Promise.all([supabase.from('favorites').select('product_id,products(id,store_id,title,description,category,price_tzs,stock_quantity,media,stores(name,slug))').eq('user_id',s.user.id),supabase.from('addresses').select('*').eq('user_id',s.user.id).order('created_at',{ascending:false})]);if(!fav.error)setFavorites((fav.data||[]).map(x=>x.products).filter(Boolean));if(!addr.error)setBuyerAddresses(addr.data||[]);if(p.role==='admin'){setScreen('admin');}else if(p.role==='buyer'||p.role==='both'){await loadOrders();setScreen('buyer');}else if(p.role==='seller')setScreen('seller');}catch(e){say(e.message,'err')}};
 useEffect(()=>{loadProducts();setLoading(false)},[]);
 useEffect(()=>{if(!supabase)return;supabase.auth.getSession().then(({data})=>{setSession(data.session);if(data.session)loadAccount(data.session)});const {data:{subscription}}=supabase.auth.onAuthStateChange((_event,s)=>{setSession(s);if(s)setTimeout(()=>loadAccount(s),0);else{setProfile(null);setStores([]);setMyProducts([])}});return()=>subscription.unsubscribe()},[]);
 useEffect(()=>{const t=setTimeout(loadProducts,250);return()=>clearTimeout(t)},[search,category]);
 const total=cart.reduce((n,x)=>n+x.price_tzs*x.quantity,0);
 const addCart=p=>{setCart(old=>{const found=old.find(x=>x.id===p.id);return found?old.map(x=>x.id===p.id?{...x,quantity:Math.min(x.quantity+1,p.stock_quantity)}:x):[...old,{...p,quantity:1}]});say('Added to your cart')};
 const signOut=async()=>{try{await api.auth.signOut();setScreen('home');say('You have signed out')}catch(e){say(e.message,'err')}};
 const submitAuth=async e=>{e.preventDefault();if(!api)return say(configError,'err');setBusy(true);try{if(authMode==='login'){const d=await api.auth.signIn({email:auth.email,password:auth.password});setSession(d.session);say('Welcome back')}else{const d=await api.auth.signUp({email:auth.email,password:auth.password,displayName:auth.name,role:auth.role});if(d.session){setSession(d.session);say('Account created')}else say('Account created. Check your email to confirm before signing in.')}setScreen('home')}catch(e){say(e.message,'err')}finally{setBusy(false)}};
 const createStore=async e=>{e.preventDefault();setBusy(true);try{const s=await api.stores.create(storeForm);setStores(x=>[...x,s]);setActiveStore(s.id);setMyProducts([]);say('Store created. It is saved as a draft until activated by an administrator.')}catch(e){say(e.message,'err')}finally{setBusy(false)}};
 const createProduct=async e=>{e.preventDefault();setBusy(true);try{const p=await api.products.create({...productForm,store_id:activeStore,status:'draft'});setMyProducts(x=>[p,...x]);setProductForm({title:'',description:'',category:'Phones',price_tzs:'',stock_quantity:'1'});say('Product saved as draft. Publish after your store is approved.')}catch(e){say(e.message,'err')}finally{setBusy(false)}};
 const checkout=async()=>{if(!session){setAuthMode('login');setScreen('auth');return say('Sign in to place your order','err')}setBusy(true);try{const result=await commerce.checkout.create(cart.map(x=>({product_id:x.id,quantity:x.quantity})));setCart([]);say(`Order created: ${Array.isArray(result)?result.length:1} seller order(s). Payment is not yet collected.`);setScreen('orders');await loadOrders()}catch(e){say(e.message,'err')}finally{setBusy(false)}};
 const loadOrders=async()=>{try{setOrders(await commerce.orders.mine())}catch(e){say(e.message,'err')}};
 const go=s=>{setScreen(s);setMobileMenu(false);if(s==='orders'&&session)loadOrders();if(s==='buyer'&&session)loadOrders();if(s==='seller'&&session&&activeStore)api.products.listMine(activeStore).then(setMyProducts).catch(e=>say(e.message,'err'));if(s==='admin'&&session)loadAdmin()};
 const loadAdmin=async()=>{if(!supabase||profile?.role!=='admin')return;try{const [a,b,c,d]=await Promise.all([supabase.from('stores').select('*').order('created_at',{ascending:false}),supabase.from('products').select('*,stores(name)').order('created_at',{ascending:false}),supabase.from('orders').select('*,stores(name),order_items(title_snapshot,quantity)').order('created_at',{ascending:false}),supabase.from('profiles').select('id,display_name,role,preferred_language,created_at').order('created_at',{ascending:false})]);for(const x of [a,b,c,d])if(x.error)throw x.error;setAdminData({stores:a.data||[],products:b.data||[],orders:c.data||[],users:d.data||[]})}catch(e){say(e.message,'err')}};
 useEffect(()=>{if(profile?.role==='admin'&&screen==='admin')loadAdmin()},[profile?.role,screen]);
 const toggleFavorite=async p=>{if(!session){go('auth');return say('Sign in to save favourites','err')}const found=favorites.some(x=>x.id===p.id);try{if(found){const {error}=await supabase.from('favorites').delete().eq('user_id',session.user.id).eq('product_id',p.id);if(error)throw error;setFavorites(v=>v.filter(x=>x.id!==p.id));say('Removed from favourites')}else{const {error}=await supabase.from('favorites').insert({user_id:session.user.id,product_id:p.id});if(error)throw error;setFavorites(v=>[p,...v]);say('Saved to favourites')}}catch(e){say(e.message,'err')}};
 const saveAddress=async e=>{e.preventDefault();try{const {data,error}=await supabase.from('addresses').insert({...addressForm,user_id:session.user.id}).select().single();if(error)throw error;setBuyerAddresses(v=>[data,...v]);setAddressForm({label:'Home',recipient_name:'',phone:'',region:'Dar es Salaam',district:'',ward:'',street:'',details:''});say('Delivery address saved')}catch(e){say(e.message,'err')}};
 const adminUpdate=async(table,id,patch)=>{try{const {error}=await supabase.from(table).update(patch).eq('id',id);if(error)throw error;say('Record updated');loadAdmin()}catch(e){say(e.message,'err')}};
 const nav=[['Explore','home',Globe],['Buyer dashboard','buyer',LayoutDashboard],['My orders','orders',Package],['Seller studio','seller',Store],['TRAVIS AI Studio','ai',Sparkles],['Messages & offers','messages',MessageCircle],['RFQ / Quotations','rfq',ClipboardList],['Wholesale','wholesale',Package],['Auctions','auctions',TrendingUp],['Reviews','reviews',Star],['Returns & disputes','returns',AlertCircle],['Shipping & tracking','tracking',Truck],['Payments & payouts','payments',Wallet],['Promotions','promotions',Tag],['Analytics','analytics',BarChart3],['Customer CRM','customers',Users],['Storefront builder','storefront',Store],['Staff & permissions','staff',Users],['Notifications','notifications',Bell],['Integrations','integrations',Globe],['Help centre','help',LifeBuoy],['Settings','settings',Settings],...(profile?.role==='admin'?[['Admin console','admin',ShieldCheck]]:[])];
 return <div className="app">
 <header className="topbar"><button className="iconbtn mobileOnly" onClick={()=>setMobileMenu(!mobileMenu)}>{mobileMenu?<X/>:<Menu/>}</button><button className="brand" onClick={()=>go('home')}><span className="brandMark">T</span><span>TRAVIS<small>MARKETPLACE</small></span></button><div className="searchbar"><Search size={18}/><input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search products, brands and stores..."/><kbd>Search</kbd></div><div className="topActions"><button className="iconbtn lang" onClick={()=>setLanguage(language==='en'?'sw':'en')}><Globe size={17}/>{language==='en'?'EN':'SW'}</button><button className="iconbtn cartBtn" onClick={()=>go('cart')}><ShoppingCart/><span>Cart</span>{cart.length>0&&<b>{cart.reduce((n,x)=>n+x.quantity,0)}</b>}</button>{session?<button className="accountBtn" onClick={()=>go('account')}><User size={17}/><span>{profile?.display_name||'Account'}</span></button>:<button className="primary small" onClick={()=>{setAuthMode('login');go('auth')}}>Log in</button>}</div></header>
 <div className="layout"><aside className={`sidebar ${mobileMenu?'show':''}`}><div className="sideLabel">DISCOVER</div>{nav.map(([label,id,Icon])=><button key={id} className={`navItem ${screen===id?'selected':''}`} onClick={()=>go(id)}><Icon size={18}/>{label}</button>)}<div className="sideDivider"/><div className="sideLabel">YOUR SPACE</div><button className={`navItem ${screen==='cart'?'selected':''}`} onClick={()=>go('cart')}><ShoppingCart size={18}/>Shopping cart</button><button className={`navItem ${screen==='account'?'selected':''}`} onClick={()=>go('account')}><User size={18}/>My account</button><div className="sidePromo"><ShieldCheck/><b>Shop with confidence</b><p>Discover products from stores across Tanzania.</p></div><div className="sideFoot">Tanzania · TZS<br/>© 2026 TRAVIS</div></aside>
 <main className="main">
 {notice&&<div className={`notice ${noticeType}`}><span>{noticeType==='err'?<AlertCircle size={17}/>:<CheckCircle2 size={17}/>}</span>{notice}<button onClick={()=>setNotice('')}><X size={15}/></button></div>}
 {!isReady&&<div className="setupBanner"><AlertCircle/><div><b>Backend setup required</b><p>{configError} Browsing will work after Supabase is configured.</p></div></div>}
 {screen==='home'&&<><section className="hero"><div className="heroText"><span className="eyebrow">TANZANIA'S MARKETPLACE</span><h1>Find what you need.<br/><em>Shop with confidence.</em></h1><p>Discover products, explore stores and connect with sellers across Tanzania.</p><button className="heroBtn" onClick={()=>document.getElementById('marketplace')?.scrollIntoView({behavior:'smooth'})}>Explore marketplace <ArrowRight size={17}/></button></div><div className="heroArt"><div className="artCircle"><div className="artCard cardOne"><Smartphone size={35}/><span>Phones</span></div><div className="artCard cardTwo"><Laptop size={35}/><span>Computers</span></div><div className="artCard cardThree"><Headphones size={35}/><span>Audio</span></div><div className="artCore">T</div></div></div><div className="heroStats"><div><b>One marketplace</b><span>Many stores</span></div><div><b>TZS pricing</b><span>Made for Tanzania</span></div><div><b>Shop anywhere</b><span>Mobile friendly</span></div></div></section>
 <section className="trustRow"><div><ShieldCheck/><span><b>Discover stores</b><small>Explore products and sellers</small></span></div><div><Truck/><span><b>Order tracking</b><small>Follow your orders</small></span></div><div><Heart/><span><b>Your favourites</b><small>Keep products in view</small></span></div></section>
 <section id="marketplace" className="market"><div className="sectionHead"><div><span className="eyebrow">THE MARKETPLACE</span><h2>Explore products</h2><p>Find something worth bringing home.</p></div><span className="resultCount">{products.length} products</span></div><div className="categoryRail">{categories.map(([label,val])=><button key={label} onClick={()=>setCategory(val)} className={category===val?'active':''}>{label}</button>)}</div>
 {loading?<div className="empty">Loading marketplace...</div>:products.length===0?<div className="empty"><Package size={34}/><h3>No products found yet</h3><p>Products published by approved stores will appear here.</p></div>:<div className="productGrid">{products.map(p=><article className="productCard" key={p.id}><div className="productImage"><span className="productTag">{p.category||'Product'}</span><div className="placeholderIcon"><Package size={40}/></div></div><div className="productInfo"><small>{p.stores?.name||'TRAVIS Store'}</small><h3>{p.title}</h3><b>{money(p.price_tzs)}</b><div className="productBottom"><span>{p.stock_quantity} in stock</span><button onClick={()=>addCart(p)} disabled={p.stock_quantity<1}><Plus size={16}/> Add</button><button title="Save to favourites" onClick={()=>toggleFavorite(p)}><Heart size={15} fill={favorites.some(x=>x.id===p.id)?'currentColor':'none'}/></button></div></div></article>)}</div>}</section></>}
 {screen==='buyer'&&<section className="pageSection"><div className="sectionHead"><div><span className="eyebrow">YOUR TRAVIS</span><h2>Welcome, {profile?.display_name||'Shopper'}</h2><p>Discover products, manage purchases and connect with stores.</p></div><button className="primary" onClick={()=>go('home')}>Explore marketplace</button></div>{!session?<div className="empty"><User/><h3>Sign in to open your buyer dashboard</h3><button className="primary" onClick={()=>go('auth')}>Log in or create account</button></div>:<><div className="dashboardTiles"><button onClick={()=>go('orders')}><Package/><b>{orders.length}</b><span>Orders</span></button><button onClick={()=>go('cart')}><ShoppingCart/><b>{cart.length}</b><span>Cart items</span></button><button onClick={()=>document.getElementById('buyer-favorites')?.scrollIntoView({behavior:'smooth'})}><Heart/><b>{favorites.length}</b><span>Favourites</span></button><button onClick={()=>document.getElementById('buyer-addresses')?.scrollIntoView({behavior:'smooth'})}><Truck/><b>{buyerAddresses.length}</b><span>Addresses</span></button></div><div className="dashboardColumns"><div className="sellerProducts"><h3>Recent orders <span>{orders.length}</span></h3>{orders.slice(0,5).map(o=><div className="sellerProduct" key={o.id}><Package/><div><b>#{o.id.slice(0,8).toUpperCase()} · {o.stores?.name||'Store'}</b><small>{money(o.subtotal_tzs)} · {new Date(o.created_at).toLocaleDateString()}</small></div><span className={`status ${o.status}`}>{o.status}</span></div>)}{!orders.length&&<p className="muted">Your purchases will appear here.</p>}<button className="outlineBtn" onClick={()=>go('orders')}>View all orders</button></div><div className="sellerProducts" id="buyer-addresses"><h3>Delivery addresses <span>{buyerAddresses.length}</span></h3>{buyerAddresses.map(a=><div className="sellerProduct" key={a.id}><Truck/><div><b>{a.label} · {a.recipient_name}</b><small>{a.phone} · {a.region} {a.district||''} {a.ward||''}</small></div></div>)}<form className="inlineAddressForm" onSubmit={saveAddress}><label>Recipient name<input required value={addressForm.recipient_name} onChange={e=>setAddressForm({...addressForm,recipient_name:e.target.value})}/></label><label>Phone<input required value={addressForm.phone} onChange={e=>setAddressForm({...addressForm,phone:e.target.value})}/></label><label>Region<input required value={addressForm.region} onChange={e=>setAddressForm({...addressForm,region:e.target.value})}/></label><label>District<input value={addressForm.district} onChange={e=>setAddressForm({...addressForm,district:e.target.value})}/></label><label>Street / area<input value={addressForm.street} onChange={e=>setAddressForm({...addressForm,street:e.target.value})}/></label><button className="primary">Save address</button></form></div></div><div className="sellerProducts favoritesPanel" id="buyer-favorites"><h3>Saved products <span>{favorites.length}</span></h3>{favorites.length? <div className="productGrid">{favorites.map(p=><article className="productCard" key={p.id}><div className="productImage"><Package size={38}/></div><div className="productInfo"><small>{p.stores?.name||'TRAVIS Store'}</small><h3>{p.title}</h3><b>{money(p.price_tzs)}</b><div className="productBottom"><button onClick={()=>addCart(p)}>Add to cart</button><button onClick={()=>toggleFavorite(p)}><Heart fill="currentColor"/></button></div></div></article>)}</div>:<p className="muted">Tap the heart on any product to save it here.</p>}</div></>}</section>}
 {screen==='auth'&&<section className="authWrap"><div className="authCard"><div className="authLogo">T</div><span className="eyebrow">WELCOME TO TRAVIS</span><h2>{authMode==='login'?'Welcome back':'Create your account'}</h2><p>{authMode==='login'?'Sign in to continue shopping and manage your store.':'Join the marketplace as a buyer, seller or both.'}</p><form onSubmit={submitAuth}>{authMode==='signup'&&<><label>Full name<input required value={auth.name} onChange={e=>setAuth({...auth,name:e.target.value})} placeholder="Your name"/></label><label>How will you use TRAVIS?<select value={auth.role} onChange={e=>setAuth({...auth,role:e.target.value})}><option value="buyer">Shop & Buy</option><option value="seller">Sell Products</option><option value="both">Both</option></select></label></>}<label>Email address<input type="email" required value={auth.email} onChange={e=>setAuth({...auth,email:e.target.value})} placeholder="you@example.com"/></label><label>Password<input type="password" minLength="8" required value={auth.password} onChange={e=>setAuth({...auth,password:e.target.value})} placeholder="At least 8 characters"/></label><button className="primary full" disabled={busy||!isReady}>{busy?'Please wait...':authMode==='login'?'Log in':'Create account'}</button></form><div className="authSwitch">{authMode==='login'?"Don't have an account?":"Already have an account?"} <button onClick={()=>setAuthMode(authMode==='login'?'signup':'login')}>{authMode==='login'?'Sign up':'Log in'}</button></div><button className="guestBtn" onClick={()=>go('home')}>Continue browsing as guest</button></div></section>}
 {screen==='cart'&&<section className="pageSection"><div className="sectionHead"><div><span className="eyebrow">YOUR SELECTION</span><h2>Shopping cart</h2><p>Review your items before placing an order.</p></div></div>{cart.length===0?<div className="empty"><ShoppingCart size={35}/><h3>Your cart is empty</h3><button className="primary" onClick={()=>go('home')}>Explore products</button></div>:<div className="cartLayout"><div className="cartList">{cart.map(p=><div className="cartLine" key={p.id}><div className="miniProduct"><Package/></div><div className="cartDescription"><b>{p.title}</b><small>{p.stores?.name||'Store'}</small><strong>{money(p.price_tzs)}</strong></div><div className="quantity"><button onClick={()=>setCart(x=>x.map(i=>i.id===p.id?{...i,quantity:Math.max(1,i.quantity-1)}:i))}>−</button><b>{p.quantity}</b><button disabled={p.quantity>=p.stock_quantity} onClick={()=>setCart(x=>x.map(i=>i.id===p.id?{...i,quantity:i.quantity+1}:i))}>+</button></div><button className="remove" onClick={()=>setCart(x=>x.filter(i=>i.id!==p.id))}>Remove</button></div>)}</div><div className="summary"><h3>Order summary</h3><div><span>Subtotal</span><b>{money(total)}</b></div><div><span>Delivery</span><span>Calculated later</span></div><hr/><div className="sumTotal"><span>Total</span><b>{money(total)}</b></div><button className="primary full" onClick={checkout} disabled={busy}>{busy?'Processing...':'Create order'}</button><small>Order creation does not collect payment. Payment integration must be configured separately.</small></div></div>}</section>}
 {screen==='seller'&&<section className="pageSection"><div className="sectionHead"><div><span className="eyebrow">SELLER STUDIO</span><h2>Manage your business</h2><p>Set up your store and manage product listings.</p></div></div>{!session?<div className="empty"><Store/><h3>Sign in to open Seller Studio</h3><button className="primary" onClick={()=>go('auth')}>Log in or sign up</button></div>:<>{stores.length===0?<div className="formCard"><h3>Create your store</h3><p>Start with your store name and a unique web address.</p><form onSubmit={createStore}><label>Store name<input required value={storeForm.name} onChange={e=>setStoreForm({...storeForm,name:e.target.value,slug:e.target.value.toLowerCase().trim().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')})} placeholder="e.g. My Electronics Store"/></label><label>Store URL slug<input required pattern="[a-z0-9-]+" value={storeForm.slug} onChange={e=>setStoreForm({...storeForm,slug:e.target.value})} placeholder="my-electronics-store"/></label><label>Description<textarea value={storeForm.description} onChange={e=>setStoreForm({...storeForm,description:e.target.value})} placeholder="Tell customers about your store"/></label><button className="primary" disabled={busy}>{busy?'Creating...':'Create store'}</button></form></div>:<><div className="sellerHeader"><div className="storeAvatar"><Store/></div><div><h3>{stores.find(s=>s.id===activeStore)?.name||'Your store'}</h3><span className={`status ${stores.find(s=>s.id===activeStore)?.status}`}>{stores.find(s=>s.id===activeStore)?.status||'draft'}</span></div><select value={activeStore} onChange={async e=>{setActiveStore(e.target.value);setMyProducts(await api.products.listMine(e.target.value))}}>{stores.map(s=><option value={s.id} key={s.id}>{s.name}</option>)}</select></div><div className="sellerNotice"><ShieldCheck/><span>New stores and products are saved as drafts. An administrator must approve/activate them before they appear in public search.</span></div><div className="sellerGrid"><div className="formCard"><h3><Plus size={18}/> Add a product</h3><form onSubmit={createProduct}><label>Product name<input required value={productForm.title} onChange={e=>setProductForm({...productForm,title:e.target.value})} placeholder="Product name"/></label><label>Category<select value={productForm.category} onChange={e=>setProductForm({...productForm,category:e.target.value})}>{['Phones','Computers','Audio','Accessories','Fashion','Home','Other'].map(x=><option key={x}>{x}</option>)}</select></label><label>Price (TZS)<input type="number" min="0" step="1" required value={productForm.price_tzs} onChange={e=>setProductForm({...productForm,price_tzs:e.target.value})} placeholder="250000"/></label><label>Stock quantity<input type="number" min="0" step="1" required value={productForm.stock_quantity} onChange={e=>setProductForm({...productForm,stock_quantity:e.target.value})}/></label><label>Description<textarea value={productForm.description} onChange={e=>setProductForm({...productForm,description:e.target.value})} placeholder="Describe the product"/></label><button className="primary" disabled={busy}>{busy?'Saving...':'Save product draft'}</button></form></div><div className="sellerProducts"><h3>Your products <span>{myProducts.length}</span></h3>{myProducts.length===0?<div className="empty compact">No products added yet.</div>:myProducts.map(p=><div className="sellerProduct" key={p.id}><Package/><div><b>{p.title}</b><small>{money(p.price_tzs)} · Stock {p.stock_quantity}</small></div><span className={`status ${p.status}`}>{p.status}</span></div>)}</div></div></>}</>}</section>}
 {screen==='orders'&&<section className="pageSection"><div className="sectionHead"><div><span className="eyebrow">ORDER HISTORY</span><h2>My orders</h2><p>Review purchases made through TRAVIS.</p></div></div>{!session?<div className="empty"><Package/><h3>Sign in to view your orders</h3><button className="primary" onClick={()=>go('auth')}>Log in</button></div>:orders.length===0?<div className="empty"><Package/><h3>No orders yet</h3><p>Your orders will appear here after checkout.</p><button className="primary" onClick={()=>go('home')}>Explore products</button></div>:<div className="orderList">{orders.map(o=><article className="orderCard" key={o.id}><div><small>ORDER #{o.id.slice(0,8).toUpperCase()}</small><h3>{o.stores?.name||'TRAVIS Store'}</h3><span>{new Date(o.created_at).toLocaleString()}</span></div><div className="orderItems">{o.order_items?.map(i=><p key={i.id}>{i.quantity} × {i.title_snapshot}</p>)}</div><b>{money(o.subtotal_tzs)}</b><span className={`status ${o.status}`}>{o.status}</span></article>)}</div>}</section>}
 {screen==='admin'&&<section className="pageSection"><div className="sectionHead"><div><span className="eyebrow">TRAVIS CONTROL CENTRE</span><h2>Administrator dashboard</h2><p>Review marketplace activity and moderate stores, products and orders.</p></div><button className="outlineBtn" onClick={loadAdmin}>Refresh data</button></div>{profile?.role!=='admin'?<div className="empty"><ShieldCheck/><h3>Administrator permission required</h3><p>This area is protected by database role checks.</p></div>:<><div className="dashboardTiles"><div><Store/><b>{adminData.stores.length}</b><span>Stores</span></div><div><Package/><b>{adminData.products.length}</b><span>Products</span></div><div><ShoppingCart/><b>{adminData.orders.length}</b><span>Orders</span></div><div><User/><b>{adminData.users.length}</b><span>Users</span></div></div><div className="sellerProducts adminPanel"><h3>Store approvals</h3>{adminData.stores.map(st=><div className="sellerProduct" key={st.id}><Store/><div><b>{st.name}</b><small>/{st.slug} · Owner {st.owner_id?.slice(0,8)}</small></div><span className={`status ${st.status}`}>{st.status}</span><select value={st.status} onChange={e=>adminUpdate('stores',st.id,{status:e.target.value})}><option value="draft">Draft</option><option value="active">Approve / Active</option><option value="suspended">Suspend</option></select></div>)}</div><div className="sellerProducts adminPanel"><h3>Product moderation</h3>{adminData.products.map(pr=><div className="sellerProduct" key={pr.id}><Package/><div><b>{pr.title}</b><small>{pr.stores?.name||'Store'} · {money(pr.price_tzs)} · Stock {pr.stock_quantity}</small></div><span className={`status ${pr.status}`}>{pr.status}</span><select value={pr.status} onChange={e=>adminUpdate('products',pr.id,{status:e.target.value})}><option value="draft">Draft</option><option value="active">Publish</option><option value="archived">Archive</option></select></div>)}</div><div className="sellerProducts adminPanel"><h3>Orders</h3>{adminData.orders.map(o=><div className="sellerProduct" key={o.id}><ShoppingCart/><div><b>#{o.id.slice(0,8).toUpperCase()} · {o.stores?.name||'Store'}</b><small>{money(o.subtotal_tzs)} · {new Date(o.created_at).toLocaleString()}</small></div><span className={`status ${o.status}`}>{o.status}</span><select value={o.status} onChange={e=>adminUpdate('orders',o.id,{status:e.target.value})}><option value="pending">Pending</option><option value="confirmed">Confirmed</option><option value="processing">Processing</option><option value="shipped">Shipped</option><option value="delivered">Delivered</option><option value="cancelled">Cancelled</option></select></div>)}</div><div className="sellerProducts adminPanel"><h3>Customer and seller accounts</h3>{adminData.users.map(u=><div className="sellerProduct" key={u.id}><User/><div><b>{u.display_name||'TRAVIS member'}</b><small>{u.id}</small></div><select value={u.role} onChange={async e=>{try{const {error}=await supabase.rpc('travis_admin_set_role',{p_user_id:u.id,p_role:e.target.value});if(error)throw error;say('Account role updated');loadAdmin()}catch(err){say(err.message,'err')}}}><option value="buyer">Buyer</option><option value="seller">Seller</option><option value="both">Both</option><option value="admin">Admin</option></select></div>)}</div></>}</section>}
 {['ai','ai-shop','ai-seller','ai-listing','ai-pricing','ai-support','ai-marketing','ai-translate','ai-risk','ai-visual','messages','rfq','wholesale','auctions','reviews','returns','tracking','payments','promotions','analytics','customers','staff','storefront','notifications','integrations','help','settings'].includes(screen)&&<AdvancedWorkspace screen={screen} onNavigate={go} profile={profile}/> }
 {screen==='account'&&<section className="pageSection"><div className="sectionHead"><div><span className="eyebrow">ACCOUNT SETTINGS</span><h2>My account</h2></div></div>{!session?<div className="empty"><User/><h3>You are browsing as a guest</h3><button className="primary" onClick={()=>go('auth')}>Log in or sign up</button></div>:<div className="accountCard"><div className="accountAvatar"><User/></div><h3>{profile?.display_name||'TRAVIS member'}</h3><p>{session.user.email}</p><div className="accountMeta"><span>Account type</span><b>{profile?.role||'buyer'}</b></div><div className="accountMeta"><span>Language</span><b>{profile?.preferred_language==='sw'?'Kiswahili':'English'}</b></div><button className="outlineBtn" onClick={signOut}><LogOut size={17}/> Sign out</button></div>}</section>}
 </main></div><footer className="footer"><span><b>TRAVIS</b> — Discover. Connect. Shop.</span><span>Built for Tanzania · TZS</span></footer></div>
}

createRoot(document.getElementById('root')).render(<App/>);
