/* Me2You - Trust & Verification: Verified badge, ID verify, proof of ownership, safe meet-ups, report/block, 2FA */
/* global React, Icon, panelStyle, btnPrimary, btnGhost, btnSmall, btnDanger, LeafletMap, CITY_COORDS */

const { useState } = React;

/* --- Verified Badge --- */
function VerifiedBadge({ level = 'verified', size = 14 }) {
 const map = {
 verified: { color:'var(--info)', label:'ID verified', icon:'shield-check' },
 trusted:  { color:'var(--success)', label:'Trusted seller', icon:'check-circle' },
 pro:      { color:'var(--brand-orange)', label:'Pro seller', icon:'star' },
 };
 const c = map[level] || map.verified;
 return (
 <span title={c.label} style={{display:'inline-flex',alignItems:'center',gap:4,padding:'2px 8px',
 borderRadius:999,background:`color-mix(in oklch, ${c.color} 15%, white)`,color:c.color,
 fontFamily:'var(--font-body)',fontWeight:700,fontSize:10,letterSpacing:'.04em',textTransform:'uppercase'}}>
 <Icon name={c.icon} size={size-2} stroke={2.5}/> {c.label}
 </span>
 );
}

/* --- ID Verification Wizard (FICA-style) --- */
function IDVerifyWizard({ onComplete, onBack }) {
 const [step, setStep] = useState(1);
 const [idType, setIdType] = useState('za_id');
 const [idNumber, setIdNumber] = useState('');
 const [docFront, setDocFront] = useState(null);
 const [selfie, setSelfie] = useState(null);
 const frontRef = React.useRef(null);
 const selfieRef = React.useRef(null);

 const readFile = (file, set) => {
 const r = new FileReader();
 r.onload = () => set(r.result);
 r.readAsDataURL(file);
 };

 return (
 <div style={{maxWidth:520,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
 </button>
 <h1 style={{marginBottom:8}}>Verify your identity</h1>
 <p style={{color:'var(--ink-500)',fontSize:14,marginBottom:24}}>
 Verified sellers get a badge, list vehicles and property, and earn buyer trust. Takes about 3 minutes.
 </p>

 <div style={{display:'flex',gap:8,marginBottom:24}}>
 {['Document','Photos','Selfie','Done'].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:11,fontWeight:600,color: i+1 <= step ? 'var(--ink-900)' : 'var(--ink-400)'}}>{s}</div>
 </div>
 ))}
 </div>

 {step === 1 && (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 12px'}}>What document will you use?</h3>
 {[
 {key:'za_id', label:'South African ID book / smart card', desc:'13-digit ID number'},
 {key:'passport', label:'Passport', desc:'For SA residents and visitors'},
 {key:'drivers', label:"Driver's licence", desc:'Card with photo and 13-digit ID'},
 ].map(opt => (
 <div key={opt.key} onClick={() => setIdType(opt.key)} style={{
 padding:14,borderRadius:'var(--radius-md)',cursor:'pointer',marginBottom:8,
 border: idType===opt.key ? '2px solid var(--brand-orange)' : '1.5px solid var(--ink-200)',
 background: idType===opt.key ? 'var(--brand-orange-50)' : 'transparent',
 }}>
 <div style={{fontWeight:700,fontSize:14}}>{opt.label}</div>
 <div style={{fontSize:12,color:'var(--ink-500)',marginTop:2}}>{opt.desc}</div>
 </div>
 ))}
 <div style={{marginTop:12}}>
 <label style={{display:'block',fontSize:13,fontWeight:700,marginBottom:6}}>ID number</label>
 <input value={idNumber} onChange={e => setIdNumber(e.target.value)}
 placeholder="9001011234086" maxLength={13}
 style={{width:'100%',padding:'13px 14px',border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',
 fontFamily:'var(--font-mono)',fontSize:15,boxSizing:'border-box'}}/>
 </div>
 <button onClick={() => setStep(2)} disabled={idNumber.length < 6}
 style={{...btnPrimary,marginTop:16,opacity: idNumber.length < 6 ? 0.5 : 1}}>Next</button>
 </div>
 )}

 {step === 2 && (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 12px'}}>Photo of your document</h3>
 <input ref={frontRef} type="file" accept="image/*" capture="environment"
 onChange={e => e.target.files[0] && readFile(e.target.files[0], setDocFront)} style={{display:'none'}}/>
 <div onClick={() => frontRef.current?.click()} style={{
 border: docFront ? '2px solid var(--success)' : '2px dashed var(--brand-orange)',
 borderRadius:'var(--radius-lg)',padding: docFront ? 0 : 40,minHeight:200,cursor:'pointer',
 background: docFront ? 'transparent' : 'var(--brand-orange-50)',
 display:'flex',alignItems:'center',justifyContent:'center',position:'relative',overflow:'hidden'
 }}>
 {docFront ? (
 <img src={docFront} alt="" style={{width:'100%',display:'block'}}/>
 ) : (
 <div style={{textAlign:'center',color:'var(--brand-orange-700)'}}>
 <Icon name="camera" size={36}/>
 <div style={{marginTop:8,fontWeight:700,fontSize:14}}>Tap to scan document</div>
 <div style={{fontSize:11,color:'var(--ink-500)',marginTop:4}}>Make sure all 4 corners are visible</div>
 </div>
 )}
 </div>
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={() => setStep(1)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(3)} disabled={!docFront}
 style={{...btnPrimary,opacity: !docFront ? 0.5 : 1}}>Next</button>
 </div>
 </div>
 )}

 {step === 3 && (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 4px'}}>Selfie holding your document</h3>
 <p style={{fontSize:13,color:'var(--ink-500)',margin:'0 0 12px'}}>
 We use this to match your face to your ID. Used once for verification, never shared.
 </p>
 <input ref={selfieRef} type="file" accept="image/*" capture="user"
 onChange={e => e.target.files[0] && readFile(e.target.files[0], setSelfie)} style={{display:'none'}}/>
 <div onClick={() => selfieRef.current?.click()} style={{
 border: selfie ? '2px solid var(--success)' : '2px dashed var(--brand-orange)',
 borderRadius:'var(--radius-lg)',padding: selfie ? 0 : 40,minHeight:200,cursor:'pointer',
 background: selfie ? 'transparent' : 'var(--brand-orange-50)',
 display:'flex',alignItems:'center',justifyContent:'center',position:'relative',overflow:'hidden'
 }}>
 {selfie ? (
 <img src={selfie} alt="" style={{width:'100%',display:'block'}}/>
 ) : (
 <div style={{textAlign:'center',color:'var(--brand-orange-700)'}}>
 <Icon name="user-round" size={36}/>
 <div style={{marginTop:8,fontWeight:700,fontSize:14}}>Tap to take selfie</div>
 <div style={{fontSize:11,color:'var(--ink-500)',marginTop:4}}>Hold your ID next to your face</div>
 </div>
 )}
 </div>
 <div style={{display:'flex',gap:8,marginTop:16}}>
 <button onClick={() => setStep(2)} style={btnGhost}>Back</button>
 <button onClick={() => setStep(4)} disabled={!selfie}
 style={{...btnPrimary,opacity: !selfie ? 0.5 : 1}}>Submit for review</button>
 </div>
 </div>
 )}

 {step === 4 && (
 <div style={{...panelStyle,textAlign:'center',padding:32,background:'var(--success-100)',borderColor:'var(--success)'}}>
 <div style={{width:64,height:64,borderRadius:999,background:'var(--success)',color:'white',
 display:'inline-flex',alignItems:'center',justifyContent:'center',marginBottom:16}}>
 <Icon name="check" size={32} stroke={2.5}/>
 </div>
 <h2 style={{margin:'0 0 8px'}}>Submitted for review</h2>
 <p style={{color:'var(--ink-700)',fontSize:14}}>
 Your documents are encrypted and being reviewed. You'll get a notification within 24 hours.
 Most verifications complete in under 4 hours.
 </p>
 <button onClick={onComplete} style={{...btnPrimary,marginTop:16}}>Back to my account</button>
 </div>
 )}
 </div>
 );
}

/* --- Proof of Ownership uploader (for vehicles/property) --- */
function ProofOfOwnership({ kind = 'vehicle' }) {
 const map = {
 vehicle: { docs: ['Vehicle registration certificate (NaTIS)','Most recent licence disc','Proof of insurance (optional)'], title:'Prove you own this vehicle' },
 property: { docs: ['Title deed or rental agreement','Latest municipal rates account','Proof of address (Eskom / water bill)'], title:'Prove you own this property' },
 };
 const c = map[kind];
 const [uploaded, setUploaded] = useState({});

 return (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 4px'}}>{c.title}</h3>
 <p style={{fontSize:13,color:'var(--ink-500)',margin:'0 0 16px'}}>
 Required to publish {kind} listings. Documents are reviewed by Me2You admins, encrypted, and never shown to buyers.
 </p>
 {c.docs.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: uploaded[i] ? 'var(--success-100)' : 'var(--ink-100)',
 color: uploaded[i] ? 'var(--success)' : 'var(--ink-500)',
 display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
 <Icon name={uploaded[i] ? 'check' : 'image'} size={18} stroke={uploaded[i] ? 2.5 : 1.75}/>
 </div>
 <div style={{flex:1}}>
 <div style={{fontWeight:700,fontSize:13}}>{d}</div>
 <div style={{fontSize:11,color:'var(--ink-500)',marginTop:2}}>{uploaded[i] ? 'Uploaded - pending review' : 'JPG, PNG or PDF - max 5 MB'}</div>
 </div>
 <button onClick={() => setUploaded({...uploaded, [i]: !uploaded[i]})} style={{...btnSmall,fontSize:12,padding:'6px 12px'}}>
 {uploaded[i] ? 'Re-upload' : 'Upload'}
 </button>
 </div>
 ))}
 <button style={{...btnPrimary,marginTop:8}} disabled={Object.keys(uploaded).filter(k => uploaded[k]).length < 2}>
 Submit for verification
 </button>
 </div>
 );
}

/* --- Safe Meet-up Locations Map --- */
const SAFE_LOCATIONS = [
 { name:'Sandton SAPS', type:'Police station', lat:-26.1051, lng:28.0532, hours:'24/7' },
 { name:'Soweto Police Station', type:'Police station', lat:-26.2683, lng:27.8543, hours:'24/7' },
 { name:'Maponya Mall', type:'Shopping mall', lat:-26.2734, lng:27.8941, hours:'9am-7pm' },
 { name:'Sandton City', type:'Shopping mall', lat:-26.1085, lng:28.0568, hours:'9am-9pm' },
 { name:'Cresta Mall', type:'Shopping mall', lat:-26.1334, lng:27.9744, hours:'9am-7pm' },
 { name:'Hatfield SAPS', type:'Police station', lat:-25.7491, lng:28.2389, hours:'24/7' },
 { name:'Menlyn Park', type:'Shopping mall', lat:-25.7838, lng:28.2774, hours:'9am-9pm' },
];

function SafeMeetupMap({ buyerCoords = [-26.2041, 28.0473], onPick }) {
 const [chosen, setChosen] = useState(null);
 const markers = SAFE_LOCATIONS.map(l => ({
 lat:l.lat, lng:l.lng,
 label: l.type === 'Police station' ? 'P' : 'M',
 color: l.type === 'Police station' ? '#2D7AC7' : '#2F9E5A',
 popup: `<b>${l.name}</b><br/>${l.type}<br/>${l.hours}`,
 }));

 return (
 <div>
 <div style={{background:'var(--info-100)',padding:12,borderRadius:'var(--radius-md)',marginBottom:12,display:'flex',gap:10,alignItems:'start'}}>
 <Icon name="shield-check" size={18}/>
 <div style={{fontSize:13,color:'var(--ink-700)'}}>
 <strong>For self-collect orders</strong> we recommend meeting at a police station or busy shopping mall during daylight hours. Never meet at a private residence.
 </div>
 </div>
 <div style={{...panelStyle,padding:0,overflow:'hidden'}}>
 <LeafletMap center={buyerCoords} zoom={11} height={320} markers={markers}/>
 </div>
 <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill, minmax(200px, 1fr))',gap:8,marginTop:12}}>
 {SAFE_LOCATIONS.slice(0,4).map((l,i) => (
 <button key={i} onClick={() => { setChosen(l); if (onPick) onPick(l); }} style={{
 padding:12,borderRadius:'var(--radius-md)',cursor:'pointer',textAlign:'left',
 border: chosen?.name === l.name ? '2px solid var(--brand-orange)' : '1.5px solid var(--ink-200)',
 background: chosen?.name === l.name ? 'var(--brand-orange-50)' : 'var(--paper)',
 }}>
 <div style={{display:'flex',alignItems:'center',gap:6,fontSize:13,fontWeight:700}}>
 <Icon name={l.type === 'Police station' ? 'shield-check' : 'map-pin'} size={13}/>
 {l.name}
 </div>
 <div style={{fontSize:11,color:'var(--ink-500)',marginTop:2}}>{l.type} - {l.hours}</div>
 </button>
 ))}
 </div>
 </div>
 );
}

/* --- Report / Block User Modal --- */
function ReportUserModal({ userName, onClose, onSubmit }) {
 const [reason, setReason] = useState('');
 const [details, setDetails] = useState('');
 const [block, setBlock] = useState(true);

 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:480,width:'100%',background:'var(--paper)',borderRadius:'var(--radius-xl)',
 padding:24,boxShadow:'var(--shadow-lg)',animation:'pop .3s ease'}}>
 <div style={{display:'flex',justifyContent:'space-between',alignItems:'start',marginBottom:16}}>
 <div>
 <h2 style={{margin:'0 0 4px',fontSize:20}}>Report {userName || 'this user'}</h2>
 <p style={{color:'var(--ink-500)',fontSize:13,margin:0}}>Reports are anonymous and reviewed by Me2You admins.</p>
 </div>
 <button onClick={onClose} style={{background:'none',border:'none',cursor:'pointer',color:'var(--ink-400)',padding:4}}>
 <Icon name="x" size={20}/>
 </button>
 </div>
 <div style={{display:'flex',flexDirection:'column',gap:6,marginBottom:12}}>
 {['Scam or fake listing','Harassment or threats','Counterfeit goods','Stolen item','Inappropriate behaviour','Other'].map(r => (
 <label key={r} style={{display:'flex',alignItems:'center',gap:10,padding:10,
 borderRadius:'var(--radius-sm)',cursor:'pointer',
 background: reason===r ? 'var(--danger-100)' : 'var(--ink-50)',
 border: '1.5px solid ' + (reason===r ? 'var(--danger)' : 'transparent')}}>
 <input type="radio" checked={reason===r} onChange={() => setReason(r)}
 style={{accentColor:'var(--danger)'}}/>
 <span style={{fontSize:14,fontWeight:600}}>{r}</span>
 </label>
 ))}
 </div>
 <textarea value={details} onChange={e => setDetails(e.target.value)}
 placeholder="Details (optional)..." rows={3}
 style={{width:'100%',padding:12,border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',
 fontFamily:'var(--font-body)',fontSize:14,boxSizing:'border-box',resize:'vertical',marginBottom:12}}/>
 <label style={{display:'flex',alignItems:'center',gap:8,fontSize:13,cursor:'pointer',marginBottom:16}}>
 <input type="checkbox" checked={block} onChange={e => setBlock(e.target.checked)}
 style={{accentColor:'var(--brand-orange)'}}/>
 Also block this user from messaging me
 </label>
 <div style={{display:'flex',gap:8}}>
 <button onClick={onClose} style={{...btnGhost,flex:1,justifyContent:'center'}}>Cancel</button>
 <button onClick={() => { onSubmit && onSubmit({reason, details, block}); onClose(); }}
 disabled={!reason} style={{...btnDanger,flex:1,justifyContent:'center',opacity: reason ? 1 : 0.5}}>
 <Icon name="triangle-alert" size={16}/> Submit report
 </button>
 </div>
 </div>
 </div>
 );
}

/* --- 2FA Setup --- */
function TwoFactorSetup({ onComplete }) {
 const [enabled, setEnabled] = useState(false);
 const [method, setMethod] = useState('sms');
 const [code, setCode] = useState(['','','','','','']);
 const [verified, setVerified] = useState(false);

 if (verified) return (
 <div style={{...panelStyle,textAlign:'center',padding:24,background:'var(--success-100)',borderColor:'var(--success)'}}>
 <div style={{width:56,height:56,borderRadius:999,background:'var(--success)',color:'white',
 display:'inline-flex',alignItems:'center',justifyContent:'center',marginBottom:12}}>
 <Icon name="shield-check" size={28} stroke={2.5}/>
 </div>
 <h3 style={{margin:'0 0 4px'}}>Two-factor authentication is on</h3>
 <p style={{fontSize:13,color:'var(--ink-700)',margin:0}}>You'll need a code from {method === 'sms' ? 'SMS' : 'your authenticator app'} every time you sign in from a new device.</p>
 </div>
 );

 return (
 <div style={panelStyle}>
 <h3 style={{fontSize:16,margin:'0 0 4px'}}>Two-factor authentication</h3>
 <p style={{fontSize:13,color:'var(--ink-500)',margin:'0 0 16px'}}>
 Adds an extra layer of security. Required for sellers handling vehicles or property.
 </p>

 {!enabled ? (
 <button onClick={() => setEnabled(true)} style={btnPrimary}>
 <Icon name="shield-check" size={16}/> Enable 2FA
 </button>
 ) : (
 <>
 <label style={{display:'block',fontSize:13,fontWeight:700,marginBottom:8}}>Verification method</label>
 <div style={{display:'flex',gap:8,marginBottom:16}}>
 {[
 {key:'sms',label:'SMS to phone',desc:'071 234 5678'},
 {key:'app',label:'Authenticator app',desc:'Google Authenticator, Authy'},
 ].map(m => (
 <button key={m.key} onClick={() => setMethod(m.key)} style={{
 flex:1,padding:14,borderRadius:'var(--radius-md)',cursor:'pointer',textAlign:'left',
 border: method===m.key ? '2px solid var(--brand-orange)' : '1.5px solid var(--ink-200)',
 background: method===m.key ? 'var(--brand-orange-50)' : 'var(--paper)',
 }}>
 <div style={{fontWeight:700,fontSize:13}}>{m.label}</div>
 <div style={{fontSize:11,color:'var(--ink-500)',marginTop:2}}>{m.desc}</div>
 </button>
 ))}
 </div>

 <div style={{padding:12,background:'var(--ink-50)',borderRadius:'var(--radius-md)',marginBottom:12,fontSize:13}}>
 {method === 'sms' ? 'Code sent to 071 *** 5678' : 'Scan this QR with your app:'}
 {method === 'app' && (
 <div style={{margin:'12px auto',width:120,height:120,background:'#fff',border:'1px solid var(--ink-200)',
 borderRadius:8,display:'flex',alignItems:'center',justifyContent:'center'}}>
 <div style={{width:96,height:96,backgroundImage:`
 repeating-linear-gradient(0deg, #000 0 4px, #fff 4px 8px),
 repeating-linear-gradient(90deg, #000 0 4px, transparent 4px 8px)`,
 mixBlendMode:'darken'}}/>
 </div>
 )}
 </div>

 <label style={{display:'block',fontSize:13,fontWeight:700,marginBottom:8}}>Enter 6-digit code</label>
 <div style={{display:'flex',gap:6,justifyContent:'center',marginBottom:16}}>
 {[0,1,2,3,4,5].map(i => (
 <input key={i} maxLength={1} value={code[i]}
 onChange={e => {
 const v = e.target.value.replace(/\D/g,'');
 const nc = [...code]; nc[i] = v; setCode(nc);
 if (v && i < 5) e.target.nextSibling?.focus();
 }}
 style={{width:42,height:50,textAlign:'center',fontSize:20,fontFamily:'var(--font-mono)',fontWeight:700,
 border:'1.5px solid var(--ink-200)',borderRadius:'var(--radius-sm)',background:'var(--paper)'}}/>
 ))}
 </div>
 <button onClick={() => setVerified(true)} disabled={code.join('').length < 6}
 style={{...btnPrimary,width:'100%',justifyContent:'center',opacity: code.join('').length < 6 ? 0.5 : 1}}>
 Verify and enable
 </button>
 </>
 )}
 </div>
 );
}

Object.assign(window, { VerifiedBadge, IDVerifyWizard, ProofOfOwnership, SafeMeetupMap, ReportUserModal, TwoFactorSetup, SAFE_LOCATIONS });
