// Thai Address Autocomplete — ใช้ Backend API
(function() {
  const { useState, useEffect, useRef } = React;

  async function searchAPI(field, value) {
    if (!value || value.length < 1) return [];
    try {
      const res = await fetch(window.ADMIN_CONFIG.apiUrl + '/thai-address/search?field=' + field + '&q=' + encodeURIComponent(value));
      const data = await res.json();
      return data.results || [];
    } catch { return []; }
  }

  function AddressAutocomplete({ label, field, value, onChange, onSelect, placeholder }) {
    const [suggestions, setSuggestions] = useState([]);
    const [show, setShow] = useState(false);
    const [timer, setTimer] = useState(null);
    const wrapRef = useRef(null);

    useEffect(() => {
      function handleClick(e) {
        if (wrapRef.current && !wrapRef.current.contains(e.target)) setShow(false);
      }
      document.addEventListener('mousedown', handleClick);
      return () => document.removeEventListener('mousedown', handleClick);
    }, []);

    function handleChange(e) {
      const v = e.target.value;
      onChange(v);
      if (timer) clearTimeout(timer);
      if (v.length >= 1) {
        setTimer(setTimeout(async () => {
          const results = await searchAPI(field, v);
          setSuggestions(results);
          setShow(results.length > 0);
        }, 200));
      } else {
        setShow(false);
      }
    }

    function handleSelect(item) {
      onSelect(item);
      setShow(false);
    }

    return (
      <div className="form-group" ref={wrapRef} style={{position:'relative'}}>
        <label>{label}</label>
        <input className="input" value={value} onChange={handleChange}
          placeholder={placeholder || ('พิมพ์เพื่อค้นหา' + label)} autoComplete="off" />
        {show && suggestions.length > 0 && (
          <div style={{
            position:'absolute', top:'100%', left:0, right:0, zIndex:100,
            background:'#fff', border:'1px solid #E5E7EB', borderRadius:10,
            boxShadow:'0 8px 24px rgba(0,0,0,.12)', maxHeight:240, overflowY:'auto', marginTop:4,
          }}>
            {suggestions.map((s, i) => (
              <div key={i} onClick={() => handleSelect(s)}
                style={{
                  padding:'10px 14px', cursor:'pointer', fontSize:14,
                  borderBottom: i < suggestions.length-1 ? '1px solid #F3F4F6' : 'none',
                }}
                onMouseEnter={e => e.currentTarget.style.background='#F4F8FD'}
                onMouseLeave={e => e.currentTarget.style.background='#fff'}>
                <span style={{fontWeight:600, color:'#102E54'}}>
                  {s.subdistrict} <span style={{color:'#9CA3AF'}}>›</span> {s.district} <span style={{color:'#9CA3AF'}}>›</span> {s.province}
                </span>
                <span style={{fontSize:12, color:'#2A6BE0', marginLeft:8}}>{s.zipcode}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  function ThaiAddressForm({ form, set }) {
    function onSelect(item) {
      set('subdistrict', item.subdistrict);
      set('district', item.district);
      set('province', item.province);
      set('zipcode', item.zipcode);
    }

    return (
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
        {/* ที่อยู่ (เลขที่ ซอย ถนน) อยู่บนสุด เต็มแถว */}
        <div className="form-group" style={{gridColumn:'1/-1'}}>
          <label>ที่อยู่</label>
          <input className="input" value={form.full_address||''} onChange={e => set('full_address',e.target.value)} placeholder="เลขที่ ซอย ถนน (ระบุเพิ่มเติม)" />
        </div>
        {/* ลำดับ: แขวง → เขต → จังหวัด → ไปรษณีย์ (2 คอลัมน์ พอดีคอลัมน์ซ้าย) */}
        <AddressAutocomplete label="แขวง/ตำบล" field="subdistrict" value={form.subdistrict||''} onChange={v => set('subdistrict',v)} onSelect={onSelect} placeholder="พิมพ์ชื่อแขวง/ตำบล" />
        <AddressAutocomplete label="เขต/อำเภอ" field="district" value={form.district||''} onChange={v => set('district',v)} onSelect={onSelect} placeholder="พิมพ์ชื่อเขต/อำเภอ" />
        <AddressAutocomplete label="จังหวัด" field="province" value={form.province||''} onChange={v => set('province',v)} onSelect={onSelect} placeholder="พิมพ์ชื่อจังหวัด" />
        <AddressAutocomplete label="รหัสไปรษณีย์" field="zipcode" value={form.zipcode||''} onChange={v => set('zipcode',v)} onSelect={onSelect} placeholder="พิมพ์รหัสไปรษณีย์" />
      </div>
    );
  }

  window.ThaiAddressForm = ThaiAddressForm;
})();
