import { useTodayZoneCheckIn } from '@/business/zone-checkin/hooks';
import { canPersistPersonalScopeResults } from '@/business/scope/selectors';
import { canZoneCheckIn, shouldNudgeZoneCheckIn } from '@/business/zone-checkin/selectors';
import { useScopeContext } from '@/shared/app/scope-context';
import { useAuth } from '@/contexts/useAuth';
import { DASHBOARD_ZONE_OPTIONS } from '@/shared/constants/dashboard';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import { ZoneCheckInCard } from '@/components/zone-checkin/ZoneCheckInCard';
import { ZoneCheckInReminder } from '@/components/zone-checkin/ZoneCheckInReminder';

/**
 * Self-contained daily Zone check-in (reminder banner + card) for the Zones of
 * Regulation page. Owns its own state via `useTodayZoneCheckIn`; rendered only
 * when the current user has `ZONE_CHECKIN`.
 */
export function ZoneCheckInSection() {
  const { user } = useAuth();
  const { ownTenant, selectedTenant } = useScopeContext();
  const canUseZoneCheckIn = canPersistPersonalScopeResults(ownTenant, selectedTenant) && canZoneCheckIn(user);
  const zone = useTodayZoneCheckIn({ enabled: canUseZoneCheckIn });

  if (!canUseZoneCheckIn) {
    return null;
  }

  const needsCheckIn = shouldNudgeZoneCheckIn(
    user,
    zone.isLoading,
    zone.isCheckedInToday,
  );

  return (
    <div className="space-y-4">
      {needsCheckIn && <ZoneCheckInReminder />}
      <ZoneCheckInCard
        zones={DASHBOARD_ZONE_OPTIONS}
        activeZone={zone.todayZone}
        needsCheckIn={needsCheckIn}
        isSaving={zone.isSaving}
        errorMessage={getOptionalErrorMessage(zone.error)}
        onCheckIn={async (selected) => { await zone.setZone(selected); }}
        onReset={async () => { await zone.clearToday(); }}
      />
    </div>
  );
}
