const { Button, Icon, IconButton, Badge, Card, Dialog, Input, RadioGroup, ListingCard } = window.HaileyAlexanderRealtorDesignSystem_1e3b8f;
function ListingDetail({param,go,saved,toggleSave,toast}){
  const id=Number(param);const l=window.HA_LISTINGS.find(x=>x.id===id)||window.HA_LISTINGS[0];const [open,setOpen]=React.useState(false);const [when,setWhen]=React.useState('weekend');
  const [tf,setTf]=React.useState({name:'',phone:'',company:''});const [tBusy,setTBusy]=React.useState(false);const [tErr,setTErr]=React.useState(null);const [tFe,setTFe]=React.useState({});
  const tset=k=>e=>{const v=e.target.value;setTf(s=>({...s,[k]:v}));setTFe(s=>s[k]?{...s,[k]:undefined}:s)};
  async function requestTour(){
    if(tBusy)return;setTBusy(true);setTErr(null);setTFe({});
    try{
      const r=await fetch('/api/contact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({kind:'tour',...tf,when,listing:l.address+' · '+l.city})});
      const d=await r.json().catch(()=>({}));
      if(!r.ok||!d.ok){setTFe(d.errors||{});setTErr(d.error||"I couldn't send that just now — please call or text me instead.");return;}
      setOpen(false);setTf({name:'',phone:'',company:''});toast("Got it! I'll be in touch within the day.",'success');
    }catch{
      setTErr("I couldn't reach the server — check your connection, or just call or text me.");
    }finally{setTBusy(false)}
  }
  // No featured listings loaded — don't render a detail page for nothing.
  if(!l) return <main className="wrap" style={{padding:'56px 0 0'}}>
    <Empty icon="house" title={<>That listing isn't <em>here</em>.</>} body="My live inventory is on my REMAX agent page." action="See my listings on REMAX" href={window.HA_PROFILE.remax}/>
  </main>;
  const label={new:'New listing',open:'Open house · Sat 1–3',sold:'Sold',pending:'Pending'}[l.status];
  const more=window.HA_LISTINGS.filter(x=>x.id!==l.id&&x.status!=='sold').slice(0,3);const comm=window.HA_COMMUNITIES.find(c=>c.slug===l.slug);
  const isLand=l.kind==='land';
  const photos=Array.isArray(l.photos)?l.photos:[];
  const perAcre=isLand&&l.acres&&l.price?Math.round(l.price/l.acres):null;
  const num=n=>typeof n==='number'?n.toLocaleString('en-US'):n;
  // A tile is a real photo when we have one, otherwise a neutral placeholder —
  // never a fabricated "+14 photos" count.
  const Ph=({i,children,style})=>photos[i]
    ? <div style={{borderRadius:'var(--radius-lg)',overflow:'hidden',...style}}><img src={photos[i]} alt="" style={{width:'100%',height:'100%',objectFit:'cover',display:'block'}}/></div>
    : <div style={{background:'var(--sand-200)',borderRadius:'var(--radius-lg)',display:'grid',placeItems:'center',color:'var(--stone-400)',fontSize:13,minHeight:120,...style}}>{children||'Listing photo'}</div>;
  return <main className="wrap" style={{padding:'32px 0 0'}}>
    <a href="#/listings" onClick={e=>{e.preventDefault();go('listings')}} style={{display:'inline-flex',alignItems:'center',gap:6,fontSize:14,fontWeight:600,color:'var(--text-secondary)'}}><Icon name="arrow-left" size={16}/>Back to listings</a>
    <div className="ggal" style={{gridAutoRows:'minmax(160px,22vw)',maxHeight:460,gap:12,marginTop:20,position:'relative'}}><Ph i={0} style={{gridRow:'1 / span 2'}}/><Ph i={1}/><Ph i={2}/><Ph i={3}/><Ph i={4}>{photos.length>5?'+'+(photos.length-5)+' photos':null}</Ph>
      <div style={{position:'absolute',top:14,left:14,display:'flex',gap:8}}>{label&&<Badge tone={l.status}>{label}</Badge>}</div>
      <div style={{position:'absolute',top:10,right:10,display:'flex',gap:8}}><IconButton label="Share" variant="glass" size="sm" onClick={()=>{navigator.clipboard&&navigator.clipboard.writeText(location.href);toast('Link copied')}}><Icon name="share-2" size={16}/></IconButton><IconButton label="Save" variant="glass" size="sm" active={saved.has(l.id)} onClick={()=>{toggleSave(l.id);toast(saved.has(l.id)?'Removed from favorites':'Saved to favorites')}}><Icon name="heart" size={16} style={saved.has(l.id)?{fill:'currentColor'}:undefined}/></IconButton></div></div>
    <div className="gside" style={{marginTop:40}}>
      <div>
        <div className="display" style={{fontSize:D.md}}>{'$'+l.price.toLocaleString('en-US')}</div>
        <h1 style={{fontSize:'var(--text-h2)',marginTop:8}}>{l.address}</h1>{comm
          ? <a href={'#/community/'+l.slug} onClick={e=>{e.preventDefault();go('community',l.slug)}} style={{color:'var(--text-secondary)',display:'inline-flex',alignItems:'center',gap:6,marginTop:4}}><Icon name="map-pin" size={16}/>{l.city}</a>
          : <div style={{color:'var(--text-secondary)',display:'inline-flex',alignItems:'center',gap:6,marginTop:4}}><Icon name="map-pin" size={16}/>{l.city}</div>}
        {perAcre&&<div style={{marginTop:6,color:'var(--text-secondary)',fontSize:15}}>{'$'+num(perAcre)} per acre</div>}
        <div style={{display:'flex',flexWrap:'wrap',marginTop:24,border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-lg)',overflow:'hidden',background:'var(--white)'}}>{(isLand
            ? [['trees',l.acres&&num(l.acres)+' ac','Acreage'],['route',l.road,'Frontage'],['sprout',l.ag?'Yes':null,'Ag exempt'],['droplet',l.utilities,'Utilities']]
            : [['bed',l.beds,'Beds'],['bath',l.baths,'Baths'],['ruler',l.sqft&&num(l.sqft),'Sq ft'],['trees',l.lot,'Lot'],['calendar',l.year,'Built']]
          ).filter(x=>x[1]!=null).map(([i,v,k])=><div key={k} style={{flex:'1 1 120px',padding:'16px 18px',borderRight:'1px solid var(--border-subtle)',borderBottom:'1px solid var(--border-subtle)',marginRight:-1,marginBottom:-1}}><Icon name={i} size={18} style={{color:'var(--rasp-500)'}}/><div style={{fontSize:20,fontWeight:600,marginTop:8,lineHeight:1}}>{v}</div><div style={{fontSize:12,color:'var(--text-secondary)',marginTop:4}}>{k}</div></div>)}</div>
        {l.desc&&<><h2 style={{fontSize:'var(--text-h3)',marginTop:36}}>{isLand?'About this land':'About this home'}</h2><p style={{color:'var(--text-secondary)',fontSize:16,maxWidth:640,margin:'10px 0 0'}}>{l.desc}</p></>}
        <h2 style={{fontSize:'var(--text-h3)',marginTop:36}}>The details</h2><dl className="g2s" style={{gap:'12px 40px',margin:'12px 0 0',fontSize:15,maxWidth:640}}>{[
            ['Type',l.type],
            isLand?['Acreage',l.acres&&num(l.acres)+' acres']:['Year built',l.year],
            isLand?['Road frontage',l.road]:['Lot size',l.lot],
            ['County',l.county||'Hunt'],
            isLand?['Ag exemption',l.ag==null?null:(l.ag?'Yes':'No')]:['School district',l.isd],
            isLand?['Utilities',l.utilities]:['HOA',l.hoa],
            ['MLS #',l.mls],
          ].filter(x=>x&&x[1]!=null&&x[1]!=='').map(([k,v])=><div key={k} style={{display:'flex',justifyContent:'space-between',gap:12,borderBottom:'1px solid var(--border-subtle)',paddingBottom:10}}><dt style={{color:'var(--text-secondary)'}}>{k}</dt><dd style={{margin:0,fontWeight:500,textAlign:'right'}}>{v}</dd></div>)}</dl>
        {l.listingCourtesyOf&&<p style={{marginTop:20,fontSize:13,color:'var(--text-tertiary)',maxWidth:640}}>Listing courtesy of {l.listingCourtesyOf}. Information deemed reliable but not guaranteed.</p>}
        {l.url&&<p style={{marginTop:12,fontSize:14}}><a href={l.url} target="_blank" rel="noopener noreferrer">View the full listing<Icon name="external-link" size={14} style={{marginLeft:6,verticalAlign:'-2px'}}/></a></p>}
        {comm&&<div style={{marginTop:36,padding:24,borderRadius:'var(--radius-lg)',background:comm.color,color:comm.text,display:'flex',justifyContent:'space-between',alignItems:'center',gap:16,flexWrap:'wrap'}}><div><div className="eyebrow" style={{color:comm.text,opacity:.8}}>About {comm.name}</div><div style={{fontSize:16,marginTop:6,maxWidth:520}}>Homes, land and farm &amp; ranch in {comm.name}.</div></div><Button variant="inverse" size="sm" iconRight={<Icon name="arrow-right" size={16}/>} onClick={()=>go('community',comm.slug)}>Explore {comm.name}</Button></div>}
      </div>
      <Card padding={28} style={{position:'sticky',top:96}}>
        <div style={{display:'flex',gap:14,alignItems:'center'}}><img className="photo" src="../../assets/photos/hailey-teal-wall-headshot.jpg" alt="" style={{width:64,height:64,borderRadius:'50%',objectFit:'cover',objectPosition:'50% 30%'}}/><div><div style={{fontWeight:600,fontSize:16}}>Hailey Alexander</div><div style={{fontSize:13,color:'var(--text-secondary)'}}>Realtor® · REMAX Four Corners</div></div></div>
        <p style={{fontSize:14,color:'var(--text-secondary)',margin:'18px 0 20px'}}>Want to see it in person? I can usually get you in within a day or two.</p>
        <Button fullWidth size="lg" iconLeft={<Icon name="calendar" size={20}/>} onClick={()=>setOpen(true)} disabled={l.status==='sold'}>{l.status==='sold'?'Sold':'Book a tour'}</Button>
        <Button fullWidth variant="secondary" style={{marginTop:10}} iconLeft={<Icon name="message-circle" size={18}/>} onClick={()=>go('contact')}>Ask a question</Button>
        <div style={{fontSize:12,color:'var(--text-tertiary)',textAlign:'center',marginTop:14}}>No pressure — I'll text you back within the day.</div>
      </Card>
    </div>
    <section className="sec"><h2 className="display" style={{fontSize:D.sm}}>You might also <em>like</em>.</h2><div className="g3" style={{marginTop:20}}>{more.map(m=><ListingCard key={m.id} {...m} image={(m.photos||[])[0]} compact saved={saved.has(m.id)} onSave={()=>toggleSave(m.id)} onClick={()=>go('listing',m.id)}/>)}</div></section>
    <Dialog open={open} onClose={()=>tBusy?null:setOpen(false)} eyebrow={l.address} title={<>Let's go see <em style={{color:'var(--rasp-600)'}}>it</em>.</>} footer={<><Button variant="ghost" onClick={()=>setOpen(false)} disabled={tBusy}>Not yet</Button><Button onClick={requestTour} loading={tBusy} disabled={tBusy}>{tBusy?'Sending':'Request tour'}</Button></>}>
      <div style={{display:'grid',gap:14}}>
        {tErr&&<div role="alert" style={{display:'flex',gap:12,alignItems:'flex-start',padding:'14px 16px',borderRadius:'var(--radius-md)',background:'var(--danger-soft)',color:'var(--danger)',fontSize:14,lineHeight:1.5}}><Icon name="triangle-alert" size={18} style={{flexShrink:0,marginTop:1}}/><span>{tErr}</span></div>}
        <RadioGroup name="when" direction="row" value={when} onChange={setWhen} options={[{value:'weekend',label:'This weekend'},{value:'week',label:'This week'},{value:'flex',label:"I'm flexible"}]}/>
        <Input label="Your name" placeholder="First and last" value={tf.name} onChange={tset('name')} error={tFe.name} autoComplete="name"/>
        <Input label="Phone" type="tel" placeholder="(903) 555-0100" value={tf.phone} onChange={tset('phone')} error={tFe.phone} hint="I'll text, not call — unless you'd rather I call." autoComplete="tel"/>
        <input type="text" name="company" tabIndex={-1} autoComplete="off" aria-hidden="true" value={tf.company} onChange={tset('company')} style={{position:'absolute',left:'-9999px',width:1,height:1,opacity:0}}/>
      </div>
    </Dialog>
  </main>;
}
window.ListingDetail=ListingDetail;