/* Me2You - Seller flow: Dashboard, Create Listing wizard */
/* global React, Icon, StatusTag, Price, Field, panelStyle, btnPrimary, btnGhost, btnSmall, PRODUCTS, SAMPLE_ORDERS */

const { useState } = React;

const SELLER_LISTINGS = [
 { id:1, title:'Hisense 32" Smart TV', price:1850, status:'live', views:342, orders:3, emoji:'', bg:'linear-gradient(135deg,#FFE7C8,#FFF6E9)' },
 { id:2, title:'Nike Air Max - UK 9', price:1200, status:'live', views:128, orders:1, emoji:'', bg:'linear-gradient(135deg,#DDF1E4,#FFF6E9)' },
 { id:3, title:'Defy Microwave 20L', price:850, status:'pending', views:0, orders:0, emoji:'', bg:'linear-gradient(135deg,#ECE6F2,#FFF6E9)' },
];

const SELLER_ORDERS = [
 { id:'M2Y-2026-00248', item:'Hisense 32" Smart TV', buyer:'Nomsa M.', status:'paid', total:1910, date:'28 Apr 2026' },
 { id:'M2Y-2026-00245', item:'Cast-iron pot, 4L', buyer:'Thandi K.', status:'dispatched', total:440, date:'26 Apr 2026' },
 { id:'M2Y-2026-00241', item:'Samsung Galaxy A14', buyer:'James R.', status:'completed', total:1460, date:'22 Apr 2026' },
];

function SellerDashboard({ onCreateListing, onNav }) {
 const [tab, setTab] = useState('overview');
 const [onVacation, setOnVacation] = useState(false);
 const [awayFrom, setAwayFrom] = useState('26 May 2026');
 const [backOn, setBackOn] = useState('3 Jun 2026');
 const [vacationMsg, setVacationMsg] = useState('Away at a family event. Watching the shop, will reply on 3 June. Thanks for your patience.');
 const [savedSettings, setSavedSettings] = useState(false);
 const stats = [
 { label:'Revenue (30d)', value:'R 3 810', icon:'wallet' },
 { label:'Active listings', value:'2', icon:'package' },
 { label:'Orders (30d)', value:'5', icon:'receipt' },
 { label:'Rating', value:'4.8 ', icon:'star' },
 ];

 return (
 <div>
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:24}}>
 <div>
 <h1 style={{margin:0}}>Seller dashboard</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,margin:'4px 0 0'}}>Welcome back, Thandi Q.</p>
 </div>
 <button onClick={onCreateListing} style={btnPrimary}>
 <Icon name="plus" size={18}/> List something
 </button>
 </div>

 <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:24}}>
 {stats.map(s => (
 <div key={s.label} style={{...panelStyle,padding:16,marginBottom:0}}>
 <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:8}}>
 <div style={{width:36,height:36,borderRadius:10,background:'var(--brand-orange-50)',
 display:'flex',alignItems:'center',justifyContent:'center',color:'var(--brand-orange-700)'}}>
 <Icon name={s.icon} size={18}/>
 </div>
 <span style={{fontFamily:'var(--font-body)',fontSize:12,color:'var(--ink-500)',fontWeight:600}}>{s.label}</span>
 </div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:24}}>{s.value}</div>
 </div>
 ))}
 </div>

 <div style={{display:'flex',gap:4,marginBottom:20,borderBottom:'1.5px solid var(--ink-200)'}}>
 {['overview','listings','orders','settings'].map(t => (
 <button key={t} onClick={() => setTab(t)} style={{
 padding:'10px 18px',fontFamily:'var(--font-body)',fontWeight:600,fontSize:14,
 background:'none',border:'none',cursor:'pointer',
 color: tab===t ? 'var(--ink-900)' : 'var(--ink-400)',
 borderBottom: tab===t ? '2.5px solid var(--brand-orange)' : '2.5px solid transparent',
 marginBottom:-1.5,transition:'all .15s'
 }}>{t.charAt(0).toUpperCase()+t.slice(1)}</button>
 ))}
 </div>

 {tab === 'overview' && (
 <div>
 <EarningsChart/>
 <h3 style={{fontSize:18,marginBottom:12,marginTop:24}}>Recent orders</h3>
 {SELLER_ORDERS.map(o => (
 <div key={o.id} style={{...panelStyle,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
 <div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:15}}>{o.item}</div>
 <div style={{fontFamily:'var(--font-mono)',fontSize:11,color:'var(--ink-500)'}}>
 {o.id} - {o.buyer} - {o.date}
 </div>
 </div>
 <div style={{display:'flex',alignItems:'center',gap:12}}>
 <StatusTag status={o.status}/>
 <Price amount={o.total} size="sm"/>
 </div>
 </div>
 ))}
 </div>
 )}

 {tab === 'listings' && (
 <div>
 {onVacation && (
 <div style={{...panelStyle,background:'var(--warning-100)',borderColor:'var(--warning)',display:'flex',gap:10,alignItems:'start'}}>
 <Icon name="umbrella" size={18} stroke={2}/>
 <div style={{fontSize:13,color:'var(--ink-700)'}}>
 <strong style={{display:'block',fontFamily:'var(--font-display)',fontSize:14}}>Vacation mode is on</strong>
 New orders are paused until <strong>{backOn}</strong>. Every listing below shows a "Back soon" badge to buyers.
 </div>
 </div>
 )}
 {SELLER_LISTINGS.map(l => (
 <div key={l.id} style={{...panelStyle,display:'grid',gridTemplateColumns:'56px 1fr auto auto auto',gap:16,alignItems:'center'}}>
 <div style={{width:56,height:56,borderRadius:12,backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center'}}/>
 <div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:15}}>{l.title}</div>
 <Price amount={l.price} size="sm"/>
 {onVacation && (
 <span style={{display:'inline-block',marginTop:4,fontFamily:'var(--font-body)',fontWeight:700,fontSize:10,
 letterSpacing:'.05em',textTransform:'uppercase',padding:'3px 8px',borderRadius:999,
 background:'var(--warning-100)',color:'var(--warning)'}}>Back {backOn}</span>
 )}
 </div>
 <StatusTag status={l.status}/>
 <div style={{textAlign:'center'}}>
 <div style={{fontFamily:'var(--font-mono)',fontSize:18,fontWeight:600}}>{l.views}</div>
 <div style={{fontSize:11,color:'var(--ink-500)'}}>views</div>
 </div>
 <div style={{display:'flex',gap:6}}>
 <button style={{...btnSmall,padding:'6px 10px'}}><Icon name="edit" size={14}/></button>
 <button style={{...btnSmall,padding:'6px 10px',color:'var(--danger)',borderColor:'var(--danger)'}}><Icon name="trash" size={14}/></button>
 </div>
 </div>
 ))}
 </div>
 )}

 {tab === 'orders' && (
 <div>
 <div style={{...panelStyle,padding:0,overflow:'hidden'}}>
 <table style={{width:'100%',borderCollapse:'collapse',fontFamily:'var(--font-body)',fontSize:14}}>
 <thead>
 <tr style={{background:'var(--ink-50)',textAlign:'left'}}>
 <th style={thStyle}>Reference</th><th style={thStyle}>Item</th><th style={thStyle}>Buyer</th>
 <th style={thStyle}>Status</th><th style={{...thStyle,textAlign:'right'}}>Total</th>
 </tr>
 </thead>
 <tbody>
 {SELLER_ORDERS.map(o => (
 <tr key={o.id} style={{borderBottom:'1px solid var(--ink-100)'}}>
 <td style={tdStyle}><span style={{fontFamily:'var(--font-mono)',fontSize:12,fontWeight:600}}>{o.id}</span></td>
 <td style={tdStyle}>{o.item}</td>
 <td style={tdStyle}>{o.buyer}</td>
 <td style={tdStyle}><StatusTag status={o.status}/></td>
 <td style={{...tdStyle,textAlign:'right'}}><Price amount={o.total} size="sm"/></td>
 </tr>
 ))}
 </tbody>
 </table>
 </div>
 </div>
 )}

 {tab === 'settings' && (
 <div style={{maxWidth:560}}>
 <h3 style={{fontSize:16,margin:'0 0 4px'}}>Availability</h3>
 <p style={{color:'var(--ink-500)',fontSize:13,margin:'0 0 16px'}}>Pause new orders while you are away. Buyers still see your shop, marked as "Back soon".</p>

 <div style={{...panelStyle,background:'var(--brand-orange-50)',borderColor:'var(--brand-orange-100)',
 display:'grid',gridTemplateColumns:'1fr auto',gap:12,alignItems:'center'}}>
 <div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:15}}>Vacation mode</div>
 <div style={{fontSize:12,color:'var(--ink-700)',marginTop:2}}>Pause new orders. Buyers still see listings, marked as "Back soon".</div>
 </div>
 <button onClick={() => { setOnVacation(v => !v); setSavedSettings(false); }} aria-pressed={onVacation}
 aria-label="Toggle vacation mode"
 style={{width:52,height:30,borderRadius:999,border:'1.5px solid var(--ink-200)',cursor:'pointer',
 background: onVacation ? 'var(--brand-orange)' : 'var(--ink-200)',position:'relative',transition:'background .2s',flexShrink:0}}>
 <span style={{position:'absolute',top:2,left: onVacation ? 24 : 2,width:22,height:22,borderRadius:'50%',
 background:'#fff',transition:'left .2s',boxShadow:'var(--shadow-sm)'}}/>
 </button>
 </div>

 {onVacation && (
 <>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:16}}>
 <Field label="Away from" value={awayFrom} icon="calendar" onChange={e => setAwayFrom(e.target.value)}/>
 <Field label="Back on" value={backOn} icon="calendar" onChange={e => setBackOn(e.target.value)}/>
 </div>
 <div style={{marginBottom:16}}>
 <label style={{display:'block',fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,color:'var(--ink-700)',marginBottom:8}}>Message buyers will see</label>
 <textarea rows={3} defaultValue={vacationMsg} onChange={e => setVacationMsg(e.target.value)}
 style={{width:'100%',padding:14,border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',
 fontFamily:'var(--font-body)',fontSize:15,boxSizing:'border-box',resize:'vertical'}}/>
 </div>
 <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="shield-check" size={16} stroke={2}/>
 <span>Buyers still see your shop. Lay-bye plans already running keep going as normal.</span>
 </div>
 </>
 )}

 <button onClick={() => setSavedSettings(true)} style={{...btnPrimary,marginTop:4}}>
 <Icon name="check" size={18}/> Save settings
 </button>
 {savedSettings && (
 <div style={{marginTop:12,fontSize:13,color:'var(--success)',fontWeight:600,display:'flex',alignItems:'center',gap:6}}>
 <Icon name="check-circle" size={16}/> Saved. {onVacation ? `Your shop shows "Back ${backOn}".` : 'Vacation mode is off.'}
 </div>
 )}
 </div>
 )}
 </div>
 );
}

/* --- Create Listing --- */
function CreateListing({ onBack, onPublish }) {
 const [step, setStep] = useState(1);
 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:4}}>Sell something</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:24}}>Takes about 4 minutes. New listings go to moderation; live within 1 business day.</p>

 <div style={{display:'flex',gap:8,marginBottom:24}}>
 {['Details','Photos','Review'].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,
 transition:'all .2s'}}>{i+1}</div>
 <div style={{fontSize:12,fontWeight:600,color: i+1 <= step ? 'var(--ink-900)' : 'var(--ink-400)'}}>{s}</div>
 </div>
 ))}
 </div>

 {step === 1 && (
 <div style={panelStyle}>
 <Field label="Title" placeholder="e.g. iPhone 11 64GB - Black" full/>
 <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginTop:12}}>
 <div>
 <label style={{display:'block',fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,color:'var(--ink-700)',marginBottom:8}}>Category</label>
 <select style={{width:'100%',padding:'13px 14px',border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',fontFamily:'var(--font-body)',fontSize:15,background:'var(--paper)'}}>
 <option>Choose...</option>
 <option>Electronics</option><option>Clothing</option><option>Home & Garden</option>
 <option>Books</option><option>Food & Produce</option><option>Tools</option>
 </select>
 </div>
 <div>
 <label style={{display:'block',fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,color:'var(--ink-700)',marginBottom:8}}>Condition</label>
 <select style={{width:'100%',padding:'13px 14px',border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',fontFamily:'var(--font-body)',fontSize:15,background:'var(--paper)'}}>
 <option>New</option><option>Like new</option><option selected>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={{display:'block',fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,color:'var(--ink-700)',marginBottom:8}}>Description</label>
 <textarea rows={4} placeholder="What's the condition? Any quirks? Why selling?" style={{width:'100%',padding:14,border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',fontFamily:'var(--font-body)',fontSize:15,boxSizing:'border-box',resize:'vertical'}}/>
 </div>
 <button onClick={() => setStep(2)} style={{...btnPrimary,marginTop:16}}>Next: Photos</button>
 </div>
 )}

 {step === 2 && (
 <div style={panelStyle}>
 <ImageUploader/>
 <div style={{display:'flex',gap:12,marginTop:16}}>
 <button onClick={() => setStep(1)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(3)} style={btnPrimary}>Next: Review</button>
 </div>
 </div>
 )}

 {step === 3 && (
 <div style={panelStyle}>
 <h3 style={{margin:'0 0 12px',fontSize:18}}>Ready to publish?</h3>
 <p style={{color:'var(--ink-500)',fontSize:14}}>Your listing will go to moderation and be live within 1 business day. You'll get a shareable WhatsApp link once approved.</p>
 <div style={{display:'flex',gap:12,marginTop:16}}>
 <button onClick={() => setStep(2)} style={btnGhost}>Back</button>
 <button onClick={onPublish} style={btnPrimary}>
 <Icon name="check" size={18}/> Publish for moderation
 </button>
 </div>
 </div>
 )}
 </div>
 );
}

const thStyle = { padding:'10px 16px',fontFamily:'var(--font-mono)',fontSize:11,fontWeight:600,color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.06em' };
const tdStyle = { padding:'12px 16px' };

/* --- Image Uploader --- */
function ImageUploader() {
 const [files, setFiles] = useState([]);
 const inputRef = useRef(null);

 const handleFiles = (selected) => {
 const arr = Array.from(selected).slice(0, 6 - files.length);
 const promises = arr.map(f => new Promise(res => {
 const r = new FileReader();
 r.onload = () => res({ name: f.name, size: f.size, url: r.result });
 r.readAsDataURL(f);
 }));
 Promise.all(promises).then(loaded => setFiles(prev => [...prev, ...loaded].slice(0,6)));
 };

 const removeFile = (idx) => setFiles(prev => prev.filter((_,i) => i !== idx));

 return (
 <div>
 <input ref={inputRef} type="file" accept="image/jpeg,image/png,image/webp" multiple
 onChange={e => handleFiles(e.target.files)} style={{display:'none'}}/>

 {files.length === 0 ? (
 <div onClick={() => inputRef.current?.click()}
 onDragOver={e => { e.preventDefault(); e.currentTarget.style.background='var(--brand-orange-100)'; }}
 onDragLeave={e => e.currentTarget.style.background='transparent'}
 onDrop={e => { e.preventDefault(); e.currentTarget.style.background='transparent'; handleFiles(e.dataTransfer.files); }}
 style={{border:'1.5px dashed var(--brand-orange)',borderRadius:'var(--radius-lg)',padding:48,textAlign:'center',
 background:'repeating-linear-gradient(45deg,var(--brand-orange-50),var(--brand-orange-50) 8px,transparent 8px,transparent 16px)',
 color:'var(--brand-orange-700)',cursor:'pointer',transition:'background .15s'}}>
 <Icon name="camera" size={36}/>
 <div style={{fontFamily:'var(--font-body)',fontWeight:700,fontSize:15,marginTop:12}}>Tap to upload photos</div>
 <div style={{fontFamily:'var(--font-mono)',fontSize:11,color:'var(--ink-500)',marginTop:4}}>
 or drag &amp; drop - JPG - PNG - WebP - up to 6 images - max 2 MB each
 </div>
 </div>
 ) : (
 <div>
 <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8}}>
 {files.map((f,i) => (
 <div key={i} style={{position:'relative',aspectRatio:1,borderRadius:12,overflow:'hidden',
 background:'var(--ink-100)',border:'1px solid var(--ink-200)'}}>
 <img src={f.url} alt={f.name} style={{width:'100%',height:'100%',objectFit:'cover'}}/>
 {i === 0 && (
 <span style={{position:'absolute',top:6,left:6,background:'var(--brand-orange)',color:'white',
 fontSize:9,fontWeight:800,padding:'3px 7px',borderRadius:999,letterSpacing:'.06em'}}>COVER</span>
 )}
 <button onClick={() => removeFile(i)} style={{position:'absolute',top:6,right:6,
 width:24,height:24,borderRadius:999,background:'rgba(0,0,0,.6)',color:'white',border:'none',
 cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center'}}>
 <Icon name="x" size={12} stroke={2.5}/>
 </button>
 <div style={{position:'absolute',bottom:0,left:0,right:0,background:'rgba(0,0,0,.6)',color:'white',
 padding:'4px 8px',fontSize:10,fontFamily:'var(--font-mono)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
 {(f.size/1024).toFixed(0)} KB
 </div>
 </div>
 ))}
 {files.length < 6 && (
 <button onClick={() => inputRef.current?.click()} style={{aspectRatio:1,borderRadius:12,
 border:'1.5px dashed var(--ink-300)',background:'var(--ink-50)',cursor:'pointer',
 display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',
 color:'var(--ink-500)',fontFamily:'var(--font-body)',fontSize:11,fontWeight:600,gap:4}}>
 <Icon name="plus" size={20}/> Add more
 </button>
 )}
 </div>
 <div style={{fontSize:12,color:'var(--ink-500)',marginTop:8,display:'flex',alignItems:'center',gap:6}}>
 <Icon name="image" size={14}/> {files.length} of 6 photos - first photo is the cover
 </div>
 </div>
 )}
 </div>
 );
}

Object.assign(window, { SellerDashboard, CreateListing });
