/* Me2You - Unified Sell Wizard for items, property, vehicles + Recently Viewed */
/* global React, Icon, Field, panelStyle, btnPrimary, btnGhost, btnSmall, ImageUploader, Price, CATEGORIES, LeafletMap */

const { useState } = React;

function UnifiedSellWizard({ onBack, onPublish }) {
 const [kind, setKind] = useState(null);
 const [step, setStep] = useState(0);

 if (!kind) return (
 <div style={{maxWidth:680,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 dashboard
 </button>
 <h1 style={{marginBottom:8}}>What are you listing?</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:24}}>Pick the type of listing so we collect the right details.</p>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:12}}>
 {[
 { key:'item', label:'Item', desc:'Anything you can ship: electronics, clothes, food, crafts.', icon:'package' },
 { key:'property', label:'Property', desc:'Rooms, apartments, houses to rent or sell.', icon:'home' },
 { key:'vehicle', label:'Vehicle', desc:'Cars, bikes, scooters. NaTIS verification required.', icon:'truck' },
 ].map(o => (
 <button key={o.key} onClick={() => { setKind(o.key); setStep(1); }} style={{
 padding:24,borderRadius:'var(--radius-lg)',cursor:'pointer',textAlign:'left',
 border:'1.5px solid var(--ink-200)',background:'var(--paper)',
 display:'flex',flexDirection:'column',gap:10,transition:'all .15s'
 }}
 onMouseEnter={e => { e.currentTarget.style.borderColor='var(--brand-orange)'; e.currentTarget.style.background='var(--brand-orange-50)'; }}
 onMouseLeave={e => { e.currentTarget.style.borderColor='var(--ink-200)'; e.currentTarget.style.background='var(--paper)'; }}>
 <div style={{width:48,height:48,borderRadius:12,background:'var(--brand-orange-100)',color:'var(--brand-orange-700)',display:'flex',alignItems:'center',justifyContent:'center'}}>
 <Icon name={o.icon} size={24}/>
 </div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:18}}>{o.label}</div>
 <div style={{fontSize:13,color:'var(--ink-500)',lineHeight:1.4}}>{o.desc}</div>
 </button>
 ))}
 </div>
 </div>
 );

 return (
 <div style={{maxWidth:680,margin:'0 auto'}}>
 <button onClick={() => { setKind(null); setStep(0); }} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Change listing type
 </button>
 {kind === 'item' && <ItemForm step={step} setStep={setStep} onPublish={onPublish}/>}
 {kind === 'property' && <PropertyForm step={step} setStep={setStep} onPublish={onPublish}/>}
 {kind === 'vehicle' && <VehicleForm step={step} setStep={setStep} onPublish={onPublish}/>}
 </div>
 );
}

function StepHeader({ step, steps }) {
 return (
 <div style={{display:'flex',gap:8,marginBottom:24}}>
 {steps.map((s,i) => (
 <div key={s} style={{flex:1,textAlign:'center'}}>
 <div style={{width:32,height:32,borderRadius:999,margin:'0 auto 6px',
 background: i+1 <= step ? 'var(--brand-orange)' : 'var(--ink-100)',
 color: i+1 <= step ? 'white' : 'var(--ink-400)',
 display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',fontWeight:700,fontSize:13}}>{i+1}</div>
 <div style={{fontSize:12,fontWeight:600,color: i+1 <= step ? 'var(--ink-900)' : 'var(--ink-400)'}}>{s}</div>
 </div>
 ))}
 </div>
 );
}

function ItemForm({ step, setStep, onPublish }) {
 return (
 <>
 <h1 style={{marginBottom:4}}>List an item</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:24}}>Takes 3-4 minutes.</p>
 <StepHeader step={step} steps={['Details','Photos','Review']}/>
 {step === 1 && (
 <div style={panelStyle}>
 <Field label="Title" placeholder="e.g. iPhone 11 64GB" full/>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginTop:12}}>
 <div><label style={lbl}>Category</label><select style={inp}><option>Choose...</option>{(window.CATEGORIES||[]).slice(1).map(c => <option key={c.slug}>{c.name}</option>)}</select></div>
 <div><label style={lbl}>Condition</label><select style={inp}><option>New</option><option>Like new</option><option>Good</option><option>Fair</option></select></div>
 </div>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginTop:12}}>
 <Field label="Price (R)" placeholder="250" type="number"/>
 <Field label="Weight (kg)" value="1.0" type="number"/>
 </div>
 <div style={{marginTop:12}}>
 <label style={lbl}>Description</label>
 <textarea rows={4} placeholder="Condition, included accessories, why selling..." style={{...inp,resize:'vertical'}}/>
 </div>
 <button onClick={() => setStep(2)} style={{...btnPrimary,marginTop:16}}>Next: Photos</button>
 </div>
 )}
 {step === 2 && <PhotosStep onBack={() => setStep(1)} onNext={() => setStep(3)}/>}
 {step === 3 && <ReviewStep label="item" onBack={() => setStep(2)} onPublish={onPublish}/>}
 </>
 );
}

function PropertyForm({ step, setStep, onPublish }) {
 const [intent, setIntent] = useState('rent');
 return (
 <>
 <h1 style={{marginBottom:4}}>List a property</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:24}}>Direct C2C. No agent commission. Verification required before going live.</p>
 <StepHeader step={step} steps={['Type','Details','Photos','Verify','Review']}/>

 {step === 1 && (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 12px'}}>What are you offering?</h3>
 <div style={{display:'flex',gap:8,marginBottom:16}}>
 {[{k:'rent',l:'To rent'},{k:'sell',l:'To sell'},{k:'share',l:'Room to share'}].map(o => (
 <button key={o.k} onClick={() => setIntent(o.k)} style={{
 flex:1,padding:14,borderRadius:'var(--radius-md)',cursor:'pointer',
 border: intent===o.k ? '2px solid var(--brand-orange)' : '1.5px solid var(--ink-200)',
 background: intent===o.k ? 'var(--brand-orange-50)' : 'var(--paper)',fontWeight:700,fontSize:14
 }}>{o.l}</button>
 ))}
 </div>
 <Field label="Listing title" placeholder="e.g. 2-bed apartment in Sandton" full/>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginTop:12}}>
 <div><label style={lbl}>Property type</label><select style={inp}><option>Apartment</option><option>House</option><option>Room</option><option>Townhouse</option><option>Bachelor flat</option><option>Garden cottage</option><option>Student commune</option></select></div>
 <div><label style={lbl}>Furnished</label><select style={inp}><option>Furnished</option><option>Semi-furnished</option><option>Unfurnished</option></select></div>
 </div>
 <button onClick={() => setStep(2)} style={{...btnPrimary,marginTop:16}}>Next</button>
 </div>
 )}

 {step === 2 && (
 <div style={panelStyle}>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
 <Field label={intent === 'sell' ? 'Asking price (R)' : 'Monthly rent (R)'} placeholder={intent === 'sell' ? '780000' : '6500'} type="number"/>
 {intent !== 'sell' && <Field label="Deposit (R)" placeholder="6500" type="number"/>}
 <div><label style={lbl}>Bedrooms</label><select style={inp}><option>Bachelor</option><option>1</option><option>2</option><option>3</option><option>4+</option></select></div>
 <div><label style={lbl}>Bathrooms</label><select style={inp}><option>1</option><option>2</option><option>3+</option></select></div>
 <Field label="Floor area (m2)" placeholder="78"/>
 <Field label="Available from" placeholder="1 June 2026"/>
 </div>
 <div style={{marginTop:12}}>
 <Field label="Address" placeholder="14 Vilakazi St, Soweto" full icon="map-pin"/>
 </div>
 <div style={{marginTop:12,display:'flex',gap:12,flexWrap:'wrap'}}>
 {['Pets allowed','Secure parking','Prepaid utilities','Pool / gym','Student-friendly','Near transport'].map(t => (
 <label key={t} style={{display:'flex',alignItems:'center',gap:6,fontSize:13,cursor:'pointer'}}>
 <input type="checkbox" style={{accentColor:'var(--brand-orange)'}}/>{t}
 </label>
 ))}
 </div>
 <div style={{marginTop:12}}>
 <label style={lbl}>Description</label>
 <textarea rows={4} placeholder="Highlights, neighbourhood, transport links, what's included..." style={{...inp,resize:'vertical'}}/>
 </div>
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={() => setStep(1)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(3)} style={btnPrimary}>Next: Photos</button>
 </div>
 </div>
 )}

 {step === 3 && <PhotosStep onBack={() => setStep(2)} onNext={() => setStep(4)} max={10}/>}

 {step === 4 && (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 8px'}}>Verify ownership</h3>
 <p style={{fontSize:13,color:'var(--ink-500)',margin:'0 0 16px'}}>
 Property listings are reviewed before going live. Documents are encrypted and never shown to buyers.
 </p>
 {['Title deed or signed mandate to let','Latest municipal rates statement','Proof of address (Eskom or water bill)'].map((d,i) => (
 <div key={i} style={{display:'flex',alignItems:'center',gap:12,padding:12,border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-md)',marginBottom:8}}>
 <div style={{width:36,height:36,borderRadius:8,background:'var(--ink-100)',display:'flex',alignItems:'center',justifyContent:'center'}}><Icon name="image" size={18}/></div>
 <div style={{flex:1,fontSize:13,fontWeight:700}}>{d}</div>
 <button style={{...btnSmall,fontSize:12}}>Upload</button>
 </div>
 ))}
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={() => setStep(3)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(5)} style={btnPrimary}>Next: Review</button>
 </div>
 </div>
 )}

 {step === 5 && <ReviewStep label="property" onBack={() => setStep(4)} onPublish={onPublish}/>}
 </>
 );
}

function VehicleForm({ step, setStep, onPublish }) {
 return (
 <>
 <h1 style={{marginBottom:4}}>List a vehicle</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:24}}>Direct C2C. No dealer commission. NaTIS verification required.</p>
 <StepHeader step={step} steps={['Type','Specs','Photos','NaTIS','Review']}/>

 {step === 1 && (
 <div style={panelStyle}>
 <div style={{display:'flex',gap:8,marginBottom:16}}>
 {['Car','Bike','Scooter','Bakkie','Truck'].map(t => (
 <button key={t} style={{flex:1,padding:'12px 14px',borderRadius:'var(--radius-md)',
 border:'1.5px solid var(--ink-200)',background:'var(--paper)',cursor:'pointer',fontWeight:700,fontSize:13}}>{t}</button>
 ))}
 </div>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
 <Field label="Make" placeholder="Toyota"/>
 <Field label="Model" placeholder="Etios 1.5 Xs"/>
 <Field label="Year" placeholder="2018" type="number"/>
 <Field label="VIN / chassis number" placeholder="VF1RFA00565...."/>
 </div>
 <button onClick={() => setStep(2)} style={{...btnPrimary,marginTop:16}}>Next</button>
 </div>
 )}

 {step === 2 && (
 <div style={panelStyle}>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
 <Field label="Asking price (R)" placeholder="128000" type="number"/>
 <Field label="Mileage (km)" placeholder="78500" type="number"/>
 <div><label style={lbl}>Fuel</label><select style={inp}><option>Petrol</option><option>Diesel</option><option>Hybrid</option><option>Electric</option></select></div>
 <div><label style={lbl}>Transmission</label><select style={inp}><option>Manual</option><option>Automatic</option><option>Semi-auto</option></select></div>
 <Field label="Body colour" placeholder="Silver"/>
 <Field label="Location" placeholder="Soweto" icon="map-pin"/>
 </div>
 <div style={{marginTop:12,display:'flex',gap:12,flexWrap:'wrap'}}>
 {['Full service history','One owner','Tow bar','Cruise control','Aircon','Bluetooth','Reverse camera','New tyres'].map(t => (
 <label key={t} style={{display:'flex',alignItems:'center',gap:6,fontSize:13,cursor:'pointer'}}>
 <input type="checkbox" style={{accentColor:'var(--brand-orange)'}}/>{t}
 </label>
 ))}
 </div>
 <div style={{marginTop:12}}>
 <label style={lbl}>Description</label>
 <textarea rows={4} placeholder="Service history, mods, reason for selling..." style={{...inp,resize:'vertical'}}/>
 </div>
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={() => setStep(1)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(3)} style={btnPrimary}>Next: Photos</button>
 </div>
 </div>
 )}

 {step === 3 && <PhotosStep onBack={() => setStep(2)} onNext={() => setStep(4)} max={12}/>}

 {step === 4 && (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 8px'}}>Verify ownership</h3>
 <p style={{fontSize:13,color:'var(--ink-500)',margin:'0 0 16px'}}>Photo evidence of the car papers. Encrypted, reviewed by admins, never shown publicly.</p>
 {['NaTIS registration certificate (eNaTIS RC1)','Latest licence disc photo','Proof of insurance (optional)'].map((d,i) => (
 <div key={i} style={{display:'flex',alignItems:'center',gap:12,padding:12,border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-md)',marginBottom:8}}>
 <div style={{width:36,height:36,borderRadius:8,background:'var(--ink-100)',display:'flex',alignItems:'center',justifyContent:'center'}}><Icon name="image" size={18}/></div>
 <div style={{flex:1,fontSize:13,fontWeight:700}}>{d}</div>
 <button style={{...btnSmall,fontSize:12}}>Upload</button>
 </div>
 ))}
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={() => setStep(3)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(5)} style={btnPrimary}>Next: Review</button>
 </div>
 </div>
 )}

 {step === 5 && <ReviewStep label="vehicle" onBack={() => setStep(4)} onPublish={onPublish}/>}
 </>
 );
}

function PhotosStep({ onBack, onNext, max = 6 }) {
 return (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 8px'}}>Photos</h3>
 <p style={{fontSize:13,color:'var(--ink-500)',margin:'0 0 12px'}}>Up to {max} photos. First is the cover.</p>
 {window.ImageUploader ? <ImageUploader/> : <div style={{padding:40,border:'1.5px dashed var(--brand-orange)',borderRadius:'var(--radius-md)',textAlign:'center',color:'var(--brand-orange-700)'}}><Icon name="camera" size={32}/><div style={{marginTop:8,fontWeight:700}}>Tap to upload</div></div>}
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={onBack} style={btnGhost}>Back</button>
 <button onClick={onNext} style={btnPrimary}>Next</button>
 </div>
 </div>
 );
}

function ReviewStep({ label, onBack, onPublish }) {
 return (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 8px'}}>Ready to publish?</h3>
 <p style={{fontSize:14,color:'var(--ink-500)'}}>Your {label} listing goes to moderation and is live within 1 business day. You'll get a shareable WhatsApp link once approved.</p>
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={onBack} style={btnGhost}>Back</button>
 <button onClick={onPublish} style={btnPrimary}><Icon name="check" size={16}/> Publish for moderation</button>
 </div>
 </div>
 );
}

const lbl = {display:'block',fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,color:'var(--ink-700)',marginBottom:8};
const inp = {width:'100%',padding:'13px 14px',border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',fontFamily:'var(--font-body)',fontSize:15,boxSizing:'border-box',background:'var(--paper)'};

/* --- Recently Viewed --- */
function RecentlyViewed({ items = [], onSelect }) {
 if (!items.length) return null;
 return (
 <section style={{marginTop:24}}>
 <h2 style={{fontSize:18,marginBottom:12}}>Recently viewed</h2>
 <div style={{display:'flex',gap:12,overflow:'auto',padding:'4px 0 8px'}}>
 {items.slice(0,8).map(p => (
 <div key={p.id} onClick={() => onSelect && onSelect(p)} style={{
 minWidth:160,maxWidth:160,padding:8,borderRadius:'var(--radius-md)',background:'var(--paper)',
 border:'1px solid var(--ink-200)',cursor:'pointer',transition:'box-shadow .15s'
 }}
 onMouseEnter={e => e.currentTarget.style.boxShadow='var(--shadow-md)'}
 onMouseLeave={e => e.currentTarget.style.boxShadow='none'}>
 <div style={{aspectRatio:1,borderRadius:8,backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center'}}/>
 <div style={{fontSize:12,fontWeight:600,marginTop:6,lineHeight:1.3,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.title}</div>
 <div style={{fontSize:11,color:'var(--brand-orange-700)',fontWeight:700,marginTop:2}}>R {(p.price || p.monthly || 0).toLocaleString('en-ZA')}{p.monthly ? '/mo' : ''}</div>
 </div>
 ))}
 </div>
 </section>
 );
}

Object.assign(window, { UnifiedSellWizard, RecentlyViewed });
