// components/rinpo-avatar.jsx — single persistent bottom-right RINPO (store)

function RinpoAvatar() {
  const store = useStore();
  const route = useRoute();
  const [uiState, setUiState] = React.useState(
    (window.RinpoRuntime && window.RinpoRuntime.getState().uiState) || 'idle'
  );

  React.useEffect(() => {
    if (!window.RinpoRuntime) return undefined;
    return window.RinpoRuntime.subscribe(function (s) {
      setUiState(s.uiState || 'idle');
    });
  }, []);

  if (!window.RinpoAssets) return null;
  if (route.name === 'onboarding') return null;
  if (route.name === 'phone' && !store.isPhoneDesktop()) return null;
  if (store.state.phoneOpen && store.isPhoneDesktop()) return null;
  if (route.name === 'checkout') return null;

  const badge = store.cartCount() || store.notificationCount() || null;

  const open = () => {
    if (window.RinpoRuntime) {
      window.RinpoRuntime.setState('greeting');
      window.RinpoRuntime.open({ tab: 'apps', source: 'avatar', surface: 'store' });
    } else if (store.isPhoneDesktop()) {
      store.openPhoneOverlay('apps');
    } else {
      HAPRouter.nav('#/phone?tab=apps');
    }
  };

  return (
    <RinpoAvatarImage
      variant="fab"
      badge={badge}
      showPill
      state={uiState}
      interactive
      className="rinpo-fab rinpo-fab--pulse"
      asButton
      onClick={open}
      ariaLabel="Open RINADS PHONE"
    />
  );
}

window.RinpoAvatar = RinpoAvatar;
