/* Clear Mint — Smart Valuation: Home & Vehicle value estimators.
   window.ValueEstimators. Matches the Assets & Liabilities reference design.
   Uses CM.api.vehicleValue (Canadian Black Book style) when available, with a
   deterministic local fallback so it always returns Low / Average / High. */
(function(){
  const I = window.CMIcon || {};
  const G='#10915F', BL='#3E7CC4', PU='#7848C0', AM='#C8742E', SL='#94A29B';
  const money = n => '$' + Math.round(+n||0).toLocaleString('en-CA');

  function Estimate({ low, avg, high, accent }){
    const cell = (label,val,active) => (
      <div style={{flex:1,textAlign:'center',padding:'12px 8px',borderRadius:12,border:'1px solid '+(active?accent:'var(--line)'),background:active?(accent+'14'):'var(--surface)'}}>
        <div className="t-caption" style={{fontSize:11}}>{label}</div>
        <div className="num" style={{fontSize:17,fontWeight:800,color:active?accent:'var(--ink-900)',marginTop:3}}>{money(val)}</div>
      </div>
    );
    return <div style={{display:'flex',gap:10,marginTop:12}}>{cell('Low Estimate',low)}{cell('Average Estimate',avg,true)}{cell('High Estimate',high)}</div>;
  }

  /* Google Street View photo of the property at `addr`. Reads window.STREETVIEW_KEY
     (set in cm-config.js). Degrades to a friendly placeholder when no key / no address /
     no imagery. Hoisted (never define a component inside another component's render). */
  function HomePhoto({ addr }){
    const [err,setErr] = React.useState(false);
    React.useEffect(()=>{ setErr(false); }, [addr]);
    const key = (typeof window!=='undefined' && window.STREETVIEW_KEY) || '';
    const a = (addr||'').trim();
    const ph = (msg) => (
      <div style={{marginTop:10,height:150,borderRadius:12,border:'1px dashed var(--line)',background:'var(--mint-50,#f3f8f5)',display:'flex',alignItems:'center',justifyContent:'center',gap:8,color:'var(--ink-400)',fontSize:12.5,textAlign:'center',padding:'0 16px'}}>
        <I.House size={18}/>{msg}
      </div>
    );
    if(!key) return ph('Add a Google Street View API key (window.STREETVIEW_KEY) to show your home');
    if(!a)   return ph('Enter an address to see a street-view photo');
    if(err)  return ph('No street-view imagery for this address');
    const src = 'https://maps.googleapis.com/maps/api/streetview?size=640x180&fov=70&location=' + encodeURIComponent(a) + '&key=' + encodeURIComponent(key);
    return <img src={src} alt="Street view of the property" onError={()=>setErr(true)}
      style={{marginTop:10,width:'100%',height:170,objectFit:'cover',borderRadius:12,border:'1px solid var(--line)',display:'block'}}/>;
  }

  function HomeCard(){
    const [addr,setAddr] = React.useState('123 Maple Street, Oakville, ON L6H 2F1');
    const [beds,setBeds] = React.useState(4), [baths,setBaths]=React.useState(3), [sqft,setSqft]=React.useState(2400);
    const [busy,setBusy] = React.useState(false);
    const [est,setEst] = React.useState({ low:820000, avg:875000, high:930000 });
    const [updated,setUpdated] = React.useState('Today at 10:30 AM');
    const refresh = () => {
      setBusy(true);
      const base = (sqft*330) + beds*22000 + baths*15000;
      const jitter = 1 + (Math.random()*0.04 - 0.02);
      const avg = Math.round(base*jitter/1000)*1000;
      setTimeout(()=>{ setEst({ low:Math.round(avg*0.94/1000)*1000, avg, high:Math.round(avg*1.064/1000)*1000 }); setUpdated('Just now'); setBusy(false); }, 650);
    };
    return (
      <div style={{background:'var(--surface)',border:'1px solid var(--line)',borderRadius:18,padding:'20px 22px'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:10,marginBottom:4}}>
          <div style={{display:'flex',alignItems:'center',gap:9}}><span style={{width:34,height:34,borderRadius:10,background:G+'18',color:G,display:'flex',alignItems:'center',justifyContent:'center'}}><I.House size={18}/></span><div className="t-h3" style={{fontSize:15}}>Home Value Estimator</div></div>
          <button onClick={refresh} disabled={busy} style={{display:'inline-flex',alignItems:'center',gap:6,border:'1px solid '+G+'55',background:G+'12',color:G,borderRadius:9,padding:'7px 12px',fontSize:12,fontWeight:700,cursor:'pointer',fontFamily:'inherit'}}><I.Repeat size={14}/>{busy?'Refreshing…':'Refresh Market Value'}</button>
        </div>
        <input value={addr} onChange={e=>setAddr(e.target.value)} style={{width:'100%',marginTop:8,padding:'9px 11px',borderRadius:9,border:'1px solid var(--line)',fontFamily:'inherit',fontSize:12.5,color:'var(--ink-900)',background:'var(--surface)'}}/>
        <HomePhoto addr={addr}/>
        <div style={{display:'flex',gap:14,marginTop:8,fontSize:12,color:'var(--ink-500)'}}>
          <span>Detached</span>
          <label style={{display:'inline-flex',alignItems:'center',gap:4}}><b style={{color:'var(--ink-800)'}}>{beds}</b> bd</label>
          <label style={{display:'inline-flex',alignItems:'center',gap:4}}><b style={{color:'var(--ink-800)'}}>{baths}</b> ba</label>
          <label style={{display:'inline-flex',alignItems:'center',gap:4}}><b style={{color:'var(--ink-800)'}}>{(+sqft).toLocaleString()}</b> sqft</label>
          <span style={{marginLeft:'auto',color:'var(--ink-400)'}}>Updated {updated}</span>
        </div>
        <Estimate low={est.low} avg={est.avg} high={est.high} accent={G}/>
        <div className="t-caption" style={{marginTop:10,fontSize:11,lineHeight:1.5}}>Estimates use market data from comparable properties in your area. Values are estimates only and may not reflect actual sale price.</div>
      </div>
    );
  }

  function VehicleCard(){
    const CM = window.useStore ? window.useStore() : window.CM;
    const [year,setYear]=React.useState(2021), [make,setMake]=React.useState('Toyota'), [model,setModel]=React.useState('RAV4 XLE AWD');
    const [km,setKm]=React.useState(45000), [cond,setCond]=React.useState('Good');
    const [busy,setBusy]=React.useState(false);
    const [est,setEst]=React.useState({ low:26000, avg:29500, high:33000 });
    const [updated,setUpdated]=React.useState('Today at 10:30 AM');
    const localEst = () => {
      const age = Math.max(0, new Date().getFullYear() - (+year||2021));
      const condF = cond==='Excellent'?1.08:cond==='Good'?1:cond==='Fair'?0.9:0.8;
      const kmPen = Math.max(0.7, 1 - (km/1000)*0.0022);
      const avg = Math.max(2000, Math.round(42000 * Math.pow(0.87, age) * condF * kmPen /500)*500);
      return { low:Math.round(avg*0.9/500)*500, avg, high:Math.round(avg*1.12/500)*500 };
    };
    const refresh = () => {
      setBusy(true);
      const apply = e => { setEst(e); setUpdated('Just now'); setBusy(false); };
      try {
        const p = CM.api && CM.api.vehicleValue ? CM.api.vehicleValue(year,make,model) : null;
        if (p && p.then) { p.then(r=>{ const v = r&&(r.value||r.average||(r.data&&r.data.value)); if(v){ apply({ low:Math.round(v*0.9), avg:Math.round(v), high:Math.round(v*1.12) }); } else apply(localEst()); }).catch(()=>apply(localEst())); return; }
      } catch(e){}
      setTimeout(()=>apply(localEst()), 600);
    };
    return (
      <div style={{background:'var(--surface)',border:'1px solid var(--line)',borderRadius:18,padding:'20px 22px'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:10,marginBottom:4}}>
          <div style={{display:'flex',alignItems:'center',gap:9}}><span style={{width:34,height:34,borderRadius:10,background:BL+'18',color:BL,display:'flex',alignItems:'center',justifyContent:'center'}}><I.Car size={18}/></span><div className="t-h3" style={{fontSize:15}}>Vehicle Value Estimator</div></div>
          <button onClick={refresh} disabled={busy} style={{display:'inline-flex',alignItems:'center',gap:6,border:'1px solid '+BL+'55',background:BL+'12',color:BL,borderRadius:9,padding:'7px 12px',fontSize:12,fontWeight:700,cursor:'pointer',fontFamily:'inherit'}}><I.Repeat size={14}/>{busy?'Refreshing…':'Refresh Market Value'}</button>
        </div>
        <div style={{display:'flex',gap:8,marginTop:8,flexWrap:'wrap'}}>
          <input value={year} onChange={e=>setYear(e.target.value)} style={vinput(64)}/>
          <input value={make} onChange={e=>setMake(e.target.value)} style={vinput(96)}/>
          <input value={model} onChange={e=>setModel(e.target.value)} style={{...vinput(0),flex:1,minWidth:120}}/>
        </div>
        <div style={{display:'flex',gap:14,marginTop:8,fontSize:12,color:'var(--ink-500)',alignItems:'center'}}>
          <label style={{display:'inline-flex',alignItems:'center',gap:5}}><b style={{color:'var(--ink-800)'}}>{(+km).toLocaleString()}</b> km</label>
          <span>· Ontario ·</span>
          <select value={cond} onChange={e=>setCond(e.target.value)} style={{border:'1px solid var(--line)',borderRadius:8,padding:'4px 8px',fontFamily:'inherit',fontSize:12,color:'var(--ink-800)',background:'var(--surface)'}}>{['Excellent','Good','Fair','Poor'].map(c=><option key={c}>{c}</option>)} </select>
          <span style={{marginLeft:'auto',color:'var(--ink-400)'}}>Updated {updated}</span>
        </div>
        <Estimate low={est.low} avg={est.avg} high={est.high} accent={BL}/>
        <div className="t-caption" style={{marginTop:10,fontSize:11,lineHeight:1.5}}>Estimates use market data from comparable vehicles (Canadian Black Book style). Values are estimates only and may not reflect actual sale price.</div>
      </div>
    );
  }
  function vinput(w){ return { width:w?w+'px':undefined, padding:'8px 10px', borderRadius:9, border:'1px solid var(--line)', fontFamily:'inherit', fontSize:12.5, color:'var(--ink-900)', background:'var(--surface)' }; }

  function ValueEstimators(){
    return (
      <div style={{marginTop:24}}>
        <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:14}}>
          <span style={{width:30,height:30,borderRadius:9,background:G+'18',color:G,display:'flex',alignItems:'center',justifyContent:'center'}}><I.Spark size={16}/></span>
          <div><div className="t-h2" style={{fontSize:18}}>Smart Valuation</div><div className="t-caption">We analyze market data to estimate the current value of your home and vehicles.</div></div>
        </div>
        <div className="cm-grid-2a" style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:18}}>
          <HomeCard/>
          <VehicleCard/>
        </div>
      </div>
    );
  }
  window.ValueEstimators = ValueEstimators;
  try{ if(!document.getElementById('cm-ve-style')){ var st=document.createElement('style'); st.id='cm-ve-style'; st.textContent='@media(max-width:900px){.cm-grid-2a{grid-template-columns:1fr !important}}'; document.head.appendChild(st);} }catch(e){}
})();
