// ============ HR Integration Session ============
// อ่าน URL params จาก HR app แล้วบันทึกเป็น session สำหรับโหมดพนักงาน
// URL จาก HR: ?mode=employee&emp_id=EMP001&emp_name=สมชาย&branch=JE+BAR&from_hr=1

const HR_SESSION_KEY = 'jebar_hr_session';

function readHRSession() {
  try {
    const raw = sessionStorage.getItem(HR_SESSION_KEY);
    if (raw) return JSON.parse(raw);
  } catch(e) {}
  return null;
}

function initHRSession() {
  try {
    const qs = new URLSearchParams(window.location.search);
    const empId = qs.get('emp_id') || qs.get('empId') || '';
    const empNameRaw = qs.get('emp_name') || qs.get('empName') || '';
    const branchRaw = qs.get('branch') || '';
    const fromHR = qs.get('from_hr') === '1' || qs.get('fromHR') === '1';

    if (!empId && !fromHR) return null;

    const session = {
      empId,
      empName: empNameRaw,
      branch: branchRaw,
      fromHR,
      startedAt: new Date().toISOString(),
    };
    sessionStorage.setItem(HR_SESSION_KEY, JSON.stringify(session));
    return session;
  } catch(e) {}
  return null;
}

function getHRSession() {
  return readHRSession() || initHRSession();
}

// เพิ่ม createdBy/branch ลงใน event object ถ้าอยู่ในโหมดพนักงานที่มาจาก HR
function stampHRSession(obj) {
  const s = getHRSession();
  if (!s || !s.empId) return obj;
  return {
    ...obj,
    createdBy: s.empId,
    createdByName: s.empName || s.empId,
    branch: s.branch || obj.branch || '',
    source: 'hr-employee',
  };
}

// badge แสดงในแถบบนเมื่ออยู่ในโหมดพนักงานที่มาจาก HR
function HREmployeeBadge() {
  const s = React.useMemo(() => getHRSession(), []);
  if (!s || !s.empId) return null;
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: 6,
      padding: '4px 10px',
      borderRadius: 999,
      background: 'var(--accent-soft)',
      fontSize: 12.5,
      fontWeight: 600,
      color: 'var(--accent)',
      whiteSpace: 'nowrap',
    }}>
      <Icon name="user" size={14} />
      {s.empName || s.empId}
      {s.branch ? <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· {s.branch}</span> : null}
    </div>
  );
}

Object.assign(window, { getHRSession, stampHRSession, initHRSession, HREmployeeBadge });
