/* global React, window */
const { useState: useProfState, useEffect: useProfEffect } = React;

let _profSetId = null;
window.openProfile = (id) => { if (_profSetId && id != null) _profSetId(String(id)); };

function pfDateStr(d) { const p = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; }
function pfThai(iso) { if (!iso) return '—'; const [y, m, d] = iso.split('-'); return `${d}/${m}/${Number(y) + 543}`; }
function pfHM(min) { if (min == null) return '—'; const h = Math.floor(min / 60), m = Math.round(min % 60); return `${h} ชม.${m ? ' ' + m + ' น.' : ''}`; }
function pfTenure(hire) {
  if (!hire) return '—';
  try { const s = new Date(hire), n = new Date(); let mo = (n.getFullYear() - s.getFullYear()) * 12 + (n.getMonth() - s.getMonth()); if (n.getDate() < s.getDate()) mo--; if (mo < 0) return '—'; const y = Math.floor(mo / 12); return `${y ? y + ' ปี ' : ''}${mo % 12} เดือน`; } catch (e) { return '—'; }
}
const PF_STATUS = {
  present: { t: 'อยู่ในงาน', c: 'c-green' }, in_only: { t: 'ยังไม่ออกงาน', c: 'c-amber' },
  leave: { t: 'ลาหยุด', c: 'c-blue' }, absent: { t: 'ขาดงาน', c: 'c-coral' },
  holiday: { t: 'วันหยุด', c: 'c-gray' }, off: { t: 'วันหยุด', c: 'c-gray' },
};
const PF_PUNCH = ['เข้างาน', 'พักเบรก', 'ออกเบรก', 'ออกงาน'];

const PfIcon = ({ d, size = 15 }) => <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.7" style={{ flex: 'none' }}>{d}</svg>;
const IC = {
  phone: <path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3-8.6A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.6a2 2 0 0 1-.5 2.1L8 9.6a16 16 0 0 0 6 6l1.2-1.2a2 2 0 0 1 2.1-.5c.8.3 1.7.5 2.6.6a2 2 0 0 1 1.7 2z" />,
  mail: <><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 6-10 7L2 6" /></>,
  work: <><rect x="2" y="7" width="20" height="14" rx="2" /><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2" /></>,
  user: <><circle cx="12" cy="8" r="4" /><path d="M6 21v-1a6 6 0 0 1 12 0v1" /></>,
  clock: <><circle cx="12" cy="12" r="9" /><path d="M12 8v4l3 2" /></>,
  cal: <><rect x="3" y="4" width="18" height="17" rx="2.5" /><path d="M3 9h18M8 2v4M16 2v4" /></>,
  pin: <><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z" /><circle cx="12" cy="10" r="3" /></>,
};

function ProfileDrawer() {
  const [id, setId] = useProfState(null);
  const [emp, setEmp] = useProfState(null);
  const [day, setDay] = useProfState(null);
  const [date, setDate] = useProfState(() => pfDateStr(new Date()));
  const [loading, setLoading] = useProfState(false);
  const [lightbox, setLightbox] = useProfState(null);
  const role = (window.CURRENT_USER && window.CURRENT_USER.role) || 'employee';

  useProfEffect(() => { _profSetId = (v) => { setId(v); setDate(pfDateStr(new Date())); }; return () => { _profSetId = null; }; }, []);

  useProfEffect(() => {
    if (!id) { setEmp(null); return; }
    fetch('/api/employees/' + id, { credentials: 'include' }).then((r) => r.ok ? r.json() : null).then(setEmp).catch(() => {});
  }, [id]);

  useProfEffect(() => {
    if (!id) { setDay(null); return; }
    setLoading(true);
    fetch('/api/attendance/day-detail?date=' + date, { credentials: 'include' }).then((r) => r.ok ? r.json() : null)
      .then((dd) => { setDay(dd && dd.rows ? dd.rows.find((x) => String(x.employee_id) === String(id)) || null : null); setLoading(false); })
      .catch(() => setLoading(false));
  }, [id, date]);

  useProfEffect(() => {
    if (!id) return undefined;
    const onKey = (e) => { if (e.key === 'Escape') { if (lightbox) setLightbox(null); else setId(null); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [id, lightbox]);

  if (!id) return null;

  const shiftEmp = (window.SHIFTS || []).find((s) => s.id === (emp && emp.shift_id));
  const shiftName = (day && day.shift_name) || (shiftEmp && shiftEmp.name) || null;
  const shiftTime = shiftEmp && shiftEmp.start_time ? `${shiftEmp.start_time.slice(0, 5)} - ${(shiftEmp.end_time || '').slice(0, 5)}` : '';
  const name = emp ? `${emp.title ? emp.title + ' ' : ''}${emp.first_name || ''} ${emp.last_name || ''}`.trim() : '';
  const deptName = (emp && (emp.department_name || (window.DEPARTMENTS || []).find((d) => d.id === emp.department_id)?.name)) || '—';
  const photo = emp && emp.photo_url ? emp.photo_url : (id ? '/faces/' + id + '.jpg' : '/img/avatar-person.svg');
  const st = day ? (PF_STATUS[day.status] || { t: day.status, c: 'c-gray' }) : null;
  const punches = (day && day.punches) || [];
  const inScan = punches[0], outScan = punches.length > 1 ? punches[punches.length - 1] : null;
  const location = (day && day.location) || 'ออฟฟิศ';

  const shiftDate = (n) => { const d = new Date(date + 'T00:00:00'); d.setDate(d.getDate() + n); setDate(pfDateStr(d)); };

  const InfoRow = ({ icon, children }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 9, color: 'var(--ink-3)', fontSize: 12.5, minWidth: 0 }}>
      <span style={{ color: 'var(--ink-5)' }}><PfIcon d={icon} /></span>
      <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{children}</span>
    </div>
  );
  const SecTitle = ({ children }) => <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)', padding: '14px 0 10px', borderBottom: '1px solid var(--line)', marginBottom: 12 }}>{children}</div>;

  return (
    <>
      <div onClick={() => setId(null)} style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(15,23,42,.35)' }} />
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(440px,100vw)', zIndex: 301, background: 'var(--surface)', boxShadow: '-14px 0 40px rgba(15,23,42,.16)', display: 'flex', flexDirection: 'column', animation: 'osslide .25s ease' }}>
        {/* topbar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 20px', borderBottom: '1px solid var(--line)', flex: 'none' }}>
          <b style={{ fontFamily: 'var(--font-display)', fontSize: 16 }}>เวลาทำงาน</b>
          <button onClick={() => setId(null)} title="ปิด" style={{ background: 'var(--surface-2)', border: 0, width: 32, height: 32, borderRadius: '50%', cursor: 'pointer', color: 'var(--ink-4)', fontSize: 16 }}>✕</button>
        </div>

        <div style={{ overflowY: 'auto', padding: '18px 20px 28px' }}>
          {/* person header */}
          <div style={{ display: 'flex', gap: 14 }}>
            <img src={photo} alt="" onError={(e) => { e.target.src = '/img/avatar-person.svg'; }}
              style={{ width: 84, height: 84, borderRadius: '50%', objectFit: 'cover', flex: 'none', border: '1px solid var(--line)' }} />
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700, lineHeight: 1.2 }}>{name || (loading ? '…' : '—')}</div>
                <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>{id}</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-4)', margin: '2px 0 10px' }}>{deptName}</div>
              <div style={{ display: 'grid', gap: 7 }}>
                <InfoRow icon={IC.phone}>{emp && emp.phone ? emp.phone : '—'}</InfoRow>
                <InfoRow icon={IC.mail}>{emp && emp.email ? emp.email : '—'}</InfoRow>
                <InfoRow icon={IC.work}>{shiftName ? `${shiftName}${shiftTime ? ' · ' + shiftTime : ''}` : 'พนักงานทั่วไป'}</InfoRow>
                <InfoRow icon={IC.cal}>อายุงาน {pfTenure(emp && emp.hire_date)}</InfoRow>
              </div>
            </div>
          </div>

          {/* date range */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '18px 0 4px' }}>
            <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>ช่วงเวลา</span>
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 4, border: '1px solid var(--line)', borderRadius: 'var(--r-pill)', padding: '4px 6px' }}>
              <button onClick={() => shiftDate(-1)} style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--ink-4)', padding: '2px 6px', fontSize: 15 }}>‹</button>
              <span className="tnum" style={{ fontSize: 12.5, fontWeight: 600 }}>{pfThai(date)}</span>
              <button onClick={() => shiftDate(1)} style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--ink-4)', padding: '2px 6px', fontSize: 15 }}>›</button>
            </div>
          </div>

          {/* เวลาเข้า-ออกงาน */}
          <SecTitle>เวลาเข้า-ออกงาน</SecTitle>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
            {st && <span className={`gv-chip ${st.c}`}>{st.t}</span>}
            {day && day.late_min > 0 && <span className="gv-chip c-coral">สายเกินกำหนด {pfHM(day.late_min)}</span>}
            {day && day.ot_min > 0 && <span className="gv-chip c-blue">OT</span>}
          </div>
          {[['เข้างาน', inScan, 'var(--mint)'], ['ออกงาน', outScan, 'var(--primary)']].map(([lbl, sc, col]) => (
            <div key={lbl} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--line)' }}>
              <span style={{ width: 9, height: 9, borderRadius: '50%', background: col, flex: 'none' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600 }}>{lbl}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-5)' }}>{pfThai(date)}</div>
              </div>
              <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: sc ? 'var(--ink)' : 'var(--ink-5)' }}>{sc ? sc.time : '--:--'}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5, color: 'var(--ink-4)', fontSize: 11.5, minWidth: 70 }}>
                {sc && <><span style={{ color: 'var(--primary)' }}><PfIcon d={IC.pin} size={13} /></span>{location}</>}
              </div>
            </div>
          ))}

          {/* scan snapshots */}
          {punches.length > 0 && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-4)', marginBottom: 8 }}>ภาพสแกนใบหน้ายืนยันตัวตน</div>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                {punches.slice(0, 4).map((p, i) => (
                  <div key={i} style={{ textAlign: 'center' }}>
                    {p.snapshot_url
                      ? <img src={p.snapshot_url} alt="" onClick={() => setLightbox(p.snapshot_url)} style={{ width: 58, height: 58, borderRadius: 14, objectFit: 'cover', cursor: 'zoom-in', border: '1px solid var(--line)' }} />
                      : <div style={{ width: 58, height: 58, borderRadius: 14, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', color: 'var(--ink-5)', border: '1px solid var(--line)' }}><PfIcon d={<><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" /><circle cx="12" cy="13" r="4" /></>} size={18} /></div>}
                    <div style={{ fontSize: 10, color: 'var(--ink-5)', marginTop: 4 }}>{PF_PUNCH[i] || 'สแกน'}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* รายละเอียด */}
          <SecTitle>รายละเอียด</SecTitle>
          {[['กะการทำงาน', shiftName ? `${shiftName}${shiftTime ? ' (' + shiftTime + ')' : ''}` : 'ตามแผนก', IC.work],
            ['คะแนน', day ? Number(day.score).toFixed(2) : '—', IC.user],
            ['รวมทำงาน', day ? pfHM(day.work_min) : '—', IC.clock],
            ['โอที', day && day.ot_min ? pfHM(day.ot_min) : '—', IC.clock]].map(([k, v, ic]) => (
            <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', fontSize: 13 }}>
              <span style={{ color: 'var(--ink-5)' }}><PfIcon d={ic} /></span>
              <span style={{ color: 'var(--ink-4)' }}>{k}</span>
              <span style={{ marginLeft: 'auto', fontWeight: 600 }}>{v}</span>
            </div>
          ))}

          {/* คำขอ */}
          <SecTitle>คำขอ</SecTitle>
          <button className="gv-btn no" style={{ width: '100%' }} onClick={() => { setId(null); window.navigateTo && window.navigateTo('leave'); }}>＋ สร้างคำขอ (ลา / แก้เวลา)</button>

          {(role === 'admin' || role === 'hr') && (
            <button onClick={() => { setId(null); window.navigateTo && window.navigateTo('employee'); }} className="gv-btn ghost" style={{ width: '100%', marginTop: 10 }}>ไปหน้าจัดการพนักงาน</button>
          )}
        </div>
      </div>

      {lightbox && (
        <div onClick={() => setLightbox(null)} style={{ position: 'fixed', inset: 0, zIndex: 340, background: 'rgba(0,0,0,.82)', display: 'grid', placeItems: 'center', padding: 24 }}>
          <img src={lightbox} alt="" style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 16 }} />
        </div>
      )}
    </>
  );
}

window.ProfileModal = ProfileDrawer;
