// ABO Tracking — modals (split from abo.jsx).
// SixWChoice, ConfirmToggle, SponsorPicker, PersonDetail, AddProspect.
// Owns window.AboView export.

// ======================== 6W choice modal ========================
function SixWChoiceModal({ pending, onCancel, onChoose }) {
  // Hooks must always run — keep useEffect ABOVE the early return.
  useEffect(() => {
    if (!pending) return;
    const onKey = (e) => {
      if (e.key === 'Escape') { e.preventDefault(); onCancel(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [pending]);

  if (!pending) return null;
  const { person } = pending;
  const current = person.filled.em6w;
  const isEnrolled = current === 'enrolled' || current === true;
  const isNoEnroll = current === 'noenroll';
  const country = window.COUNTRIES?.find(c => c.id === person.country);

  return (
    <Modal open={true} onClose={onCancel} size="md" title={
      <div className="flex items-center gap-2">
        <div className="w-7 h-7 rounded-md flex items-center justify-center text-white" style={{ background: '#10B981' }}>
          <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className="w-4 h-4">
            <path d="M3 13h18a9 9 0 0 1-18 0z"/>
            <path d="M7 4v3M11.5 3v4M16 4v3"/>
          </svg>
        </div>
        <div>
          <div className="text-sm font-semibold text-ink-900">บันทึกสถานะ 6W · EM6W</div>
          <div className="text-[10px] text-ink-400 uppercase tracking-wider font-semibold">โปรแกรมลดน้ำหนัก 6 สัปดาห์</div>
        </div>
      </div>
    } footer={
      <div className="flex items-center justify-between">
        <span className="text-[10px] text-ink-400">เลือก 1 ตัวเลือก · Esc เพื่อยกเลิก</span>
        <Btn variant="ghost" size="sm" onClick={onCancel}>ยกเลิก</Btn>
      </div>
    }>
      <div className="space-y-3">
        <div className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-ink-50/40">
          <Avatar user={{ avatar: person.name.charAt(person.name.indexOf(' ')+1) || 'ค', color: person.source === 'EM6W' ? '#10B981' : '#2F5DE5' }} size={36} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1.5">
              <span className="text-sm font-semibold text-ink-900 truncate">{person.name}</span>
              {country && <span className="text-sm leading-none">{country.flag}</span>}
            </div>
            <div className="text-[11px] text-ink-500">{person.source === 'EM6W' ? '🥤 EM6W' : '💼 Sponsor'}</div>
          </div>
          {current && (
            <Pill color={isEnrolled ? '#10B981' : '#475569'} tint={isEnrolled ? '#E7F8F1' : '#F1F5F9'} size="xs">
              {isEnrolled ? 'เข้าคอร์ส' : 'ไม่เข้าคอร์ส'}
            </Pill>
          )}
        </div>

        <div className="grid grid-cols-2 gap-3">
          <button
            onClick={() => onChoose('enrolled')}
            className={`relative text-left p-4 rounded-xl border-2 transition-all ${isEnrolled ? 'border-emerald-500 bg-emerald-50/80 shadow-card' : 'border-ink-100 bg-white hover:border-emerald-300 hover:bg-emerald-50/30'}`}>
            <div className="flex items-center gap-2 mb-2">
              <div className="w-10 h-10 rounded-lg bg-emerald-500 flex items-center justify-center">
                <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                  <path d="M3 13h18a9 9 0 0 1-18 0z"/>
                  <path d="M7 4v3M11.5 3v4M16 4v3"/>
                </svg>
              </div>
              {isEnrolled && <Icon name="check" className="w-4 h-4 text-emerald-600 ml-auto" strokeWidth={3} />}
            </div>
            <div className="text-sm font-bold text-emerald-700">เข้าคอร์ส</div>
            <div className="text-[11px] text-ink-500 mt-0.5 leading-snug">ลงทะเบียน EM6W · เริ่มชั่งน้ำหนัก + ใช้ชุด BodyKey</div>
          </button>

          <button
            onClick={() => onChoose('noenroll')}
            className={`relative text-left p-4 rounded-xl border-2 transition-all ${isNoEnroll ? 'border-slate-400 bg-slate-100 shadow-card' : 'border-ink-100 bg-white hover:border-slate-300 hover:bg-slate-50'}`}>
            <div className="flex items-center gap-2 mb-2">
              <div className="w-10 h-10 rounded-lg bg-slate-400 flex items-center justify-center relative">
                <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                  <path d="M3 13h18a9 9 0 0 1-18 0z"/>
                  <path d="M7 4v3M11.5 3v4M16 4v3"/>
                  <line x1="3" y1="21" x2="21" y2="3" stroke="white" strokeWidth="2.5" />
                </svg>
              </div>
              {isNoEnroll && <Icon name="check" className="w-4 h-4 text-slate-600 ml-auto" strokeWidth={3} />}
            </div>
            <div className="text-sm font-bold text-slate-700">ไม่เข้าคอร์ส</div>
            <div className="text-[11px] text-ink-500 mt-0.5 leading-snug">คุยเรื่อง 6W แล้ว แต่ลูกค้าไม่ลงทะเบียน · จะตามใหม่ภายหลัง</div>
          </button>
        </div>

        {current && (
          <button onClick={() => onChoose('unset')}
            className="w-full text-center py-2 text-[11px] font-medium text-rose-600 hover:bg-rose-50 rounded-lg transition-colors">
            ↺ ล้างค่า (ยังไม่ได้คุย)
          </button>
        )}
      </div>
    </Modal>
  );
}

// ======================== Confirm toggle modal ========================
function ConfirmToggleModal({ pending, onCancel, onConfirm }) {
  // Hooks must run on every render — declare them BEFORE any early return.
  const btnRef = React.useRef(null);
  useEffect(() => {
    if (!pending) return;
    const t = setTimeout(() => btnRef.current?.focus(), 30);
    const onKey = (e) => {
      if (e.key === 'Enter') { e.preventDefault(); onConfirm(); }
      if (e.key === 'Escape') { e.preventDefault(); onCancel(); }
    };
    window.addEventListener('keydown', onKey);
    return () => { clearTimeout(t); window.removeEventListener('keydown', onKey); };
  }, [pending]);

  if (!pending) return null;
  const { person, col } = pending;
  const wasFilled = !!person.filled[col.id];
  const group = FU_GROUPS.find(g => g.id === col.groupId);
  const country = window.COUNTRIES?.find(c => c.id === person.country);

  return (
    <Modal open={true} onClose={onCancel} size="sm" title={
      <div className="flex items-center gap-2">
        <div className="w-7 h-7 rounded-md flex items-center justify-center text-white" style={{ background: group.color }}>
          {wasFilled
            ? <Icon name="x" className="w-4 h-4" strokeWidth={2.5} />
            : <Icon name="check" className="w-4 h-4" strokeWidth={2.5} />
          }
        </div>
        <div>
          <div className="text-sm font-semibold text-ink-900">{wasFilled ? 'ยกเลิกการติ๊ก?' : 'บันทึกการติ๊ก?'}</div>
          <div className="text-[10px] text-ink-400 uppercase tracking-wider font-semibold">{group.label}</div>
        </div>
      </div>
    } footer={
      <div className="flex items-center justify-between">
        <span className="text-[10px] text-ink-400">Enter เพื่อยืนยัน · Esc เพื่อยกเลิก</span>
        <div className="flex items-center gap-2">
          <Btn variant="ghost" size="sm" onClick={onCancel}>ยกเลิก</Btn>
          {wasFilled ? (
            <button ref={btnRef} onClick={onConfirm}
              className="h-9 px-3.5 text-sm font-medium rounded-lg bg-rose-500 text-white hover:bg-rose-600 transition-all inline-flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-rose-500/30">
              <Icon name="x" className="w-3.5 h-3.5" strokeWidth={2.5} /> ยกเลิกการติ๊ก
            </button>
          ) : (
            <button ref={btnRef} onClick={onConfirm}
              className="h-9 px-3.5 text-sm font-medium rounded-lg text-white transition-all inline-flex items-center gap-1.5 focus:outline-none focus:ring-2"
              style={{ background: group.color, '--tw-ring-color': group.color + '4D' }}>
              <Icon name="check" className="w-3.5 h-3.5" strokeWidth={2.5} /> บันทึก
            </button>
          )}
        </div>
      </div>
    }>
      <div className="space-y-3">
        <div className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-ink-50/40">
          <Avatar user={{ avatar: person.name.charAt(person.name.indexOf(' ')+1) || 'ค', color: person.source === 'EM6W' ? '#10B981' : '#2F5DE5' }} size={36} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1.5">
              <span className="text-sm font-semibold text-ink-900 truncate">{person.name}</span>
              {country && <span className="text-sm leading-none">{country.flag}</span>}
            </div>
            <div className="text-[11px] text-ink-500">{person.source === 'EM6W' ? '🥤 EM6W' : '💼 Sponsor'}</div>
          </div>
        </div>

        <div className="rounded-xl border p-3" style={{ borderColor: group.color + '40', background: group.color + '0A' }}>
          <div className="text-[10px] uppercase tracking-wider font-semibold mb-1" style={{ color: group.color }}>{group.label}</div>
          <div className="flex items-center gap-2">
            <div className="w-6 h-6 rounded flex items-center justify-center flex-shrink-0" style={{ background: wasFilled ? '#F1F5F9' : group.color }}>
              {!wasFilled && <Icon name="check" className="w-3.5 h-3.5 text-white" strokeWidth={3} />}
              {wasFilled && <Icon name="check" className="w-3.5 h-3.5 text-ink-500" strokeWidth={3} />}
            </div>
            <Icon name="arrowR" className="w-3 h-3 text-ink-300" />
            <div className="w-6 h-6 rounded flex items-center justify-center flex-shrink-0" style={{ background: wasFilled ? '#F1F5F9' : group.color }}>
              {wasFilled
                ? <div className="w-3 h-0.5 bg-ink-400 rounded" />
                : <Icon name="check" className="w-3.5 h-3.5 text-white" strokeWidth={3} />
              }
            </div>
            <span className="text-sm font-medium text-ink-900 ml-1">{col.label}</span>
          </div>
        </div>

        <div className="text-xs text-ink-600 leading-relaxed">
          {wasFilled
            ? <>กำลังจะ <span className="font-semibold text-rose-600">ยกเลิก</span> การติ๊กรายการนี้ — ระบบจะเอาเครื่องหมายออกและบันทึก log ไว้</>
            : <>กำลังจะ <span className="font-semibold" style={{ color: group.color }}>บันทึก</span> ว่า <span className="font-semibold">{person.name}</span> ทำขั้นตอน <span className="font-semibold">{col.label}</span> แล้ว</>
          }
        </div>
      </div>
    </Modal>
  );
}

// ======================== Sponsor (DL-of) picker ========================
// Pick which other person in the sheet `person` is a downline of. Each
// candidate row shows quick contact info (IG / source link / ABO / 6W LINE
// group) so the user can confirm who they're linking before picking.
function SponsorPickerModal({ person, people, onClose, onPick }) {
  const [q, setQ] = useState('');
  useEffect(() => { if (person) setQ(''); }, [person]);
  if (!person) return null;

  const term = q.trim().toLowerCase();
  // Candidates = everyone except the person themself (avoid self-sponsor).
  const candidates = (people || [])
    .filter(c => c.id !== person.id)
    .filter(c => !term || c.name.toLowerCase().includes(term) || (c.abo_code || '').includes(term));

  const igUrl = (c) => c.sourceUrl || (c.igHandle ? `https://instagram.com/${c.igHandle}` : null);

  return (
    <Modal open={!!person} onClose={onClose} size="md"
      title={
        <div>
          <div className="text-sm font-semibold text-ink-900">เลือกว่า <span className="text-brand-700">{person.name}</span> เป็น DL ของใคร</div>
          <div className="text-[11px] text-ink-400 mt-0.5">แตะคนที่เป็น upline · ดูข้อมูล IG / ลิงก์ก่อนเลือกได้</div>
        </div>
      }
      footer={
        <div className="flex items-center justify-between">
          <button onClick={() => onPick(null)}
            className="text-xs font-medium text-rose-500 hover:text-rose-700">ล้าง DL (ไม่มี upline)</button>
          <Btn variant="ghost" size="sm" onClick={onClose}>ปิด</Btn>
        </div>
      }>
      <div className="mb-2">
        <input value={q} onChange={e => setQ(e.target.value)} autoFocus
          placeholder="ค้นหาชื่อ หรือ รหัส ABO…"
          className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
      </div>
      <div className="space-y-1.5 max-h-[420px] overflow-y-auto scroll-thin">
        {candidates.length === 0 && (
          <div className="text-center py-8 text-[12px] text-ink-400">ไม่พบรายชื่อ</div>
        )}
        {candidates.map(c => {
          const isCur = person.sponsorId === c.id;
          const url = igUrl(c);
          return (
            <div key={c.id}
              className={`flex items-center gap-3 p-2.5 rounded-lg border transition-all ${
                isCur ? 'bg-amber-50 border-amber-200 ring-1 ring-amber-200' : 'border-ink-100 hover:bg-ink-50'
              }`}>
              <button onClick={() => onPick(c.id)} className="flex items-center gap-3 flex-1 min-w-0 text-left">
                <Avatar user={{ avatar: c.name.charAt(c.name.indexOf(' ')+1) || c.name.charAt(0) || 'ค', color: c.source === 'EM6W' ? '#10B981' : '#2F5DE5' }} size={34} />
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-ink-900 truncate flex items-center gap-1.5">
                    {c.name}
                    {isCur && <Pill color="#B45309" tint="#FEF3C7" size="xs">DL ปัจจุบัน</Pill>}
                  </div>
                  <div className="text-[11px] text-ink-500 flex items-center gap-2 flex-wrap mt-0.5">
                    <span>{c.source === 'EM6W' ? '🥤 EM6W' : '💼 Sponsor'}</span>
                    {c.abo_code && <span className="num tracking-wide">ABO {c.abo_code}</span>}
                    {c.igHandle && <span className="text-pink-600">@{c.igHandle}</span>}
                    {c.age != null && <span>· {c.age} ปี</span>}
                  </div>
                </div>
              </button>
              {/* Info links — open without selecting. */}
              <div className="flex items-center gap-1 flex-shrink-0">
                {url && (
                  <a href={url} target="_blank" rel="noopener noreferrer" title="เปิดโปรไฟล์ / ลิงก์ที่มา"
                    className="w-7 h-7 rounded-md flex items-center justify-center text-pink-600 hover:bg-pink-50">
                    <Icon name="arrowR" className="w-3.5 h-3.5" />
                  </a>
                )}
                {c.lineGroupUrl && (
                  <a href={c.lineGroupUrl} target="_blank" rel="noopener noreferrer" title="เปิดกลุ่ม LINE"
                    className="w-7 h-7 rounded-md flex items-center justify-center text-white" style={{ background: '#06C755' }}>
                    <Icon name="line" className="w-3.5 h-3.5" />
                  </a>
                )}
                <button onClick={() => onPick(c.id)}
                  className={`px-2.5 h-7 rounded-md text-[11px] font-semibold ${isCur ? 'bg-amber-400 text-white' : 'bg-brand-500 text-white hover:bg-brand-600'}`}>
                  {isCur ? '✓' : 'เลือก'}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </Modal>
  );
}

// ======================== Add prospect modal ========================
// ======================== Edit person modal (name + ABO) ========================
// Full prospect detail — opens when a name is clicked. Shows + edits the
// info captured at add-time: name, ABO, lead source + link, age, occupation,
// note, photo.
function PersonDetailModal({ person, onCancel, onSubmit }) {
  const [name, setName] = useState('');
  const [abo, setAbo] = useState('');
  const [leadSource, setLeadSource] = useState('');
  const [sourceUrl, setSourceUrl] = useState('');
  const [age, setAge] = useState('');
  const [occupation, setOccupation] = useState('');
  const [note, setNote] = useState('');
  const [photo, setPhoto] = useState(null);
  const photoInputRef = React.useRef(null);
  const leadSources = window.LEAD_SOURCES || [];

  useEffect(() => {
    if (!person) return;
    setName(person.name || '');
    setAbo(person.abo_code || '');
    setLeadSource(person.leadSource || '');
    setSourceUrl(person.sourceUrl || '');
    setAge(person.age != null ? String(person.age) : '');
    setOccupation(person.occupation || '');
    setNote(person.notes || '');
    setPhoto(person.photoUrl || null);
    const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); onCancel(); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [person?.id]);

  if (!person) return null;
  const onPhoto = (e) => {
    const f = e.target.files?.[0]; if (!f) return;
    const r = new FileReader(); r.onload = () => setPhoto(r.result); r.readAsDataURL(f); e.target.value = '';
  };
  const aboValid = abo.length === 0 || /^\d{10}$/.test(abo);
  const canSubmit = name.trim().length > 0 && aboValid;
  const openUrl = sourceUrl.trim() || (person.igHandle ? `https://instagram.com/${person.igHandle}` : null);
  const submit = (e) => {
    e?.preventDefault?.();
    if (!canSubmit) return;
    onSubmit({
      name: name.trim(), abo_code: abo || null,
      source_id: leadSource || null,
      source_url: sourceUrl.trim() || null,
      age: age.trim() === '' ? null : Math.max(0, Math.min(130, parseInt(age, 10) || 0)),
      occupation: occupation.trim() || null,
      notes: note.trim() || null,
      photo_url: photo || null,
    });
  };

  return (
    <Modal open={true} onClose={onCancel} size="sm" title={
      <div className="flex items-center gap-2">
        {photo
          ? <img src={photo} alt="" className="w-8 h-8 rounded-lg object-cover" />
          : <div className="w-8 h-8 rounded-lg flex items-center justify-center text-white bg-brand-500"><Icon name="user" className="w-4 h-4" strokeWidth={2.5} /></div>}
        <div>
          <div className="text-sm font-semibold text-ink-900">{person.name}</div>
          <div className="text-[10px] text-ink-400 uppercase tracking-wider font-semibold">ข้อมูล Prospect</div>
        </div>
      </div>
    } footer={
      <div className="flex items-center justify-between">
        <span className="text-[10px] text-ink-400">Esc เพื่อปิด</span>
        <div className="flex items-center gap-2">
          <Btn variant="ghost" size="sm" onClick={onCancel}>ยกเลิก</Btn>
          <button onClick={submit} disabled={!canSubmit}
            className="h-9 px-3.5 text-sm font-medium rounded-lg bg-brand-500 text-white hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed inline-flex items-center gap-1.5">
            <Icon name="check" className="w-3.5 h-3.5" strokeWidth={2.5} /> บันทึก
          </button>
        </div>
      </div>
    }>
      <form onSubmit={submit} className="space-y-3">
        {/* Photo */}
        <div className="flex items-center gap-3">
          <input ref={photoInputRef} type="file" accept="image/*" onChange={onPhoto} className="hidden" />
          {photo
            ? <img src={photo} alt="" className="w-16 h-16 rounded-xl object-cover border border-ink-200 flex-shrink-0" />
            : <div className="w-16 h-16 rounded-xl bg-ink-50 border border-ink-200 flex items-center justify-center text-ink-300 flex-shrink-0"><Icon name="user" className="w-7 h-7" /></div>}
          <div className="flex flex-col gap-1">
            <button type="button" onClick={() => photoInputRef.current?.click()}
              className="text-[12px] font-medium text-brand-600 hover:underline text-left">{photo ? 'เปลี่ยนรูป' : 'แนบรูป'}</button>
            {photo && <button type="button" onClick={() => setPhoto(null)} className="text-[12px] font-medium text-rose-500 hover:underline text-left">ลบรูป</button>}
          </div>
        </div>

        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">ชื่อ</label>
          <input value={name} onChange={e => setName(e.target.value)}
            className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
        </div>

        <div>
          <label className="flex items-center justify-between text-[11px] font-semibold text-ink-600 mb-1">
            <span>เลข ABO <span className="text-ink-400 font-normal">(10 หลัก · ไม่ใส่ก็ได้)</span></span>
            <span className={`text-[10px] num ${abo.length === 10 ? 'text-emerald-600' : abo.length > 0 ? 'text-amber-600' : 'text-ink-300'}`}>{abo.length}/10</span>
          </label>
          <input value={abo} onChange={e => setAbo(e.target.value.replace(/\D/g, '').slice(0, 10))}
            placeholder="0000000000" inputMode="numeric" maxLength={10}
            className={`w-full h-9 px-3 text-sm num tracking-wider border rounded-lg outline-none focus:ring-2 ${!aboValid ? 'border-rose-300 focus:border-rose-500 focus:ring-rose-500/15' : 'border-ink-200 focus:border-brand-500 focus:ring-brand-500/15'}`} />
          {!aboValid && <p className="mt-1 text-[10px] text-rose-600">ต้องเป็นตัวเลข 10 หลักเท่านั้น</p>}
        </div>

        {/* Lead source + link */}
        <div>
          <label className="flex items-center justify-between text-[11px] font-semibold text-ink-600 mb-1">
            <span>แหล่งที่มา (Lead Source)</span>
            {openUrl && <a href={openUrl} target="_blank" rel="noopener noreferrer" className="text-[11px] font-semibold text-brand-600 hover:underline inline-flex items-center gap-0.5"><Icon name="arrowR" className="w-3 h-3" />เปิดลิงก์</a>}
          </label>
          <div className="flex flex-wrap gap-1.5 mb-2">
            {leadSources.map(s => {
              const active = leadSource === s.id;
              return (
                <button type="button" key={s.id} onClick={() => setLeadSource(active ? '' : s.id)}
                  className="px-2.5 h-7 rounded-md text-[11px] font-medium border-2 transition-all inline-flex items-center gap-1"
                  style={active ? { borderColor: s.color, background: (s.color || '#2F5DE5') + '14', color: s.color } : { borderColor: '#E6EAF3', background: 'white', color: '#445576' }}>
                  <span className="w-1.5 h-1.5 rounded-full" style={{ background: s.color || '#CBD5E1' }} />{s.label}
                </button>
              );
            })}
          </div>
          <input type="url" value={sourceUrl} onChange={e => setSourceUrl(e.target.value)}
            placeholder="แนบลิงก์ profile / โพสต์" inputMode="url"
            className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
        </div>

        <div className="grid grid-cols-2 gap-2">
          <div>
            <label className="block text-[11px] font-semibold text-ink-600 mb-1">อายุ</label>
            <input value={age} onChange={e => setAge(e.target.value.replace(/\D/g, '').slice(0, 3))} placeholder="—" inputMode="numeric"
              className="w-full h-9 px-3 text-sm num border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
          </div>
          <div>
            <label className="block text-[11px] font-semibold text-ink-600 mb-1">อาชีพ</label>
            <input value={occupation} onChange={e => setOccupation(e.target.value)} placeholder="—"
              className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
          </div>
        </div>

        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">โน้ต · เป็นใคร</label>
          <textarea value={note} onChange={e => setNote(e.target.value)} rows={3} placeholder="รายละเอียด / สิ่งที่ต้องตามต่อ"
            className="w-full px-3 py-2 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15 resize-none" />
        </div>

        <button type="submit" className="hidden" />
      </form>
    </Modal>
  );
}

function AddProspectModal({ open, onCancel, onSubmit }) {
  const [name, setName] = useState('');
  const [aboCode, setAboCode] = useState('');
  const [source, setSource] = useState('Sponsor');
  const [country, setCountry] = useState('th');
  const [leadSource, setLeadSource] = useState('');  // source_id from LEAD_SOURCES
  const [sourceUrl, setSourceUrl] = useState('');     // link to their profile / post
  const [age, setAge] = useState('');
  const [occupation, setOccupation] = useState('');
  const [note, setNote] = useState('');
  const [photo, setPhoto] = useState(null);           // data URL
  const nameRef = React.useRef(null);
  const photoInputRef = React.useRef(null);
  const leadSources = window.LEAD_SOURCES || [];

  const onPhoto = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => setPhoto(r.result);
    r.readAsDataURL(f);
    e.target.value = '';
  };

  useEffect(() => {
    if (!open) return;
    setName('');
    setAboCode('');
    setSource('Sponsor');
    setCountry('th');
    setLeadSource('');
    setSourceUrl('');
    setAge('');
    setOccupation('');
    setNote('');
    setPhoto(null);
    const t = setTimeout(() => nameRef.current?.focus(), 30);
    const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); onCancel(); } };
    window.addEventListener('keydown', onKey);
    return () => { clearTimeout(t); window.removeEventListener('keydown', onKey); };
  }, [open]);

  // ABO code is optional; if present must be exactly 10 digits.
  const aboValid = aboCode.length === 0 || /^\d{10}$/.test(aboCode);
  const canSubmit = name.trim().length > 0 && aboValid;
  const submit = (e) => {
    e?.preventDefault?.();
    if (!canSubmit) return;
    onSubmit({
      name: name.trim(), abo_code: aboCode || null, source, country,
      source_id: leadSource || null,
      source_url: sourceUrl.trim() || null,
      age: age.trim() === '' ? null : Math.max(0, Math.min(130, parseInt(age, 10) || 0)),
      occupation: occupation.trim() || null,
      notes: note.trim() || null,
      photo_url: photo || null,
    });
  };

  if (!open) return null;
  const countries = window.COUNTRIES || [
    { id: 'th', label: 'ไทย', flag: '🇹🇭' },
    { id: 'au', label: 'ออสเตรเลีย', flag: '🇦🇺' },
    { id: 'nz', label: 'นิวซีแลนด์', flag: '🇳🇿' },
    { id: 'us', label: 'อเมริกา', flag: '🇺🇸' },
  ];

  return (
    <Modal open={true} onClose={onCancel} size="sm" title={
      <div className="flex items-center gap-2">
        <div className="w-7 h-7 rounded-md flex items-center justify-center text-white bg-brand-500">
          <Icon name="plus" className="w-4 h-4" strokeWidth={2.5} />
        </div>
        <div>
          <div className="text-sm font-semibold text-ink-900">เพิ่มคนเข้า Follow Up</div>
          <div className="text-[10px] text-ink-400 uppercase tracking-wider font-semibold">Sponsor & EM6W</div>
        </div>
      </div>
    } footer={
      <div className="flex items-center justify-between">
        <span className="text-[10px] text-ink-400">Enter เพื่อบันทึก · Esc เพื่อยกเลิก</span>
        <div className="flex items-center gap-2">
          <Btn variant="ghost" size="sm" onClick={onCancel}>ยกเลิก</Btn>
          <button
            onClick={submit}
            disabled={!canSubmit}
            className="h-9 px-3.5 text-sm font-medium rounded-lg bg-brand-500 text-white hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed inline-flex items-center gap-1.5">
            <Icon name="check" className="w-3.5 h-3.5" strokeWidth={2.5} /> เพิ่ม
          </button>
        </div>
      </div>
    }>
      <form onSubmit={submit} className="space-y-3">
        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">ชื่อ</label>
          <input
            ref={nameRef}
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="เช่น คุณวริศรา ม."
            className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15"
          />
        </div>

        <div>
          <label className="flex items-center justify-between text-[11px] font-semibold text-ink-600 mb-1">
            <span>เลข ABO <span className="text-ink-400 font-normal">(10 หลัก · ไม่ใส่ก็ได้)</span></span>
            <span className={`text-[10px] num ${aboCode.length === 10 ? 'text-emerald-600' : aboCode.length > 0 ? 'text-amber-600' : 'text-ink-300'}`}>
              {aboCode.length}/10
            </span>
          </label>
          <input
            value={aboCode}
            onChange={e => setAboCode(e.target.value.replace(/\D/g, '').slice(0, 10))}
            placeholder="0000000000"
            inputMode="numeric"
            maxLength={10}
            className={`w-full h-9 px-3 text-sm num tracking-wider border rounded-lg outline-none focus:ring-2 ${
              !aboValid
                ? 'border-rose-300 focus:border-rose-500 focus:ring-rose-500/15'
                : 'border-ink-200 focus:border-brand-500 focus:ring-brand-500/15'
            }`}
          />
          {!aboValid && (
            <p className="mt-1 text-[10px] text-rose-600">ต้องเป็นตัวเลข 10 หลักเท่านั้น</p>
          )}
        </div>

        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">แหล่งที่มา</label>
          <div className="grid grid-cols-2 gap-2">
            {[
              { id: 'Sponsor', label: '💼 Sponsor', desc: 'มาจากการ Sponsor ตรง', color: '#2F5DE5' },
              { id: 'EM6W',    label: '🥤 EM6W',    desc: 'ผ่านโปรแกรม 6W',        color: '#10B981' },
            ].map(opt => {
              const active = source === opt.id;
              return (
                <button
                  type="button"
                  key={opt.id}
                  onClick={() => setSource(opt.id)}
                  className={`text-left p-2.5 rounded-lg border-2 transition-all ${active ? 'shadow-card' : 'border-ink-100 hover:border-ink-200'}`}
                  style={{ borderColor: active ? opt.color : undefined, background: active ? opt.color + '10' : 'white' }}>
                  <div className="text-xs font-bold" style={{ color: active ? opt.color : '#0F1E38' }}>{opt.label}</div>
                  <div className="text-[10px] text-ink-500 leading-tight mt-0.5">{opt.desc}</div>
                </button>
              );
            })}
          </div>
        </div>

        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">ประเทศ</label>
          <div className="grid grid-cols-4 gap-2">
            {countries.map(c => {
              const active = country === c.id;
              return (
                <button
                  type="button"
                  key={c.id}
                  onClick={() => setCountry(c.id)}
                  className={`flex flex-col items-center justify-center gap-0.5 py-2 rounded-lg border-2 transition-all ${active ? 'border-brand-500 bg-brand-50/60' : 'border-ink-100 hover:border-ink-200'}`}>
                  <span className="text-base leading-none">{c.flag}</span>
                  <span className="text-[10px] font-medium text-ink-700">{c.label}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Lead source (IG/FB/…) + link */}
        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">แหล่งที่มา (Lead Source)</label>
          <div className="flex flex-wrap gap-1.5 mb-2">
            {leadSources.map(s => {
              const active = leadSource === s.id;
              return (
                <button type="button" key={s.id} onClick={() => setLeadSource(active ? '' : s.id)}
                  className="px-2.5 h-7 rounded-md text-[11px] font-medium border-2 transition-all inline-flex items-center gap-1"
                  style={active ? { borderColor: s.color, background: (s.color || '#2F5DE5') + '14', color: s.color }
                                : { borderColor: '#E6EAF3', background: 'white', color: '#445576' }}>
                  <span className="w-1.5 h-1.5 rounded-full" style={{ background: s.color || '#CBD5E1' }} />
                  {s.label}
                </button>
              );
            })}
          </div>
          <input type="url" value={sourceUrl} onChange={e => setSourceUrl(e.target.value)}
            placeholder="แนบลิงก์ profile / โพสต์ (ไม่บังคับ)"
            inputMode="url"
            className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
        </div>

        {/* Age + occupation */}
        <div className="grid grid-cols-2 gap-2">
          <div>
            <label className="block text-[11px] font-semibold text-ink-600 mb-1">อายุ</label>
            <input value={age} onChange={e => setAge(e.target.value.replace(/\D/g, '').slice(0, 3))}
              placeholder="เช่น 28" inputMode="numeric"
              className="w-full h-9 px-3 text-sm num border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
          </div>
          <div>
            <label className="block text-[11px] font-semibold text-ink-600 mb-1">อาชีพ</label>
            <input value={occupation} onChange={e => setOccupation(e.target.value)}
              placeholder="เช่น พยาบาล"
              className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15" />
          </div>
        </div>

        {/* Note */}
        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">โน้ต · เป็นใคร</label>
          <textarea value={note} onChange={e => setNote(e.target.value)} rows={2}
            placeholder="เช่น เพื่อนพี่เมย์ · สนใจสุขภาพ · ทักมาจากโพสต์ลดน้ำหนัก"
            className="w-full px-3 py-2 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15 resize-none" />
        </div>

        {/* Photo */}
        <div>
          <label className="block text-[11px] font-semibold text-ink-600 mb-1">รูป (ไม่บังคับ)</label>
          <input ref={photoInputRef} type="file" accept="image/*" onChange={onPhoto} className="hidden" />
          {photo ? (
            <div className="flex items-center gap-2">
              <img src={photo} alt="" className="w-14 h-14 rounded-lg object-cover border border-ink-200" />
              <button type="button" onClick={() => photoInputRef.current?.click()}
                className="text-[11px] font-medium text-brand-600 hover:underline">เปลี่ยนรูป</button>
              <button type="button" onClick={() => setPhoto(null)}
                className="text-[11px] font-medium text-rose-500 hover:underline">ลบรูป</button>
            </div>
          ) : (
            <button type="button" onClick={() => photoInputRef.current?.click()}
              className="w-full h-10 rounded-lg border-2 border-dashed border-ink-200 text-ink-400 text-xs font-medium hover:border-brand-400 hover:text-brand-600 inline-flex items-center justify-center gap-1.5">
              <Icon name="plus" className="w-4 h-4" /> แนบรูป
            </button>
          )}
        </div>

        <button type="submit" className="hidden" />
      </form>
    </Modal>
  );
}

window.AboView = AboView;
