/* CustomerDrawer (CRM Phase 2) — มุมมองราย "ลูกค้า": รวมทุกลีดของเบอร์เดียว + timeline รวม
   ใช้ได้ทุกหน้า: window.CustomerDrawer({ phone, userId, name, onClose }) */
(function() {
  const { useState, useEffect } = React;

  const STAGES = {
    new: ['ใหม่', 'badge-yellow'], contacted: ['ติดต่อแล้ว', 'badge-blue'],
    appointment: ['นัดคุย', 'badge-purple'], proposal: ['เสนอดีล', 'badge-blue'],
    negotiation: ['เจรจา', 'badge-yellow'], won: ['ปิดการขาย', 'badge-green'], lost: ['ไม่สำเร็จ', 'badge-red'],
  };
  const stageLabel = (s) => (STAGES[s] || [s || '-'])[0];
  const stageBadge = (s) => { const m = STAGES[s] || ['-', 'badge-gray']; return <span className={'badge ' + m[1]}>{m[0]}</span>; };
  // กลุ่มลีด: ไอคอน · สี · ป้ายกำกับ
  const KIND = {
    investor: ['ph-trend-up', '#2A6BE0', 'สนใจลงทุน'],
    buyer: ['ph-house', '#15976A', 'สนใจซื้อทรัพย์'],
    matching: ['ph-hand-coins', '#B5860B', 'ขอเงินทุน (เจ้าของทรัพย์)'],
  };
  const KYC = {
    no_account: ['badge-red', 'ยังไม่สมัคร'], unverified: ['badge-yellow', 'ยังไม่ทำ'],
    pending: ['badge-blue', 'รอตรวจ'], rejected: ['badge-red', 'ไม่ผ่าน'], verified: ['badge-green', 'ผ่านแล้ว'],
  };
  const fmtDT = (ts) => ts ? new Date(ts).toLocaleString('th-TH', { dateStyle: 'medium', timeStyle: 'short' }) : '';
  const fmtD = (ts) => ts ? new Date(ts).toLocaleDateString('th-TH', { dateStyle: 'medium' }) : '';
  const money = (n) => n ? Number(n).toLocaleString() + ' ฿' : null;

  function CustomerDrawer({ phone, userId, name, onClose, onOpenListing }) {
    const [d, setD] = useState(null);
    const [loading, setLoading] = useState(true);
    const [err, setErr] = useState(null);

    useEffect(() => {
      setLoading(true); setErr(null);
      window.api.customerLookup(phone, userId)
        .then(setD).catch(e => setErr(e.message || 'โหลดไม่สำเร็จ')).finally(() => setLoading(false));
    }, [phone, userId]);

    // ปิดด้วย ESC
    useEffect(() => {
      const h = (e) => { if (e.key === 'Escape') onClose(); };
      window.addEventListener('keydown', h);
      return () => window.removeEventListener('keydown', h);
    }, []);

    const leads = (d && d.leads) || [];
    const profile = (d && d.profile) || {};

    // ไทม์ไลน์รวม: การสร้างลีด + กิจกรรมติดตาม (lead_activities) เรียงใหม่→เก่า
    const events = [];
    leads.forEach(l => {
      const k = KIND[l.kind] || KIND.buyer;
      let label = k[2];
      if (l.kind === 'matching') label = 'ยื่นขอเงินทุน' + (l.asset_type ? ' · ' + l.asset_type : '');
      else label = k[2] + (l.listing_title ? ' · ' + l.listing_title : (l.listing_code ? ' · #' + l.listing_code : ''));
      events.push({ at: l.created_at, icon: k[0], color: k[1], text: label });
      if (Number(l.interest_count) > 1)
        events.push({ at: l.last_interest_at || l.created_at, icon: 'ph-bell-ringing', color: '#C0344F', text: 'กดสนใจซ้ำ รวม ' + l.interest_count + ' ครั้ง' });
    });
    (d && d.activities || []).forEach(a => {
      let text = a.from_status && a.to_status
        ? 'เปลี่ยนสถานะ: ' + stageLabel(a.from_status) + ' → ' + stageLabel(a.to_status)
        : (a.note ? 'บันทึกโน้ต' : 'อัปเดต');
      if (a.listing_title) text += ' · ' + a.listing_title;
      events.push({ at: a.created_at, icon: 'ph-note-pencil', color: '#4A6079', text, note: a.note, by: a.user_name });
    });
    events.sort((x, y) => new Date(y.at) - new Date(x.at));

    const kyc = profile.kyc && KYC[profile.kyc];

    return (
      <div className="cust-overlay" onClick={onClose}>
        <div className="cust-drawer" onClick={e => e.stopPropagation()}>
          <div className="cust-head">
            <div>
              <div style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 600 }}><i className="ph ph-user-circle" style={{ marginRight: 5 }}></i>โปรไฟล์ลูกค้า</div>
              <h3 style={{ fontSize: 18, fontWeight: 700, marginTop: 3 }}>{profile.name || name || 'ลูกค้า'}</h3>
            </div>
            <button className="modal-close" onClick={onClose} aria-label="ปิด"><i className="ph ph-x"></i></button>
          </div>

          <div className="cust-body">
            {loading && <div style={{ padding: 30, textAlign: 'center', color: 'var(--text-2)' }}>กำลังโหลด…</div>}
            {err && <div style={{ padding: 16, color: '#C0344F' }}>เกิดข้อผิดพลาด: {err}</div>}
            {d && (
              <React.Fragment>
                {/* ระบุตัว */}
                <div className="cust-idcard">
                  {(profile.phone) && <a href={'tel:' + profile.phone} className="cust-chip"><i className="ph ph-phone"></i>{profile.phone}</a>}
                  {profile.email && <a href={'mailto:' + profile.email} className="cust-chip"><i className="ph ph-envelope-simple"></i>{profile.email}</a>}
                  {kyc && <span className={'badge ' + kyc[0]}>KYC: {kyc[1]}</span>}
                  <span className="cust-chip" style={{ background: '#EEF3F9' }}><i className="ph ph-stack"></i>{profile.total} รายการที่เกี่ยวข้อง</span>
                </div>

                {/* ทรัพย์/คำขอที่เกี่ยวข้อง */}
                <div className="cust-sec-title">ทรัพย์ / คำขอที่เกี่ยวข้อง ({leads.length})</div>
                {leads.length === 0 && <div style={{ color: 'var(--text-2)', fontSize: 13 }}>ไม่มีรายการ</div>}
                {leads.map((l, i) => {
                  const k = KIND[l.kind] || KIND.buyer;
                  const overdue = l.next_action_at && new Date(l.next_action_at).toISOString().slice(0, 10) < new Date().toISOString().slice(0, 10);
                  const canOpen = l.kind !== 'matching' && l.listing_id && onOpenListing;
                  return (
                    <div className={'cust-lead' + (canOpen ? ' cust-lead-link' : '')} key={l.kind + l.id + i}
                      onClick={canOpen ? () => onOpenListing(l.listing_id, l.listing_type) : undefined}
                      title={canOpen ? 'เปิดหน้าจัดการทรัพย์นี้' : ''}>
                      <div className="cust-lead-icon" style={{ background: k[1] + '18', color: k[1] }}><i className={'ph ' + k[0]}></i></div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 11, fontWeight: 700, color: k[1] }}>{k[2]}{canOpen && <i className="ph ph-arrow-square-out" style={{ marginLeft: 5, fontSize: 12, opacity: .7 }}></i>}</div>
                        <div style={{ fontWeight: 600, marginTop: 1 }}>
                          {l.kind === 'matching'
                            ? (l.asset_type || 'ขอเงินทุน') + (money(l.amount_needed) ? ' · ' + money(l.amount_needed) : '')
                            : (l.listing_title || 'ทรัพย์') }
                        </div>
                        <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 1, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                          {l.listing_code && <span style={{ fontFamily: 'monospace', color: 'var(--blue)' }}>#{l.listing_code}</span>}
                          {l.province && <span>{l.province}</span>}
                          {l.kind !== 'matching' && money(l.price) && <span>{money(l.price)}</span>}
                          <span>· {fmtD(l.created_at)}</span>
                        </div>
                        <div style={{ marginTop: 5, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                          {stageBadge(l.stage)}
                          <span style={{ fontSize: 12, color: 'var(--text-2)' }}>
                            <i className="ph ph-user" style={{ marginRight: 3 }}></i>{l.assigned_name || 'ยังไม่มอบหมาย'}
                          </span>
                          {l.next_action_at && (
                            <span style={{ fontSize: 12, fontWeight: 600, color: overdue ? '#C0344F' : '#8A6D1B' }}>
                              <i className="ph ph-calendar-dot" style={{ marginRight: 3 }}></i>{fmtD(l.next_action_at)}{overdue ? ' (เกินกำหนด)' : ''}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}

                {/* ไทม์ไลน์รวม */}
                <div className="cust-sec-title" style={{ marginTop: 20 }}>ไทม์ไลน์การติดตาม ({events.length})</div>
                {events.length === 0 && <div style={{ color: 'var(--text-2)', fontSize: 13 }}>ยังไม่มีความเคลื่อนไหว</div>}
                <div className="cust-timeline">
                  {events.map((e, i) => (
                    <div className="cust-tl-item" key={i}>
                      <div className="cust-tl-dot" style={{ color: e.color }}><i className={'ph ' + e.icon}></i></div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13.5, fontWeight: 500 }}>{e.text}</div>
                        {e.note && <div style={{ fontSize: 12.5, color: 'var(--text-2)', marginTop: 2, background: '#F6F8FB', borderRadius: 8, padding: '5px 9px' }}>“{e.note}”</div>}
                        <div style={{ fontSize: 11.5, color: 'var(--text-2)', marginTop: 2 }}>{fmtDT(e.at)}{e.by ? ' · โดย ' + e.by : ''}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </React.Fragment>
            )}
          </div>
        </div>
      </div>
    );
  }

  window.CustomerDrawer = CustomerDrawer;
})();
