/* หน้าหลังบ้าน: คิวทรัพย์ที่คนภายนอกส่งเข้ามา — รีวิว/แก้ไข/อนุมัติ→เพิ่มทรัพย์/ปฏิเสธ */
(function () {
  const { useState, useEffect } = React;

  const STATUS = {
    new: ['#B5860B', '#FBF0D0', 'ใหม่'],
    reviewing: ['#1F58C4', '#DCE9FC', 'กำลังตรวจ'],
    approved: ['#15976A', '#DBF1E7', 'อนุมัติแล้ว'],
    rejected: ['#D8567A', '#FBE4EC', 'ปฏิเสธ'],
  };
  function SBadge({ s }) {
    const m = STATUS[s] || ['#555', '#eee', s];
    return <span style={{ background: m[1], color: m[0], padding: '3px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap' }}>{m[2]}</span>;
  }
  const baht = (v) => v == null || v === '' ? '-' : Number(v).toLocaleString() + ' ฿';
  const catLabel = (c) => c === 'invest' ? 'ลงทุน' : 'ทรัพย์ฝากขาย';
  const typeLabel = (t) => ({ sale: 'ขายขาด', mortgage: 'จำนอง', consignment: 'ขายฝาก' }[t] || t || '-');

  function SubmissionsPage({ embedded }) {
    const [tab, setTab] = useState('all');
    const [rows, setRows] = useState([]);
    const [loading, setLoading] = useState(true);
    const [active, setActive] = useState(null);

    function load() {
      setLoading(true);
      window.api.submissions(tab === 'all' ? '' : tab)
        .then(d => { setRows(d.submissions || []); setLoading(false); })
        .catch(() => setLoading(false));
    }
    useEffect(load, [tab]);

    const tabs = [
      { id: 'all', label: 'ทั้งหมด' },
      { id: 'new', label: 'ใหม่' },
      { id: 'approved', label: 'อนุมัติแล้ว' }, { id: 'rejected', label: 'ปฏิเสธ' },
    ];

    const cols = [
      { label: 'ทรัพย์', sortKey: 'title', render: r => <span className="text-bold">{r.title || '(ไม่มีชื่อ)'}</span> },
      { label: 'หมวด', sortKey: 'deal_category', render: r => <span style={{ fontWeight: 600, color: r.deal_category === 'invest' ? '#B5860B' : '#15976A' }}>{catLabel(r.deal_category)}</span> },
      { label: 'ประเภท', sortKey: 'listing_type', render: r => typeLabel(r.listing_type) },
      { label: 'ทำเล', sortKey: 'province', render: r => r.province || '-' },
      { label: 'ราคา/มูลค่า', sortKey: 'price', render: r => baht(r.price) },
      { label: 'ผู้ติดต่อ', sortKey: 'contact_name', render: r => <span>{r.contact_name || '-'}<br /><span style={{ fontSize: 12, color: 'var(--text-2)' }}>{r.phone}{r.phone_verified ? ' ✓' : ''}</span></span> },
      { label: 'สถานะ', sortKey: 'status', render: r => <SBadge s={r.status} /> },
      { label: 'วันที่', sortKey: 'created_at', render: r => new Date(r.created_at).toLocaleDateString('th-TH') },
      { label: 'จัดการ', render: r => <button className="btn btn-sm btn-primary" onClick={() => setActive(r)}>ดู/จัดการ</button> },
    ];

    const ts = window.useTableSort(rows, 'created_at', 'desc', ['price']);

    const body = (
      <>
        {!embedded && <div className="page-header"><h1><i className="ph ph-tray-arrow-down" style={{marginRight:8,color:'#4A6079'}}></i>ทรัพย์ที่ส่งเข้ามา</h1></div>}
        <p className="muted" style={{ marginTop: embedded ? 0 : -8, marginBottom: 16 }}>ทรัพย์จากฟอร์มสาธารณะ — ตรวจสอบ แก้ไขให้สมบูรณ์ แล้วอนุมัติเพื่อเพิ่มทรัพย์จริง</p>
        <div className="tabs">
          {tabs.map(tb => <button key={tb.id} className={'tab' + (tab === tb.id ? ' active' : '')} onClick={() => setTab(tb.id)}>{tb.label}</button>)}
        </div>
        <div className="card" style={{ marginTop: 16 }}>
          <Table columns={cols} data={ts.sorted} loading={loading} empty="ยังไม่มีทรัพย์ที่ส่งเข้ามาจากฟอร์มสาธารณะ" emptyIcon="ph-tray-arrow-down" sort={ts.sort} onSort={ts.onSort} />
        </div>
        {active && <ReviewModal sub={active} onClose={() => setActive(null)} onDone={() => { setActive(null); load(); }} />}
      </>
    );
    return embedded ? body : <div className="page">{body}</div>;
  }

  function ReviewModal({ sub, onClose, onDone }) {
    const [f, setF] = useState({
      listing_type: sub.listing_type || 'sale',
      property_type: sub.property_type || 'house',
      title: sub.title || '', description: sub.description || '',
      province: sub.province || '', district: sub.district || '', address: sub.address || '',
      price: sub.price || '', appraised_value: sub.appraised_value || '', amount_needed: sub.amount_needed || '',
      contact_name: sub.contact_name || '', email: sub.email || '', note: sub.note || '',
    });
    const [busy, setBusy] = useState(false);
    const [msg, setMsg] = useState('');
    const [consentLogs, setConsentLogs] = useState(null); // หลักฐานการยินยอม PDPA
    const images = Array.isArray(sub.images) ? sub.images : [];
    const documents = Array.isArray(sub.document_keys) ? sub.document_keys : [];
    const isInvest = f.listing_type === 'mortgage' || f.listing_type === 'consignment';
    const locked = sub.status === 'approved' || sub.status === 'rejected';
    const set = (k, v) => setF(s => ({ ...s, [k]: v }));

    // ดึงหลักฐานการยินยอม PDPA ตามเบอร์ของผู้ส่ง
    async function loadConsent() {
      try {
        const r = await window.api.get('/admin/consent-logs?ref=' + encodeURIComponent(sub.phone || ''));
        setConsentLogs(Array.isArray(r.logs) ? r.logs : []);
      } catch (e) { setConsentLogs([]); }
    }

    // เปิดเอกสารสิทธิ์ (private) ผ่าน signed URL ชั่วคราว
    //   เปิดแท็บทันทีตอนคลิก (user gesture) แล้วค่อยชี้ URL — กัน popup blocker บล็อกตอน await
    async function openDoc(key) {
      const win = window.open('', '_blank');
      try {
        const r = await window.api.get('/admin/submissions/' + sub.id + '/document?key=' + encodeURIComponent(key));
        if (r && r.url) { if (win) win.location.href = r.url; else window.location.href = r.url; }
        else { if (win) win.close(); alert('เปิดเอกสารไม่สำเร็จ'); }
      } catch (e) { if (win) win.close(); alert('เปิดเอกสารไม่สำเร็จ: ' + e.message); }
    }

    async function save() {
      setBusy(true); setMsg('');
      try { await window.api.updateSubmission(sub.id, { ...f, images }); setMsg('บันทึกแล้ว ✅'); }
      catch (e) { setMsg('บันทึกไม่สำเร็จ: ' + e.message); }
      setBusy(false);
    }
    async function approve() {
      if (!confirm('อนุมัติและเพิ่มทรัพย์จริงขึ้นเว็บ?')) return;
      setBusy(true); setMsg('');
      try {
        await window.api.updateSubmission(sub.id, { ...f, images });
        const res = await window.api.approveSubmission(sub.id);
        alert('เพิ่มทรัพย์แล้ว: ' + (res.listing_code || res.listing_id) + '\nไปเติมรายละเอียด/ผลตอบแทนต่อได้ที่เมนู "จัดการทรัพย์"');
        onDone();
      } catch (e) { setMsg('อนุมัติไม่สำเร็จ: ' + e.message); setBusy(false); }
    }
    async function reject() {
      const reason = prompt('เหตุผลที่ปฏิเสธ (ไม่บังคับ):') ?? null;
      if (reason === null && !confirm('ปฏิเสธรายการนี้?')) return;
      setBusy(true); setMsg('');
      try { await window.api.rejectSubmission(sub.id, reason); onDone(); }
      catch (e) { setMsg('ไม่สำเร็จ: ' + e.message); setBusy(false); }
    }

    const Field = ({ label, k, type = 'text', area }) => (
      <div className="form-group" style={{ marginBottom: 12 }}>
        <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 5 }}>{label}</label>
        {area
          ? <textarea className="input" rows={2} value={f[k] || ''} disabled={locked} onChange={e => set(k, e.target.value)} />
          : <input className="input" type={type} value={f[k] || ''} disabled={locked} onChange={e => set(k, e.target.value)} />}
      </div>
    );

    return (
      <Modal title="ตรวจสอบทรัพย์ที่ส่งเข้ามา" onClose={onClose}>
        <div style={{ maxHeight: '72vh', overflowY: 'auto', margin: '-4px', padding: '4px' }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
          <SBadge s={sub.status} />
          <span style={{ fontWeight: 700, color: isInvest ? '#B5860B' : '#15976A' }}>{isInvest ? 'หมวดลงทุน' : 'หมวดทรัพย์ฝากขาย'}</span>
          <span style={{ color: 'var(--text-2)', fontSize: 13 }}>· {sub.phone}{sub.phone_verified ? ' (ยืนยันแล้ว ✓)' : ''}</span>
        </div>

        {locked && <div className="alert" style={{ background: '#F3F6FB', color: '#555' }}>
          รายการนี้{sub.status === 'approved' ? 'อนุมัติแล้ว' : 'ถูกปฏิเสธ'} — แก้ไขไม่ได้{sub.reject_reason ? (' · เหตุผล: ' + sub.reject_reason) : ''}
        </div>}

        {images.length > 0 && (
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
            {images.map((u, i) => <img key={i} src={u} alt="" style={{ width: 88, height: 66, objectFit: 'cover', borderRadius: 8, border: '1px solid var(--border)' }} />)}
          </div>
        )}

        {documents.length > 0 && (
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>เอกสารสิทธิ์ที่แนบมา ({documents.length}) — เปิดได้เฉพาะแอดมิน</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {documents.map((d, i) => (
                <button key={i} onClick={() => openDoc(d.key)} title="เปิดเอกสาร (ลิงก์ชั่วคราว)"
                  style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: '#F1F5FB', border: '1px solid #DDE6F2', borderRadius: 8, padding: '7px 11px', fontSize: 13, cursor: 'pointer', color: '#2A6BE0', maxWidth: 230 }}>
                  <i className="ph ph-file-text" style={{ fontSize: 16 }}></i>
                  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.name || 'เอกสาร'}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* หลักฐานการยินยอม PDPA */}
        <div style={{ marginBottom: 14 }}>
          {consentLogs === null ? (
            <button onClick={loadConsent} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: '#F1F5FB', border: '1px solid #DDE6F2', borderRadius: 8, padding: '6px 11px', fontSize: 12.5, cursor: 'pointer', color: '#2A6BE0' }}>
              <i className="ph ph-shield-check" style={{ fontSize: 15 }}></i> ดูหลักฐานการยินยอม (PDPA)
            </button>
          ) : consentLogs.length === 0 ? (
            <div style={{ fontSize: 12.5, color: 'var(--text-2)' }}>ไม่พบบันทึกการยินยอมสำหรับเบอร์นี้</div>
          ) : (
            <div style={{ border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden' }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--text-2)', background: '#F6F8FC', padding: '6px 10px' }}>หลักฐานการยินยอม PDPA ({consentLogs.length})</div>
              {consentLogs.map((l, i) => (
                <div key={i} style={{ fontSize: 12, padding: '8px 10px', borderTop: i ? '1px solid var(--border)' : 'none', lineHeight: 1.6 }}>
                  <div><b>{new Date(l.created_at).toLocaleString('th-TH')}</b> · {l.purpose} · {l.action}</div>
                  <div style={{ color: 'var(--text-2)' }}>เวอร์ชันข้อความ {l.consent_version} · นโยบาย {l.policy_version} · IP {l.ip_address || '-'}</div>
                  <div style={{ color: 'var(--text-2)', fontStyle: 'italic' }}>“{l.consent_text}”</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* สเปคที่ผู้ส่งกรอกมา (read-only) */}
        {(() => {
          const specs = [
            sub.bedrooms != null && `นอน ${sub.bedrooms}`,
            sub.bathrooms != null && `น้ำ ${sub.bathrooms}`,
            sub.area_sqm != null && `${sub.area_sqm} ตร.ม.`,
            sub.floors != null && `${sub.floors} ชั้น`,
            sub.floor_number != null && `ชั้นที่ ${sub.floor_number}`,
            (sub.land_rai || sub.land_ngan || sub.land_wa) && `${sub.land_rai || 0} ไร่ ${sub.land_ngan || 0} งาน ${sub.land_wa || 0} ตร.ว.`,
            sub.deed_type && `เอกสาร: ${sub.deed_type}`,
          ].filter(Boolean);
          return specs.length ? <div style={{ marginBottom: 14, fontSize: 13, color: '#555', background: '#F6F8FC', borderRadius: 8, padding: '8px 12px' }}><i className="ph ph-ruler" style={{marginRight:5}}></i>{specs.join(' · ')}</div> : null;
        })()}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
          <div className="form-group">
            <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 5 }}>ประเภทลิสต์ {isInvest ? '· ลงทุน' : '· ทรัพย์ฝากขาย'}</label>
            <select className="input" value={f.listing_type} disabled={locked} onChange={e => set('listing_type', e.target.value)}>
              <option value="sale">ขายขาด</option><option value="mortgage">จำนอง</option><option value="consignment">ขายฝาก</option>
            </select>
          </div>
          <div className="form-group">
            <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 5 }}>ประเภททรัพย์</label>
            <select className="input" value={f.property_type} disabled={locked} onChange={e => set('property_type', e.target.value)}>
              <option value="">เลือก</option>
              <option value="land_bare">ที่ดินเปล่า</option><option value="land_building">ที่ดิน + สิ่งปลูกสร้าง</option><option value="house_townhome">บ้าน / ทาวน์โฮม</option><option value="condo">คอนโด</option><option value="factory_warehouse">โรงงาน + โกดัง</option><option value="hotel_apartment">โรงแรม / หอพัก</option><option value="commercial">อาคารพาณิชย์</option>
            </select>
          </div>
        </div>

        <Field label="ชื่อ/หัวข้อทรัพย์" k="title" />
        <Field label="รายละเอียด" k="description" area />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="จังหวัด" k="province" />
          <Field label="เขต/อำเภอ" k="district" />
        </div>
        <Field label="ที่อยู่" k="address" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label={isInvest ? 'มูลค่าทรัพย์ (บาท)' : 'ราคาขาย (บาท)'} k="price" type="number" min="0" onKeyDown={window.blockNeg} />
          {isInvest && <Field label="มูลค่าประเมิน (บาท)" k="appraised_value" type="number" min="0" onKeyDown={window.blockNeg} />}
          {isInvest && <Field label="วงเงินที่ต้องการ (บาท)" k="amount_needed" type="number" min="0" onKeyDown={window.blockNeg} />}
          <Field label="ชื่อผู้ติดต่อ" k="contact_name" />
          <Field label="อีเมล" k="email" type="email" />
        </div>
        <Field label="หมายเหตุจากผู้ส่ง" k="note" area />

        {isInvest && !locked && <div className="alert" style={{ background: '#FFF8E8', color: '#8A6D1B' }}>
          <i className="ph ph-info" style={{marginRight:5}}></i>หมวดลงทุน: ระบบคำนวณ Risk Grade เบื้องต้นตอนอนุมัติ — ผลตอบแทน (%) ไปเติมที่หน้าแก้ทรัพย์หลังอนุมัติ
        </div>}

        {msg && <div style={{ marginTop: 10, color: msg.includes('ไม่') ? '#D8567A' : '#15976A', fontWeight: 600 }}>{msg}</div>}

        {!locked && (
          <div className="row gap-10" style={{ marginTop: 18, justifyContent: 'flex-end' }}>
            <button className="btn btn-danger" onClick={reject} disabled={busy}>ปฏิเสธ</button>
            <button className="btn btn-ghost" onClick={save} disabled={busy}>บันทึก</button>
            <button className="btn btn-success" onClick={approve} disabled={busy}>{busy ? '...' : <><i className="ph ph-check-circle" style={{marginRight:5}}></i>อนุมัติ → เพิ่มทรัพย์</>}</button>
          </div>
        )}
        </div>
      </Modal>
    );
  }

  window.SubmissionsPage = SubmissionsPage;
})();
