// Dirty state guard — global mechanism to confirm before navigating away from
// a page with unsaved changes. Any page can set itself "dirty" via window.__setDirty(true).

window.__dirtyState = { isDirty: false, location: null, savePending: false };

/**
 * Mark current view as dirty (has unsaved changes).
 * `location` is a string label shown in the confirmation prompt (e.g. "BOQ Editor").
 */
window.__setDirty = function setDirty(dirty, location = null) {
  window.__dirtyState.isDirty = !!dirty;
  if (location) window.__dirtyState.location = location;
  // Re-render subscribers
  if (window.__dirtyListeners) {
    window.__dirtyListeners.forEach(fn => fn(window.__dirtyState));
  }
};

/**
 * Returns true if it's safe to navigate. If dirty, prompts the user and
 * resolves based on their choice. Sync function returning bool (uses confirm()).
 */
window.__confirmLeave = function confirmLeave(actionDescription = '') {
  if (!window.__dirtyState.isDirty) return true;
  const where = window.__dirtyState.location ? `(${window.__dirtyState.location})` : '';
  const msg = `⚠️ มีข้อมูลที่ยังไม่ได้บันทึก ${where}\n\n` +
              `${actionDescription || 'ออกจากหน้านี้?'}\n\n` +
              `กด "OK" เพื่อออกโดยไม่บันทึก\n` +
              `กด "Cancel" เพื่ออยู่ต่อ`;
  const ok = window.confirm(msg);
  if (ok) {
    window.__dirtyState.isDirty = false;
    if (window.__dirtyListeners) window.__dirtyListeners.forEach(fn => fn(window.__dirtyState));
  }
  return ok;
};

/**
 * Subscribe to dirty-state changes. Returns unsubscribe function.
 */
window.__subscribeDirty = function subscribeDirty(fn) {
  if (!window.__dirtyListeners) window.__dirtyListeners = new Set();
  window.__dirtyListeners.add(fn);
  return () => window.__dirtyListeners.delete(fn);
};

/**
 * React hook for using dirty state in a component.
 */
function useDirty() {
  const [state, setState] = useState(window.__dirtyState);
  useEffect(() => window.__subscribeDirty(s => setState({ ...s })), []);
  return state;
}

// Show a small floating "unsaved" badge when dirty
function DirtyIndicator() {
  const state = useDirty();
  if (!state.isDirty) return null;
  return (
    <div style={{
      position: "fixed", bottom: 18, left: "50%", transform: "translateX(-50%)",
      zIndex: 100,
      background: "linear-gradient(180deg, #f59e0b, #d97706)",
      color: "white",
      padding: "8px 16px",
      borderRadius: 12,
      fontSize: 12.5, fontWeight: 600,
      boxShadow: "0 8px 24px rgba(245,158,11,0.4)",
      display: "flex", alignItems: "center", gap: 8,
      pointerEvents: "none",
      animation: "fadeUp .3s ease",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: "white", animation: "pulseGlow 1.5s infinite" }} />
      มีข้อมูลที่ยังไม่บันทึก
    </div>
  );
}

// Prevent accidentally closing the window with unsaved changes
window.addEventListener('beforeunload', (e) => {
  if (window.__dirtyState?.isDirty) {
    e.preventDefault();
    e.returnValue = 'มีข้อมูลที่ยังไม่บันทึก';
    return e.returnValue;
  }
});
