/* หน้าหลังบ้าน: คำขอใช้สิทธิเจ้าของข้อมูล (PDPA) — เข้าถึง/แก้ไข/ลบ/ถอนความยินยอม */
(function () {
  const { useState, useEffect } = React;

  const STATUS = {
    new: ['#B5860B', '#FBF0D0', 'ใหม่'],
    processing: ['#1F58C4', '#DCE9FC', 'กำลังดำเนินการ'],
    done: ['#15976A', '#DBF1E7', 'เสร็จสิ้น'],
    rejected: ['#D8567A', '#FBE4EC', 'ปฏิเสธ'],
  };
  const TYPE = {
    access: 'ขอเข้าถึง/สำเนา', rectify: 'ขอแก้ไข', erase: 'ขอลบข้อมูล',
    withdraw: 'ถอนความยินยอม', object: 'คัดค้าน', portability: 'ขอโอนย้าย', other: 'อื่นๆ',
  };
  function Badge({ map, k }) {
    const m = map[k] || ['#555', '#eee', k];
    return <span style={{ background: m[1], color: m[0], padding: '3px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap' }}>{m[2]}</span>;
  }

  function PrivacyRequestsPage() {
    const [tab, setTab] = useState('all');
    const [rows, setRows] = useState([]);
    const [loading, setLoading] = useState(true);
    const [active, setActive] = useState(null);
    const [note, setNote] = useState('');
    const [busy, setBusy] = useState(false);

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

    async function setStatus(id, status) {
      setBusy(true);
      try { await window.api.updatePrivacyRequest(id, { status, handler_note: note }); setActive(null); setNote(''); load(); }
      catch (e) { alert('อัปเดตไม่สำเร็จ: ' + e.message); }
      setBusy(false);
    }

    async function anonymize(r) {
      if (!confirm('ยืนยันลบ/ทำให้ข้อมูลไม่ระบุตัวตน?\n\nระบบจะ mask ชื่อ/เบอร์/อีเมล ที่ตรงกับ ' + (r.requester_email || r.requester_phone || '-') + ' ในทุกตาราง (ทรัพย์ที่ส่ง/lead/โฉนดแลกเงิน/ติดต่อ)\nการกระทำนี้ย้อนกลับไม่ได้')) return;
      setBusy(true);
      try {
        const d = await window.api.anonymizePrivacyRequest(r.id);
        alert('ลบ/ทำให้ไม่ระบุตัวตนแล้ว ' + (d.total || 0) + ' รายการ' + (d.summary && d.summary.length ? '\n' + d.summary.join('\n') : ''));
        setActive(null); setNote(''); load();
      } catch (e) { alert('ดำเนินการไม่สำเร็จ: ' + e.message); }
      setBusy(false);
    }

    const TABS = [['all', 'ทั้งหมด'], ['new', 'ใหม่'], ['processing', 'กำลังดำเนินการ'], ['done', 'เสร็จสิ้น'], ['rejected', 'ปฏิเสธ']];

    return (
      <div>
        <div className="page-head"><h1 className="page-title"><i className="ph ph-shield-check" style={{marginRight:8,color:'#4A6079'}}></i>คำขอใช้สิทธิ (PDPA)</h1>
          <span className="page-sub">คำขอเข้าถึง / แก้ไข / ลบข้อมูล / ถอนความยินยอม จากเจ้าของข้อมูล</span>
        </div>

        <div className="tabs" style={{ display: 'flex', gap: 8, margin: '12px 0 18px', flexWrap: 'wrap' }}>
          {TABS.map(([k, l]) => (
            <button key={k} className={'btn btn-sm ' + (tab === k ? 'btn-primary' : 'btn-soft')} onClick={() => setTab(k)}>{l}</button>
          ))}
        </div>

        {loading ? <div style={{ padding: 30, color: 'var(--text-2)' }}>กำลังโหลด...</div>
          : rows.length === 0 ? <div style={{ padding: 30, color: 'var(--text-2)' }}>ไม่มีคำขอในหมวดนี้</div>
          : (
            <div className="table-wrap">
              <table className="table">
                <thead><tr><th>วันที่</th><th>ประเภท</th><th>ผู้ขอ</th><th>ติดต่อ</th><th>สถานะ</th><th></th></tr></thead>
                <tbody>
                  {rows.map(r => (
                    <tr key={r.id}>
                      <td style={{ whiteSpace: 'nowrap' }}>{new Date(r.created_at).toLocaleString('th-TH')}</td>
                      <td><Badge map={TYPE_BADGE} k={r.request_type} /></td>
                      <td>{r.requester_name || r.user_name || '-'}</td>
                      <td style={{ fontSize: 12.5 }}>{r.requester_email || r.user_email || '-'}<br />{r.requester_phone || ''}</td>
                      <td><Badge map={STATUS} k={r.status} /></td>
                      <td><button className="btn btn-sm btn-soft" onClick={() => { setActive(r); setNote(r.handler_note || ''); }}>จัดการ</button></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

        {active && (
          <div onClick={() => setActive(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.45)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
            <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 12, padding: 22, width: 'min(94vw,560px)', maxHeight: '88vh', overflow: 'auto' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                <h3 style={{ fontSize: 17, fontWeight: 700 }}>คำขอ: {TYPE[active.request_type] || active.request_type}</h3>
                <button className="btn btn-sm" onClick={() => setActive(null)}>ปิด</button>
              </div>
              <div style={{ fontSize: 13.5, lineHeight: 1.8, marginBottom: 14 }}>
                <div><b>วันที่:</b> {new Date(active.created_at).toLocaleString('th-TH')}</div>
                <div><b>ผู้ขอ:</b> {active.requester_name || active.user_name || '-'}</div>
                <div><b>อีเมล:</b> {active.requester_email || active.user_email || '-'}</div>
                <div><b>เบอร์:</b> {active.requester_phone || '-'}</div>
                <div><b>IP:</b> {active.ip_address || '-'}</div>
                {active.detail && <div style={{ marginTop: 6, padding: '8px 12px', background: '#F6F8FC', borderRadius: 8 }}><b>รายละเอียด:</b><br />{active.detail}</div>}
              </div>
              <div className="form-group" style={{ marginBottom: 14 }}>
                <label>บันทึกการดำเนินการ</label>
                <textarea className="input" rows={3} value={note} onChange={e => setNote(e.target.value)} placeholder="เช่น ส่งสำเนาข้อมูลแล้ว / ลบข้อมูลเรียบร้อย / ติดต่อยืนยันตัวตน" />
              </div>
              {(active.request_type === 'erase' || active.request_type === 'withdraw') && (
                <div style={{ marginBottom: 12, padding: '10px 12px', background: '#FBE4EC', borderRadius: 8, border: '1px solid #F3C6D6' }}>
                  <div style={{ fontSize: 12.5, color: '#A33A5E', marginBottom: 8, fontWeight: 600 }}>คำขอลบข้อมูล — ทำให้ข้อมูลไม่ระบุตัวตน (ย้อนกลับไม่ได้)</div>
                  <button className="btn btn-sm" disabled={busy} style={{ background: '#D8567A', color: '#fff' }} onClick={() => anonymize(active)}>
                    <i className="ph ph-eraser" style={{ fontSize: 14, marginRight: 5 }}></i>ลบ / ทำให้ข้อมูลไม่ระบุตัวตน
                  </button>
                </div>
              )}
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
                <button className="btn btn-sm btn-soft" disabled={busy} onClick={() => setStatus(active.id, 'processing')}>กำลังดำเนินการ</button>
                <button className="btn btn-sm" disabled={busy} style={{ color: '#D8567A' }} onClick={() => setStatus(active.id, 'rejected')}>ปฏิเสธ</button>
                <button className="btn btn-sm btn-primary" disabled={busy} onClick={() => setStatus(active.id, 'done')}>ทำเสร็จแล้ว</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }

  // badge สีของประเภทคำขอ (ใช้สีกลาง)
  const TYPE_BADGE = Object.keys(TYPE).reduce((a, k) => { a[k] = ['#3C4657', '#EEF1F6', TYPE[k]]; return a; }, {});

  window.PrivacyRequestsPage = PrivacyRequestsPage;
})();
