/* Me2You - Polish features: Notifications, Search suggestions, Filters, Wishlist, Storefront, Chat, PayFast, Onboarding, Analytics, Audit log, PWA banner */
/* global React, Icon, StatusTag, Price, panelStyle, btnPrimary, btnGhost, btnSmall, btnDanger, PRODUCTS */

const { useState, useEffect, useRef } = React;

/* =================================================================
 1. NOTIFICATIONS BELL
================================================================= */
const NOTIFICATIONS = [
 { id:0, type:'price-drop', icon:'tag', title:'Price dropped', body:'Price dropped from R 349 to R 299 on Running shoes, Nike sz 10.', time:'2 days ago', unread:true, color:'var(--brand-orange)' },
 { id:1, type:'order', icon:'truck', title:'Your order is on the way', body:'Bongani K. is heading to you with the Hisense TV.', time:'5 min ago', unread:true, color:'var(--info)' },
 { id:2, type:'payment', icon:'wallet', title:'You\'re paid up', body:'Payment of R 1 910 received for M2Y-2026-00248.', time:'1 hour ago', unread:true, color:'var(--success)' },
 { id:3, type:'message', icon:'message-circle', title:'New message from Thandi K.', body:'"Hi, is the price negotiable?"', time:'2 hours ago', unread:true, color:'var(--brand-orange)' },
 { id:4, type:'review', icon:'star', title:'New 5-star review', body:'Nomsa M. left you a glowing review.', time:'Yesterday', unread:false, color:'var(--warning)' },
 { id:5, type:'dispute', icon:'triangle-alert', title:'Dispute resolved', body:'M2Y-2026-00232 was resolved in your favour.', time:'2 days ago', unread:false, color:'var(--danger)' },
];

function NotificationBell() {
 const [open, setOpen] = useState(false);
 const unread = NOTIFICATIONS.filter(n => n.unread).length;
 return (
 <div style={{position:'relative'}}>
 <button onClick={() => setOpen(!open)} style={{
 display:'inline-flex',alignItems:'center',justifyContent:'center',
 padding:'10px',borderRadius:'var(--radius-md)',background:'transparent',
 border:'none',cursor:'pointer',color:'var(--ink-700)',position:'relative'
 }}>
 <Icon name="bell" size={18}/>
 {unread > 0 && (
 <span style={{position:'absolute',top:4,right:4,background:'var(--danger)',color:'white',
 fontSize:10,fontWeight:800,borderRadius:999,width:16,height:16,
 display:'flex',alignItems:'center',justifyContent:'center'}}>{unread}</span>
 )}
 </button>
 {open && (
 <>
 <div onClick={() => setOpen(false)} style={{position:'fixed',inset:0,zIndex:30}}/>
 <div style={{position:'absolute',top:'calc(100% + 4px)',right:0,width:360,...panelStyle,padding:0,
 boxShadow:'var(--shadow-lg)',zIndex:40,marginBottom:0,maxHeight:480,overflow:'auto',animation:'pop .2s ease'}}>
 <div style={{padding:'12px 16px',borderBottom:'1px solid var(--ink-100)',display:'flex',justifyContent:'space-between',alignItems:'center',position:'sticky',top:0,background:'var(--paper)'}}>
 <h3 style={{fontSize:15,margin:0}}>Notifications</h3>
 <button style={{background:'none',border:'none',cursor:'pointer',color:'var(--brand-orange-700)',fontSize:12,fontWeight:600}}>Mark all read</button>
 </div>
 {NOTIFICATIONS.map(n => (
 <div key={n.id} style={{padding:'12px 16px',borderBottom:'1px solid var(--ink-100)',display:'flex',gap:10,
 background: n.unread ? 'var(--brand-orange-50)' : 'transparent',cursor:'pointer'}}
 onMouseEnter={e => e.currentTarget.style.background='var(--ink-50)'}
 onMouseLeave={e => e.currentTarget.style.background= n.unread ? 'var(--brand-orange-50)' : 'transparent'}>
 <div style={{width:32,height:32,borderRadius:8,flexShrink:0,
 background:`color-mix(in oklch, ${n.color} 15%, white)`,color:n.color,
 display:'flex',alignItems:'center',justifyContent:'center'}}>
 <Icon name={n.icon} size={16}/>
 </div>
 <div style={{flex:1,minWidth:0}}>
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:8}}>
 <strong style={{fontSize:13,fontFamily:'var(--font-body)'}}>{n.title}</strong>
 {n.unread && <span style={{width:8,height:8,borderRadius:999,background:'var(--brand-orange)',flexShrink:0,marginTop:4}}/>}
 </div>
 <p style={{fontSize:12,color:'var(--ink-700)',margin:'2px 0',lineHeight:1.4}}>{n.body}</p>
 <div style={{fontSize:11,color:'var(--ink-400)'}}>{n.time}</div>
 </div>
 </div>
 ))}
 </div>
 </>
 )}
 </div>
 );
}

/* =================================================================
 2. LIVE SEARCH SUGGESTIONS
================================================================= */
function SearchSuggestions({ value, onChange, onSelect }) {
 const [focused, setFocused] = useState(false);
 const recent = ['Samsung A14', 'Power drill', 'School blazer'];
 const trending = ['iPhone', 'Microwave', 'Bicycle', 'Cast-iron pot'];
 
 const matches = value ? PRODUCTS.filter(p => 
 p.title.toLowerCase().includes(value.toLowerCase())
 ).slice(0,5) : [];

 return (
 <div style={{position:'relative',maxWidth:600,width:'100%'}}>
 <div style={{position:'absolute',left:14,top:'50%',transform:'translateY(-50%)',color:'var(--ink-400)',zIndex:2}}>
 <Icon name="search" size={18}/>
 </div>
 <input value={value} onChange={e => onChange(e.target.value)}
 onFocus={() => setFocused(true)}
 onBlur={() => setTimeout(() => setFocused(false), 200)}
 placeholder="Search listings, e.g. 'Hisense TV'"
 style={{width:'100%',padding:'12px 40px 12px 42px',border:'1.5px solid var(--ink-200)',
 borderRadius:'var(--radius-pill)',background:'var(--ink-50)',
 fontFamily:'var(--font-body)',fontSize:14,boxSizing:'border-box',
 transition:'border-color .15s'}}/>
 {value && (
 <button onClick={() => onChange('')} style={{position:'absolute',right:14,top:'50%',transform:'translateY(-50%)',
 background:'none',border:'none',cursor:'pointer',color:'var(--ink-400)',zIndex:2}}>
 <Icon name="x" size={16}/>
 </button>
 )}
 
 {focused && (
 <div style={{position:'absolute',top:'calc(100% + 6px)',left:0,right:0,...panelStyle,marginBottom:0,padding:8,
 zIndex:30,maxHeight:440,overflow:'auto',animation:'pop .15s ease'}}>
 {matches.length > 0 && (
 <>
 <div style={{padding:'8px 12px',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,
 color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.08em'}}>Listings</div>
 {matches.map(p => (
 <button key={p.id} onClick={() => onSelect(p)} style={{display:'flex',alignItems:'center',gap:12,padding:'10px 12px',width:'100%',
 background:'none',border:'none',cursor:'pointer',borderRadius:8,textAlign:'left'}}
 onMouseEnter={e => e.currentTarget.style.background='var(--ink-50)'}
 onMouseLeave={e => e.currentTarget.style.background='none'}>
 <div style={{width:36,height:36,borderRadius:8,background:p.bg,
 display:'flex',alignItems:'center',justifyContent:'center',fontSize:18,flexShrink:0}}>{p.emoji}</div>
 <div style={{flex:1,minWidth:0}}>
 <div style={{fontFamily:'var(--font-body)',fontWeight:600,fontSize:13,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.title}</div>
 <div style={{fontSize:11,color:'var(--ink-500)'}}>{p.location} - R {p.price.toLocaleString('en-ZA')}</div>
 </div>
 </button>
 ))}
 </>
 )}
 {!value && (
 <>
 <div style={{padding:'8px 12px',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,
 color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.08em'}}>Recent searches</div>
 {recent.map(r => (
 <button key={r} onClick={() => onChange(r)} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 12px',width:'100%',
 background:'none',border:'none',cursor:'pointer',borderRadius:8,textAlign:'left',
 fontFamily:'var(--font-body)',fontSize:13,color:'var(--ink-700)'}}>
 <Icon name="clock" size={14}/> {r}
 </button>
 ))}
 <div style={{padding:'8px 12px',marginTop:8,fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,
 color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.08em'}}>Trending</div>
 <div style={{display:'flex',gap:6,flexWrap:'wrap',padding:'0 12px 8px'}}>
 {trending.map(t => (
 <button key={t} onClick={() => onChange(t)} style={{padding:'6px 12px',borderRadius:999,
 background:'var(--ink-100)',border:'none',cursor:'pointer',
 fontFamily:'var(--font-body)',fontSize:12,fontWeight:600,color:'var(--ink-700)'}}>
 {t}
 </button>
 ))}
 </div>
 </>
 )}
 </div>
 )}
 </div>
 );
}

/* =================================================================
 3. BROWSE FILTERS SIDEBAR
================================================================= */
function BrowseFilters({ filters, onChange }) {
 return (
 <aside style={{...panelStyle,marginBottom:0,position:'sticky',top:96}}>
 <h3 style={{fontSize:15,margin:'0 0 12px',display:'flex',alignItems:'center',gap:6}}>
 <Icon name="filter" size={16}/> Filters
 </h3>
 
 <div style={{marginBottom:16}}>
 <label style={{display:'block',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8}}>Price (R)</label>
 <div style={{display:'flex',gap:8}}>
 <input value={filters.minPrice || ''} onChange={e => onChange({...filters, minPrice: e.target.value})}
 type="number" placeholder="Min" style={inputStyle}/>
 <input value={filters.maxPrice || ''} onChange={e => onChange({...filters, maxPrice: e.target.value})}
 type="number" placeholder="Max" style={inputStyle}/>
 </div>
 </div>

 <div style={{marginBottom:16}}>
 <label style={{display:'block',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8}}>Condition</label>
 <div style={{display:'flex',flexDirection:'column',gap:6}}>
 {['New','Like new','Good','Fair'].map(c => (
 <label key={c} style={{display:'flex',alignItems:'center',gap:8,fontSize:13,cursor:'pointer'}}>
 <input type="checkbox" checked={filters.conditions?.includes(c) || false}
 onChange={e => {
 const arr = filters.conditions || [];
 onChange({...filters, conditions: e.target.checked ? [...arr, c] : arr.filter(x => x !== c)});
 }}
 style={{accentColor:'var(--brand-orange)'}}/>
 {c}
 </label>
 ))}
 </div>
 </div>

 <div style={{marginBottom:16}}>
 <label style={{display:'block',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8}}>Sort by</label>
 <select value={filters.sort || 'newest'} onChange={e => onChange({...filters, sort: e.target.value})}
 style={{...inputStyle,width:'100%'}}>
 <option value="newest">Newest first</option>
 <option value="price-asc">Price: low to high</option>
 <option value="price-desc">Price: high to low</option>
 <option value="rating">Best rated</option>
 </select>
 </div>

 <button onClick={() => onChange({})} style={{...btnSmall,width:'100%',justifyContent:'center'}}>
 <Icon name="x" size={14}/> Clear filters
 </button>
 </aside>
 );
}

const inputStyle = {
 padding:'8px 12px',border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',
 fontFamily:'var(--font-body)',fontSize:13,background:'var(--paper)',width:'100%',boxSizing:'border-box'
};

/* =================================================================
 4. WISHLIST / SAVED PAGE
================================================================= */
function WishlistPage({ saved, watched = [], onSelect, onUnsave, onToggleWatch }) {
 const [tab, setTab] = useState('saved');
 const savedItems = saved.map(id => PRODUCTS.find(p => p.id === id)).filter(Boolean);
 const watchedItems = watched.map(id => PRODUCTS.find(p => p.id === id)).filter(Boolean);
 const items = tab === 'saved' ? savedItems : watchedItems;

 const card = (p) => {
 const isWatched = watched.includes(p.id);
 return (
 <div key={p.id} onClick={() => onSelect(p)} style={{...panelStyle,padding:10,cursor:'pointer',marginBottom:0}}>
 <div style={{aspectRatio:1,borderRadius:14,backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center'}}/>
 <div style={{padding:'8px 4px 0'}}>
 <h3 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:14,margin:'4px 0'}}>{p.title}</h3>
 <Price amount={p.price} size="sm"/>
 <button onClick={e => { e.stopPropagation(); onToggleWatch && onToggleWatch(p.id); }}
 style={{...btnSmall,marginTop:8,width:'100%',justifyContent:'center',fontSize:12,minHeight:36,
 color: isWatched ? 'var(--brand-orange-700)' : 'var(--ink-700)',
 borderColor: isWatched ? 'var(--brand-orange)' : 'var(--ink-300)'}}>
 <Icon name="eye" size={14} fill={isWatched ? 'currentColor' : 'none'}/> {isWatched ? 'Watching - on' : 'Watch'}
 </button>
 {tab === 'saved' && (
 <button onClick={e => { e.stopPropagation(); onUnsave(p.id); }}
 style={{...btnSmall,marginTop:6,width:'100%',justifyContent:'center',color:'var(--danger)',fontSize:12,minHeight:36}}>
 <Icon name="heart" size={14} fill="currentColor"/> Unsave
 </button>
 )}
 </div>
 </div>
 );
 };

 return (
 <div>
 <h1 style={{marginBottom:16}}>Saved &amp; watching</h1>
 <div style={{display:'flex',gap:2,padding:4,background:'var(--ink-100)',borderRadius:999,marginBottom:20,width:'fit-content'}}>
 {[
 { key:'saved', label:`Saved (${savedItems.length})` },
 { key:'watching', label:`Watching (${watchedItems.length})` },
 ].map(t => (
 <button key={t.key} onClick={() => setTab(t.key)} style={{
 padding:'8px 18px',borderRadius:999,border:'none',cursor:'pointer',minHeight:36,
 fontFamily:'var(--font-body)',fontWeight:600,fontSize:13,
 background: tab === t.key ? 'var(--paper)' : 'transparent',
 color: tab === t.key ? 'var(--ink-900)' : 'var(--ink-500)',
 boxShadow: tab === t.key ? 'var(--shadow-xs)' : 'none',transition:'all .15s'
 }}>{t.label}</button>
 ))}
 </div>

 {tab === 'watching' && watchedItems.length > 0 && (
 <div style={{...panelStyle,background:'var(--success-100)',borderColor:'var(--success)',fontSize:13,color:'var(--status-paid-fg)',display:'flex',gap:8,alignItems:'start'}}>
 <Icon name="bell" size={16} stroke={2}/>
 <span>Items you watch send a free in-app alert if the seller drops the price.</span>
 </div>
 )}

 {items.length === 0 ? (
 <div style={{textAlign:'center',padding:'64px 24px'}}>
 <div style={{width:72,height:72,borderRadius:999,background:'var(--ink-100)',display:'inline-flex',alignItems:'center',justifyContent:'center',color:'var(--ink-400)',marginBottom:16}}>
 <Icon name={tab === 'saved' ? 'heart' : 'eye'} size={32}/>
 </div>
 <h3>{tab === 'saved' ? 'No saved items yet' : 'You are not watching anything yet'}</h3>
 <p style={{color:'var(--ink-500)'}}>
 {tab === 'saved' ? 'Tap the heart on any listing to save it for later.' : 'Tap Watch on a listing to be told if the price drops.'}
 </p>
 </div>
 ) : (
 <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))',gap:16}}>
 {items.map(card)}
 </div>
 )}
 </div>
 );
}

/* =================================================================
 5. SELLER STOREFRONT
================================================================= */
function SellerStorefront({ sellerName, onBack, onSelect }) {
 const seller = sellerName || 'Sipho M.';
 const sellerListings = PRODUCTS.filter(p => p.seller === seller);
 const allRatings = sellerListings.map(p => p.rating);
 const avgRating = (allRatings.reduce((a,b) => a+b, 0) / allRatings.length).toFixed(1);
 const [following, setFollowing] = useState(false);

 return (
 <div>
 <button onClick={onBack} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Back
 </button>
 <div style={{...panelStyle,padding:24,display:'flex',alignItems:'center',gap:16}}>
 <div style={{width:72,height:72,borderRadius:999,background:'var(--brand-orange-100)',
 display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',
 fontWeight:700,fontSize:28,color:'var(--brand-orange-700)'}}>
 {seller.charAt(0)}
 </div>
 <div style={{flex:1}}>
 <h1 style={{margin:'0 0 4px',fontSize:24}}>{seller}</h1>
 <div style={{fontSize:13,color:'var(--ink-500)',display:'flex',gap:12,flexWrap:'wrap'}}>
 <span> {avgRating} avg</span>
 <span> - </span>
 <span>{sellerListings.length} listings</span>
 <span> - </span>
 <span><Icon name="map-pin" size={11}/> {sellerListings[0]?.location}</span>
 <span> - </span>
 <span>Joined Mar 2025</span>
 </div>
 </div>
 <div style={{display:'flex',gap:8}}>
 <button onClick={() => setFollowing(!following)} style={following ? btnGhost : btnPrimary}>
 <Icon name={following ? 'check' : 'plus'} size={16}/> {following ? 'Following' : 'Follow'}
 </button>
 <button style={btnGhost}><Icon name="message-circle" size={16}/> Message</button>
 </div>
 </div>

 <h2 style={{marginTop:32,marginBottom:16}}>Listings from {seller}</h2>
 <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))',gap:16}}>
 {sellerListings.map(p => (
 <div key={p.id} onClick={() => onSelect && onSelect(p)} style={{...panelStyle,padding:10,cursor:'pointer',marginBottom:0}}>
 <div style={{aspectRatio:1,borderRadius:14,background:p.bg,display:'flex',alignItems:'center',justifyContent:'center',fontSize:48}}>{p.emoji}</div>
 <div style={{padding:'8px 4px 0'}}>
 <h3 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:14,margin:'4px 0'}}>{p.title}</h3>
 <Price amount={p.price} size="sm"/>
 </div>
 </div>
 ))}
 </div>
 </div>
 );
}

/* =================================================================
 6. MESSAGES / CHAT
================================================================= */
const CHAT_THREADS = [
 { id:1, with:'Sipho M.', last:'I can drop it off tomorrow if that works', time:'5 min ago', unread:true, avatar:'S', bg:'var(--brand-orange-100)' },
 { id:2, with:'Thandi K.', last:'Sure, R1800 works for me', time:'2 hours ago', unread:false, avatar:'T', bg:'var(--success-100)' },
 { id:3, with:'Mama K.', last:'Is the cast iron pot still available?', time:'Yesterday', unread:false, avatar:'M', bg:'var(--info-100)' },
];

function ChatList({ onOpenThread }) {
 return (
 <div>
 <h1 style={{marginBottom:24}}>Messages</h1>
 {CHAT_THREADS.map(t => (
 <div key={t.id} onClick={() => onOpenThread(t)} style={{...panelStyle,display:'flex',gap:12,alignItems:'center',cursor:'pointer'}}>
 <div style={{width:48,height:48,borderRadius:999,background:t.bg,
 display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',
 fontWeight:700,fontSize:18}}>{t.avatar}</div>
 <div style={{flex:1,minWidth:0}}>
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
 <strong style={{fontSize:14}}>{t.with}</strong>
 <span style={{fontSize:11,color:'var(--ink-400)'}}>{t.time}</span>
 </div>
 <p style={{fontSize:13,color:t.unread ? 'var(--ink-900)' : 'var(--ink-500)',margin:'4px 0 0',
 fontWeight: t.unread ? 600 : 400,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{t.last}</p>
 </div>
 {t.unread && <div style={{width:8,height:8,borderRadius:999,background:'var(--brand-orange)'}}/>}
 </div>
 ))}
 </div>
 );
}

function ChatThread({ thread, onBack }) {
 const [input, setInput] = useState('');
 const [messages, setMessages] = useState([
 { from:'them', text:'Hi! Is this still available?', time:'10:23' },
 { from:'me', text:'Yes it is! In great condition.', time:'10:25' },
 { from:'them', text:'Would you take R 1 800?', time:'10:26' },
 { from:'me', text:'Hmm, I could do R 1 850.', time:'10:28' },
 { from:'them', text:thread?.last || 'I can drop it off tomorrow if that works', time:'10:30' },
 ]);
 const send = () => {
 if (!input.trim()) return;
 setMessages(prev => [...prev, { from:'me', text:input, time:'now' }]);
 setInput('');
 };
 return (
 <div style={{maxWidth:600,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 messages
 </button>
 <div style={{...panelStyle,padding:0,height:500,display:'flex',flexDirection:'column'}}>
 <div style={{padding:16,borderBottom:'1px solid var(--ink-100)',display:'flex',alignItems:'center',gap:12}}>
 <div style={{width:40,height:40,borderRadius:999,background:thread?.bg || 'var(--brand-orange-100)',
 display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',
 fontWeight:700,fontSize:16}}>{thread?.avatar || 'S'}</div>
 <div>
 <strong style={{fontSize:14}}>{thread?.with || 'Sipho M.'}</strong>
 <div style={{fontSize:12,color:'var(--success)',display:'flex',alignItems:'center',gap:4}}>
 <span style={{width:6,height:6,borderRadius:999,background:'var(--success)'}}/> Online
 </div>
 </div>
 </div>
 <div style={{flex:1,overflow:'auto',padding:16,display:'flex',flexDirection:'column',gap:8}}>
 {messages.map((m,i) => (
 <div key={i} style={{display:'flex',justifyContent: m.from === 'me' ? 'flex-end' : 'flex-start'}}>
 <div style={{maxWidth:'70%',padding:'10px 14px',borderRadius: m.from === 'me' ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
 background: m.from === 'me' ? 'var(--brand-orange)' : 'var(--ink-100)',
 color: m.from === 'me' ? 'white' : 'var(--ink-900)',
 fontSize:14,fontFamily:'var(--font-body)',lineHeight:1.4}}>
 {m.text}
 <div style={{fontSize:10,opacity:.7,marginTop:4,textAlign:'right'}}>{m.time}</div>
 </div>
 </div>
 ))}
 </div>
 <div style={{padding:12,borderTop:'1px solid var(--ink-100)',display:'flex',gap:8}}>
 <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
 placeholder="Type a message..." style={{flex:1,padding:'10px 14px',border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-pill)',fontFamily:'var(--font-body)',fontSize:14}}/>
 <button onClick={send} style={{...btnPrimary,padding:'10px 16px'}}>
 <Icon name="arrow-right" size={16}/>
 </button>
 </div>
 </div>
 </div>
 );
}

/* =================================================================
 7. PAYFAST SIMULATION
================================================================= */
function PayFastRedirect({ amount, onComplete }) {
 const [stage, setStage] = useState(0); // 0=loading, 1=form, 2=processing
 useEffect(() => {
 const t = setTimeout(() => setStage(1), 1200);
 return () => clearTimeout(t);
 }, []);
 
 const pay = () => {
 setStage(2);
 setTimeout(() => onComplete(), 1800);
 };

 return (
 <div style={{maxWidth:500,margin:'0 auto',padding:'48px 0'}}>
 <div style={{...panelStyle,padding:32}}>
 <div style={{textAlign:'center',marginBottom:24}}>
 <div style={{display:'inline-flex',alignItems:'center',gap:8,
 background:'linear-gradient(135deg,#1B4F86,#2D7AC7)',color:'white',
 padding:'8px 16px',borderRadius:8,fontFamily:'var(--font-display)',fontWeight:700,fontSize:18}}>
 <Icon name="shield-check" size={18}/> PayFast
 </div>
 <div style={{fontSize:11,color:'var(--ink-500)',marginTop:8,fontFamily:'var(--font-mono)',letterSpacing:'.06em'}}>SECURE PAYMENT GATEWAY - ZA</div>
 </div>

 {stage === 0 && (
 <div style={{textAlign:'center',padding:40}}>
 <div style={{width:48,height:48,borderRadius:999,border:'3px solid var(--info-100)',
 borderTopColor:'var(--info)',animation:'spin 1s linear infinite',margin:'0 auto'}}/>
 <p style={{marginTop:16,color:'var(--ink-500)'}}>Connecting to PayFast...</p>
 </div>
 )}

 {stage === 1 && (
 <>
 <div style={{textAlign:'center',padding:'16px 0 24px',borderBottom:'1px solid var(--ink-100)',marginBottom:20}}>
 <div style={{fontSize:13,color:'var(--ink-500)'}}>Paying Me2You (Pty) Ltd</div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:36,marginTop:4}}>
 R {amount?.toLocaleString('en-ZA') || '1 910'}
 </div>
 </div>
 <div style={{display:'flex',flexDirection:'column',gap:12}}>
 <div style={{display:'flex',gap:8}}>
 {['Card','EFT','Mobile'].map((m,i) => (
 <button key={m} style={{
 flex:1,padding:'12px',borderRadius:'var(--radius-md)',cursor:'pointer',
 border: i === 0 ? '2px solid var(--info)' : '1.5px solid var(--ink-200)',
 background: i === 0 ? 'var(--info-100)' : 'var(--paper)',
 fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,color: i === 0 ? 'var(--info)' : 'var(--ink-700)',
 }}>{m}</button>
 ))}
 </div>
 <input placeholder="Card number" defaultValue="4242 4242 4242 4242" style={inputStyle}/>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
 <input placeholder="MM/YY" defaultValue="08/28" style={inputStyle}/>
 <input placeholder="CVV" defaultValue="123" type="password" style={inputStyle}/>
 </div>
 <button onClick={pay} style={{...btnPrimary,width:'100%',justifyContent:'center',padding:'14px',marginTop:8,
 background:'#1B4F86',boxShadow:'0 8px 18px rgba(27,79,134,.3)'}}>
 <Icon name="shield-check" size={18}/> Pay securely with PayFast
 </button>
 <p style={{fontSize:11,color:'var(--ink-400)',textAlign:'center',marginTop:8}}>
 Your card details never touch Me2You's servers - they're encrypted end-to-end by PayFast.
 </p>
 </div>
 </>
 )}

 {stage === 2 && (
 <div style={{textAlign:'center',padding:40}}>
 <div style={{width:48,height:48,borderRadius:999,border:'3px solid var(--success-100)',
 borderTopColor:'var(--success)',animation:'spin 1s linear infinite',margin:'0 auto'}}/>
 <p style={{marginTop:16,color:'var(--ink-700)',fontWeight:600}}>Processing your payment...</p>
 <p style={{color:'var(--ink-500)',fontSize:13}}>Do not close this window.</p>
 </div>
 )}
 </div>
 </div>
 );
}

/* =================================================================
 8. ONBOARDING TOUR
================================================================= */
function OnboardingTour({ onComplete }) {
 const [step, setStep] = useState(0);
 const slides = [
 { 
 title:'Welcome to Me2You',
 body:"South Africa's safer C2C marketplace. Buy and sell with neighbours you can trust.",
 icon:'shield-check', color:'var(--brand-orange)'
 },
 {
 title:'Your money is safe',
 body:"We hold the buyer's payment until they confirm receipt. No more fake proof of payment.",
 icon:'wallet', color:'var(--success)'
 },
 {
 title:'Three ways to receive',
 body:"Courier to your door, collect from a pickup point, or meet in person with OTP self-collect.",
 icon:'truck', color:'var(--info)'
 },
 {
 title:'Built for South Africa',
 body:"POPIA-compliant. PayFast secure. Works on any phone, even on 3G.",
 icon:'star', color:'var(--brand-plum)'
 },
 ];
 const s = slides[step];

 return (
 <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,.6)',
 display:'flex',alignItems:'center',justifyContent:'center',padding:24}}>
 <div style={{maxWidth:440,width:'100%',background:'var(--paper)',borderRadius:'var(--radius-xl)',
 padding:32,boxShadow:'var(--shadow-lg)',animation:'pop .3s ease'}}>
 <div style={{textAlign:'center'}}>
 <div style={{width:80,height:80,borderRadius:999,margin:'0 auto 20px',
 background:`color-mix(in oklch, ${s.color} 15%, white)`,color:s.color,
 display:'flex',alignItems:'center',justifyContent:'center'}}>
 <Icon name={s.icon} size={36} stroke={1.8}/>
 </div>
 <h2 style={{margin:'0 0 12px',fontSize:24}}>{s.title}</h2>
 <p style={{color:'var(--ink-700)',fontSize:15,lineHeight:1.5,margin:0}}>{s.body}</p>
 </div>
 <div style={{display:'flex',justifyContent:'center',gap:6,margin:'24px 0'}}>
 {slides.map((_,i) => (
 <div key={i} style={{width: i === step ? 24 : 8, height:8,borderRadius:4,
 background: i === step ? 'var(--brand-orange)' : 'var(--ink-200)',transition:'all .3s'}}/>
 ))}
 </div>
 <div style={{display:'flex',gap:8}}>
 {step > 0 && <button onClick={() => setStep(step-1)} style={{...btnGhost,flex:1,justifyContent:'center'}}>Back</button>}
 {step < slides.length - 1 ? (
 <button onClick={() => setStep(step+1)} style={{...btnPrimary,flex:1,justifyContent:'center'}}>Next</button>
 ) : (
 <button onClick={onComplete} style={{...btnPrimary,flex:1,justifyContent:'center'}}>Get started</button>
 )}
 </div>
 <button onClick={onComplete} style={{background:'none',border:'none',cursor:'pointer',
 color:'var(--ink-500)',fontSize:12,marginTop:12,width:'100%',padding:8}}>Skip tour</button>
 </div>
 </div>
 );
}

/* =================================================================
 9. SELLER EARNINGS ANALYTICS CHART
================================================================= */
function EarningsChart() {
 const data = [
 { month:'Nov', amount:420 },
 { month:'Dec', amount:680 },
 { month:'Jan', amount:540 },
 { month:'Feb', amount:920 },
 { month:'Mar', amount:1240 },
 { month:'Apr', amount:1850 },
 ];
 const max = Math.max(...data.map(d => d.amount));
 return (
 <div style={panelStyle}>
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:20}}>
 <h3 style={{fontSize:16,margin:0}}>Earnings (6 months)</h3>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:24,color:'var(--success)'}}>
 R {data.reduce((s,d) => s + d.amount, 0).toLocaleString('en-ZA')}
 </div>
 </div>
 <div style={{display:'flex',alignItems:'flex-end',gap:8,height:180,paddingBottom:20,borderBottom:'1px solid var(--ink-100)'}}>
 {data.map((d,i) => (
 <div key={d.month} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:4}}>
 <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--ink-500)',fontWeight:600}}>
 R {d.amount}
 </div>
 <div style={{width:'100%',
 height: `${(d.amount / max) * 130}px`,
 background: i === data.length - 1 ? 'var(--brand-orange)' : 'var(--brand-orange-100)',
 borderRadius:'6px 6px 0 0',transition:'all .3s ease',
 boxShadow: i === data.length - 1 ? 'var(--shadow-pop)' : 'none'
 }}/>
 <div style={{fontSize:12,color:'var(--ink-500)',marginTop:4}}>{d.month}</div>
 </div>
 ))}
 </div>
 <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,marginTop:16}}>
 <div><div style={{fontSize:11,color:'var(--ink-500)'}}>Avg / month</div><div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16}}>R 942</div></div>
 <div><div style={{fontSize:11,color:'var(--ink-500)'}}>Growth</div><div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16,color:'var(--success)'}}>+49%</div></div>
 <div><div style={{fontSize:11,color:'var(--ink-500)'}}>Best month</div><div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16}}>April</div></div>
 </div>
 </div>
 );
}

/* =================================================================
 10. ADMIN AUDIT LOG
================================================================= */
const AUDIT_ENTRIES = [
 { time:'1 May 2026, 14:23', actor:'Marco P.', action:'suspended_user', target:'Bongani Tshabalala', detail:'Repeated low ratings' },
 { time:'1 May 2026, 11:08', actor:'Marco P.', action:'approved_listing', target:'iPhone 11 64GB', detail:'Pending moderation queue' },
 { time:'1 May 2026, 09:45', actor:'Marco P.', action:'resolved_dispute', target:'M2Y-2026-00232', detail:'Refunded buyer R155' },
 { time:'30 Apr 2026, 16:30', actor:'System', action:'auto_release_escrow', target:'M2Y-2026-00241', detail:'48h post-delivery' },
 { time:'30 Apr 2026, 14:12', actor:'Marco P.', action:'rejected_listing', target:'Fake Gucci bag', detail:'Counterfeit suspected' },
 { time:'30 Apr 2026, 10:00', actor:'Marco P.', action:'batch_payout', target:'5 sellers', detail:'R 3 380 total' },
];

function AdminAuditLog() {
 return (
 <div>
 <h1 style={{marginBottom:4}}>Audit log</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:20}}>Every admin action and system event, immutable.</p>
 <div style={{...panelStyle,padding:0,overflow:'hidden'}}>
 <table style={{width:'100%',borderCollapse:'collapse',fontFamily:'var(--font-body)',fontSize:13}}>
 <thead>
 <tr style={{background:'var(--ink-50)'}}>
 {['Time','Actor','Action','Target','Detail'].map(h => (
 <th key={h} style={{padding:'10px 16px',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,
 color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.06em',textAlign:'left'}}>{h}</th>
 ))}
 </tr>
 </thead>
 <tbody>
 {AUDIT_ENTRIES.map((e,i) => (
 <tr key={i} style={{borderBottom:'1px solid var(--ink-100)'}}>
 <td style={{padding:'10px 16px',fontFamily:'var(--font-mono)',fontSize:11,color:'var(--ink-500)'}}>{e.time}</td>
 <td style={{padding:'10px 16px',fontWeight:600}}>{e.actor}</td>
 <td style={{padding:'10px 16px'}}>
 <span style={{fontFamily:'var(--font-mono)',fontSize:11,padding:'3px 8px',borderRadius:6,
 background: e.actor === 'System' ? 'var(--info-100)' : 'var(--brand-orange-100)',
 color: e.actor === 'System' ? 'var(--info)' : 'var(--brand-orange-700)'}}>{e.action}</span>
 </td>
 <td style={{padding:'10px 16px'}}>{e.target}</td>
 <td style={{padding:'10px 16px',color:'var(--ink-500)',fontSize:12}}>{e.detail}</td>
 </tr>
 ))}
 </tbody>
 </table>
 </div>
 </div>
 );
}

/* =================================================================
 11. PWA INSTALL BANNER
================================================================= */
function PWAInstallBanner({ onDismiss }) {
 return (
 <div style={{position:'fixed',bottom:24,left:24,right:24,maxWidth:480,margin:'0 auto',zIndex:50,
 background:'var(--paper)',border:'1px solid var(--ink-200)',borderRadius:'var(--radius-lg)',
 padding:16,boxShadow:'var(--shadow-lg)',display:'flex',gap:12,alignItems:'center',
 animation:'pop .3s ease'}}>
 <img src="assets/logo-peace-orange.png" alt="" style={{width:40,height:40}}/>
 <div style={{flex:1}}>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:14}}>Add Me2You to your home screen</div>
 <div style={{fontSize:12,color:'var(--ink-500)'}}>Works offline. Lighter than the browser.</div>
 </div>
 <button onClick={onDismiss} style={{...btnSmall,padding:'6px 12px',fontSize:12}}>Install</button>
 <button onClick={onDismiss} style={{background:'none',border:'none',cursor:'pointer',color:'var(--ink-400)',padding:4}}>
 <Icon name="x" size={16}/>
 </button>
 </div>
 );
}

Object.assign(window, {
 NotificationBell, SearchSuggestions, BrowseFilters,
 WishlistPage, SellerStorefront, ChatList, ChatThread,
 PayFastRedirect, OnboardingTour, EarningsChart, AdminAuditLog, PWAInstallBanner,
});
