// Property drawer + property cards (right-side drawer over map).

const { useState: useStateP, useEffect: useEffectP } = React;

function PropertyList({ neighborhoodId, onOpenProperty, L, lang }) {
  const isRTL = lang === 'ar';
  const { NEIGHBORHOODS, PROPERTIES } = window.DATA;
  const nh = NEIGHBORHOODS.find(n => n.id === neighborhoodId);
  const props = PROPERTIES.filter(p => p.nh === neighborhoodId);
  if (!nh) return null;
  const trNh = isRTL ? window.I18N_NEIGHBORHOODS[neighborhoodId] : null;
  const nhName = trNh ? trNh.name : nh.name;
  const nhBlurb = trNh ? trNh.blurb : nh.blurb;
  const emirate = isRTL ? (nh.emirate === 'Dubai' ? L.mapUI.dubai : L.mapUI.abuDhabi) : nh.emirate;

  return (
    <div>
      <div style={{padding:'28px 32px 20px', borderBottom:'1px solid var(--line-2)'}}>
        <div className="mono" style={{color:'var(--bronze)', marginBottom:10}}>{emirate}</div>
        <div className="display" style={{fontSize:44, lineHeight:1.1, marginBottom:10}}>{nhName}</div>
        <div style={{fontSize:14, lineHeight:1.7, color:'var(--ink-2)', maxWidth:400}}>{nhBlurb}</div>
      </div>
      <div style={{padding:'12px 32px 48px'}}>
        <div className="mono" style={{color:'var(--mute)', padding:'16px 0 12px'}}>
          {L.drawer.available(props.length)}
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:18}}>
          {props.map(p => (
            <PropertyCard key={p.id} p={p} onClick={() => onOpenProperty(p.id)} L={L}/>
          ))}
        </div>
      </div>
    </div>
  );
}

function PropertyCard({ p, onClick, L }) {
  return (
    <button onClick={onClick}
      style={{
        textAlign:'start',
        display:'grid',
        gridTemplateColumns:'140px 1fr',
        gap:18,
        padding:14,
        background:'#f3eee5',
        border:'1px solid var(--line-2)',
        transition:'all .25s ease',
      }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--bronze)'; e.currentTarget.style.background = '#f7f2e8'; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.background = '#f3eee5'; }}
    >
      <div style={{
        width:'100%', height:140,
        backgroundImage:`url(${p.gallery[0]})`,
        backgroundSize:'cover', backgroundPosition:'center',
      }}/>
      <div style={{paddingTop:4}}>
        <div className="mono" style={{color:'var(--bronze)', marginBottom:8}}>{p.type}</div>
        <div className="display" style={{fontSize:22, lineHeight:1.25, marginBottom:10}}>{p.title}</div>
        <div style={{fontSize:12, color:'var(--mute)', marginBottom:12, display:'flex', gap:10, flexWrap:'wrap'}}>
          <span>{p.beds} {L.drawer.bed}</span><span style={{opacity:0.4}}>·</span>
          <span>{p.baths} {L.drawer.bath}</span><span style={{opacity:0.4}}>·</span>
          <span>{p.sqft} {L.drawer.sqft}</span>
        </div>
        <div className="display" style={{fontSize:20}}>{p.price}</div>
      </div>
    </button>
  );
}

// ---- Property Detail ----
function PropertyDetail({ propertyId, onClose, L, lang }) {
  const isRTL = lang === 'ar';
  const { PROPERTIES, NEIGHBORHOODS } = window.DATA;
  const p = PROPERTIES.find(x => x.id === propertyId);
  const [idx, setIdx] = useStateP(0);
  const [showForm, setShowForm] = useStateP(false);
  useEffectP(() => { setIdx(0); setShowForm(false); }, [propertyId]);
  if (!p) return null;
  const nh = NEIGHBORHOODS.find(n => n.id === p.nh);
  const trNh = isRTL ? window.I18N_NEIGHBORHOODS[p.nh] : null;
  const nhName = trNh ? trNh.name : nh.name;
  const emirate = isRTL ? (nh.emirate === 'Dubai' ? L.mapUI.dubai : L.mapUI.abuDhabi) : nh.emirate;

  return (
    <div style={{
      position:'absolute', inset:0,
      background:'var(--ivory)',
      zIndex:10,
      overflow:'auto',
    }}>
      <div style={{
        position:'sticky', top:0, zIndex:2,
        display:'flex', justifyContent:'space-between', alignItems:'center',
        padding:'16px 32px',
        background:'rgba(243,238,229,0.94)',
        backdropFilter:'blur(10px)',
        borderBottom:'1px solid var(--line-2)',
      }}>
        <button onClick={onClose} className="mono" style={{display:'flex', alignItems:'center', gap:8, color:'var(--ink-2)'}}>
          {L.drawer.back(nhName)}
        </button>
        <div className="mono" style={{color:'var(--mute)'}}>{L.drawer.ref} · HM-{p.id.toUpperCase()}</div>
      </div>

      <div style={{position:'relative', width:'100%', height:460, background:'#121212'}}>
        <div style={{
          width:'100%', height:'100%',
          backgroundImage:`url(${p.gallery[idx]})`,
          backgroundSize:'cover', backgroundPosition:'center',
          transition:'background-image .3s',
        }}/>
        <div style={{
          position:'absolute', insetInlineStart:32, bottom:20, display:'flex', gap:6,
          background:'rgba(18,18,18,0.5)', padding:6,
        }}>
          {p.gallery.map((g, i) => (
            <button key={i} onClick={() => setIdx(i)}
              style={{
                width:54, height:40,
                backgroundImage:`url(${g})`, backgroundSize:'cover', backgroundPosition:'center',
                opacity: i === idx ? 1 : 0.5,
                outline: i === idx ? '2px solid #b89466' : 'none',
                transition:'opacity .2s',
              }}/>
          ))}
        </div>
        <div style={{
          position:'absolute', insetInlineEnd:32, bottom:20,
          color:'#f3eee5', fontFamily:"'Archivo Narrow', sans-serif",
          fontSize:10, letterSpacing:'0.22em',
        }}>
          {(idx+1).toString().padStart(2,'0')} / {p.gallery.length.toString().padStart(2,'0')}
        </div>
      </div>

      <div style={{padding:'36px 32px 48px', maxWidth:820}}>
        <div className="mono" style={{color:'var(--bronze)', marginBottom:14}}>{p.type} · {nhName}, {emirate}</div>
        <div className="display" style={{fontSize:42, lineHeight:1.15, marginBottom:18}}>{p.title}</div>
        <div style={{fontSize:15, lineHeight:1.75, color:'var(--ink-2)', marginBottom:28, maxWidth:680}}>
          {p.summary}
        </div>

        <div style={{
          display:'grid', gridTemplateColumns:'repeat(4, 1fr)',
          borderTop:'1px solid var(--line)',
          borderBottom:'1px solid var(--line)',
          padding:'22px 0', marginBottom:28,
        }}>
          <Spec label={L.drawer.price} value={p.price} big/>
          <Spec label={L.drawer.beds} value={p.beds}/>
          <Spec label={L.drawer.baths} value={p.baths}/>
          <Spec label={L.drawer.interior} value={p.sqft + ' ' + L.drawer.sqft}/>
        </div>

        <div style={{
          display:'grid', gridTemplateColumns:'repeat(3, 1fr)',
          gap:24, marginBottom:36, paddingBottom:28, borderBottom:'1px solid var(--line-2)'
        }}>
          <Spec label={L.drawer.plot} value={p.plot === '—' ? '—' : p.plot + ' ' + L.drawer.sqft}/>
          <Spec label={L.drawer.view} value={p.view}/>
          <Spec label={L.drawer.tenure} value={p.tenure}/>
        </div>

        <div className="mono" style={{color:'var(--mute)', marginBottom:14}}>{L.drawer.defines}</div>
        <ul style={{listStyle:'none', padding:0, margin:'0 0 36px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px 28px'}}>
          {p.highlights.map((h,i) => (
            <li key={i} style={{fontSize:14, paddingInlineStart:18, position:'relative', color:'var(--ink-2)'}}>
              <span style={{position:'absolute', insetInlineStart:0, top:8, width:8, height:1, background:'var(--bronze)'}}/>
              {h}
            </li>
          ))}
        </ul>

        <InquiryBlock property={p} showForm={showForm} setShowForm={setShowForm} L={L} lang={lang}/>
      </div>
    </div>
  );
}

function Spec({label, value, big}) {
  return (
    <div>
      <div className="mono" style={{color:'var(--mute)', marginBottom:6, fontSize:9}}>{label}</div>
      <div className="display" style={{fontSize: big ? 26 : 20, lineHeight:1.2}}>{value}</div>
    </div>
  );
}

function InquiryBlock({ property, showForm, setShowForm, L, lang }) {
  const isRTL = lang === 'ar';
  const [sent, setSent] = useStateP(false);
  const [name, setName] = useStateP('');
  const [email, setEmail] = useStateP('');
  const [phone, setPhone] = useStateP('');
  const [msg, setMsg] = useStateP(L.inquiry.greeting(property.title, property.id.toUpperCase()));

  useEffectP(() => {
    setMsg(L.inquiry.greeting(property.title, property.id.toUpperCase()));
    setSent(false);
  }, [property.id, lang]);

  const waUrl = `https://wa.me/971561755171?text=${encodeURIComponent(msg)}`;

  return (
    <div style={{
      background:'#ebe4d6',
      border:'1px solid var(--line)',
      padding:'30px 28px',
    }}>
      <div style={{display:'flex', gap:20, alignItems:'center', marginBottom:22}}>
        <div style={{
          width:64, height:64, borderRadius:'50%',
          background:`linear-gradient(135deg, #8a6a3b, #b89466)`,
          display:'flex', alignItems:'center', justifyContent:'center',
          color:'#f3eee5',
          fontFamily: isRTL ? "'Amiri', serif" : "'Italiana', serif",
          fontSize:28, flexShrink:0,
        }}>{isRTL ? 'ح' : 'H'}</div>
        <div>
          <div className="mono" style={{color:'var(--bronze)', marginBottom:4}}>{L.inquiry.yourAgent}</div>
          <div className="display" style={{fontSize:22, lineHeight:1.2}}>{L.inquiry.agentName}</div>
          <div style={{fontSize:12, color:'var(--mute)'}}>{L.inquiry.agentSub}</div>
        </div>
      </div>

      {!showForm && !sent && (
        <>
          <div style={{fontSize:14, color:'var(--ink-2)', marginBottom:20, lineHeight:1.65}}>
            {L.inquiry.lead}
          </div>

          <div style={{
            background:'#f3eee5', border:'1px solid var(--line-2)',
            padding:'16px 18px', marginBottom:18, fontSize:13.5,
            color:'var(--ink-2)', lineHeight:1.6, position:'relative',
          }}>
            <div className="mono" style={{color:'var(--mute)', marginBottom:8, fontSize:9}}>{L.inquiry.preview}</div>
            <textarea value={msg} onChange={e => setMsg(e.target.value)}
              dir={isRTL ? 'rtl' : 'ltr'}
              style={{
                width:'100%', minHeight:60, border:'none', background:'transparent',
                fontFamily:'inherit', fontSize:13.5, color:'var(--ink)', resize:'vertical',
                outline:'none', lineHeight:1.6,
              }}/>
          </div>

          <div style={{display:'flex', gap:10, flexWrap:'wrap'}}>
            <a href={waUrl} target="_blank" rel="noopener"
              style={{
                display:'inline-flex', alignItems:'center', gap:10,
                padding:'14px 24px', background:'var(--ink)',
                color:'var(--ivory)', textDecoration:'none',
                fontFamily: isRTL ? "'Noto Kufi Arabic', sans-serif" : 'Archivo Narrow, sans-serif',
                letterSpacing: isRTL ? '0.1em' : '0.2em',
                fontSize:11, textTransform: isRTL ? 'none' : 'uppercase',
              }}>
              <WhatsAppIcon/> {L.inquiry.waBtn}
            </a>
            <button onClick={() => setShowForm(true)}
              className="mono"
              style={{
                padding:'14px 24px', border:'1px solid var(--ink)',
                fontSize:11, color:'var(--ink)',
              }}>
              {L.inquiry.emailBtn}
            </button>
          </div>
        </>
      )}

      {showForm && !sent && (
        <form onSubmit={e => { e.preventDefault(); setSent(true); }}
          style={{display:'grid', gap:14}}>
          <Input label={L.inquiry.name} value={name} onChange={setName} required/>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
            <Input label={L.inquiry.email} type="email" value={email} onChange={setEmail} required/>
            <Input label={L.inquiry.phone} type="tel" value={phone} onChange={setPhone} placeholder="+971 50 ..."/>
          </div>
          <div>
            <div className="mono" style={{color:'var(--mute)', marginBottom:6, fontSize:9}}>{L.inquiry.message}</div>
            <textarea value={msg} onChange={e => setMsg(e.target.value)}
              rows={4}
              dir={isRTL ? 'rtl' : 'ltr'}
              style={{
                width:'100%', padding:'12px 14px', background:'#f3eee5',
                border:'1px solid var(--line-2)', fontFamily:'inherit', fontSize:14,
                color:'var(--ink)', outline:'none', resize:'vertical',
              }}/>
          </div>
          <div style={{display:'flex', gap:10, paddingTop:6}}>
            <button type="submit" className="mono"
              style={{
                padding:'14px 24px', background:'var(--ink)',
                color:'var(--ivory)', fontSize:11,
              }}>
              {L.inquiry.send}
            </button>
            <button type="button" onClick={() => setShowForm(false)}
              className="mono"
              style={{padding:'14px 24px', color:'var(--mute)', fontSize:11}}>
              {L.inquiry.backBtn}
            </button>
          </div>
        </form>
      )}

      {sent && (
        <div style={{padding:'20px 0'}}>
          <div className="mono" style={{color:'var(--bronze)', marginBottom:10}}>{L.inquiry.received}</div>
          <div className="display" style={{fontSize:24, marginBottom:8}}>{L.inquiry.thanks(name)}</div>
          <div style={{fontSize:14, color:'var(--ink-2)', lineHeight:1.65}}>
            {L.inquiry.sentLine}
          </div>
          <div style={{marginTop:16, paddingTop:16, borderTop:'1px solid var(--line-2)', display:'flex', gap:20, fontSize:13, flexWrap:'wrap'}}>
            <div><span className="mono" style={{color:'var(--mute)'}}>{L.inquiry.direct}</span> · +971 56 175 5171</div>
            <div><span className="mono" style={{color:'var(--mute)'}}>{L.inquiry.emailLabel}</span> · hamza.eleiwat@psinv.pro</div>
          </div>
        </div>
      )}
    </div>
  );
}

function Input({label, value, onChange, type='text', required, placeholder}) {
  return (
    <div>
      <div className="mono" style={{color:'var(--mute)', marginBottom:6, fontSize:9}}>{label}{required && ' *'}</div>
      <input type={type} value={value} onChange={e => onChange(e.target.value)}
        required={required} placeholder={placeholder}
        style={{
          width:'100%', padding:'12px 14px', background:'#f3eee5',
          border:'1px solid var(--line-2)', fontFamily:'inherit', fontSize:14,
          color:'var(--ink)', outline:'none',
        }}/>
    </div>
  );
}

function WhatsAppIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.297-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
    </svg>
  );
}

window.PropertyList = PropertyList;
window.PropertyDetail = PropertyDetail;
